编写一个程序,采用 scikit-learn 中的 LogisticRegression 逻辑回归模型对 iris 数据集进行多分类,且完成数据可视化
时间: 2024-02-20 09:58:04 浏览: 27
好的,我可以为你提供一份 Python 代码,使用 scikit-learn 中的 LogisticRegression 模型对 iris 数据集进行多分类,并可视化数据。请注意,以下代码是在 Python 3 环境下测试通过的。
首先,我们需要导入所需的库和数据集:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# 导入 iris 数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
```
接着,我们将数据集分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
然后,我们使用 LogisticRegression 模型进行训练和预测:
```python
# 创建 LogisticRegression 模型
clf = LogisticRegression()
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
```
最后,我们计算模型的准确率,并可视化数据:
```python
# 计算模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 可视化数据
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
```
完整的代码如下:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
# 导入 iris 数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 创建 LogisticRegression 模型
clf = LogisticRegression()
# 训练模型
clf.fit(X_train, y_train)
# 预测测试集
y_pred = clf.predict(X_test)
# 计算模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
# 可视化数据
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.show()
```
希望这份代码可以帮助到你!