鸢尾花分类逻辑回归Python带图
时间: 2024-05-08 16:13:52 浏览: 124
逻辑回归-鸢尾花数据集分类
鸢尾花分类是机器学习中的一个经典问题,逻辑回归是其中一种常用的分类算法。下面是使用Python实现鸢尾花分类逻辑回归的步骤:
1. 导入必要的库
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
```
2. 加载数据
```python
iris = load_iris()
X = iris.data[:, :2] # 只选择前两个特征
y = iris.target
```
3. 数据可视化
```python
plt.scatter(X[:, 0], X[:, 1], c=y)
plt.xlabel('Sepal Length')
plt.ylabel('Sepal Width')
plt.show()
```
4. 划分训练集和测试集
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
```
5. 训练模型
```python
clf = LogisticRegression(solver='liblinear', multi_class='auto')
clf.fit(X_train, y_train)
```
6. 预测结果
```python
y_pred = clf.predict(X_test)
```
7. 分类报告
```python
print(classification_report(y_test, y_pred))
```
下图展示了使用逻辑回归分类器对鸢尾花数据集进行分类的结果:
![image.png](https://img-blog.csdnimg.cn/20210911173502598.png)
阅读全文