鸢尾花分类python
时间: 2023-10-12 17:18:13 浏览: 201
基于逻辑回归的鸢尾花二分类实验python源码+数据集+详细注释.zip
5星 · 资源好评率100%
以下是使用python对鸢尾花数据集进行分类的示例代码:
```python
# 导入所需的库
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
iris = load_iris()
# 将数据集转换为DataFrame格式
df = pd.DataFrame(data = np.c_[iris['data'], iris['target']], columns = iris['feature_names'] + ['target'])
# 划分数据集为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(df[iris.feature_names], df['target'], test_size = 0.3, random_state = 0)
# 训练决策树分类器
dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
# 使用测试集进行预测
y_pred = dtc.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
输出:
```
Accuracy: 0.9777777777777777
```
这里使用了决策树分类器对数据进行分类,并使用准确率作为评估指标。根据输出结果,我们获得了97.78%的准确率,说明这个模型能够很好地对鸢尾花数据进行分类。
阅读全文