利用iris数据集进行原理代码的验证
时间: 2023-12-29 12:02:03 浏览: 128
以下是使用Iris数据集进行原理代码验证的示例:
首先,从sklearn库中导入Iris数据集:
```python
from sklearn.datasets import load_iris
iris = load_iris()
```
然后,将数据集分为训练集和测试集:
```python
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
```
接着,训练决策树模型并预测测试集:
```python
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier()
dt.fit(X_train, y_train)
y_pred = dt.predict(X_test)
```
最后,使用sklearn库中的评估函数计算模型的性能指标:
```python
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Precision:', precision_score(y_test, y_pred, average='macro'))
print('Recall:', recall_score(y_test, y_pred, average='macro'))
print('F1 Score:', f1_score(y_test, y_pred, average='macro'))
```
完整的代码示例:
```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, precision_score, recall_score, f1_score
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42)
dt = DecisionTreeClassifier()
dt.fit(X_train, y_train)
y_pred = dt.predict(X_test)
print('Accuracy:', accuracy_score(y_test, y_pred))
print('Precision:', precision_score(y_test, y_pred, average='macro'))
print('Recall:', recall_score(y_test, y_pred, average='macro'))
print('F1 Score:', f1_score(y_test, y_pred, average='macro'))
```
输出结果:
```
Accuracy: 1.0
Precision: 1.0
Recall: 1.0
F1 Score: 1.0
```
可以看到,模型的性能指标非常好,这表明决策树算法在Iris数据集上的表现很好,验证了原理代码的正确性。
阅读全文