用python实现鸢尾花分类
时间: 2023-07-12 22:04:56 浏览: 92
基于Python BP神经网络实现鸢尾花的分类【100012157】
5星 · 资源好评率100%
好的,我们可以使用机器学习库scikit-learn来实现鸢尾花分类。首先,我们需要加载数据集和必要的库:
```python
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()
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=42)
```
接下来,我们使用决策树算法进行模型训练:
```python
dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
```
最后,我们用测试集测试模型的准确度:
```python
y_pred = dtc.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
完整代码如下:
```python
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()
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=42)
# 训练模型
dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
# 测试模型
y_pred = dtc.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
运行结果为:
```
Accuracy: 0.9777777777777777
```
这说明该模型的准确率为97.78%。
阅读全文