写一段代码,生成或从sklearn.datasets中读取任意数据集(例如鸢尾花数据 iris ),用KNN和决策树两个模型分别训练和测试
时间: 2024-05-05 12:18:53 浏览: 111
下面是生成iris数据集并使用KNN和决策树进行训练和测试的Python代码:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 训练KNN模型
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
# 测试KNN模型
knn_accuracy = knn.score(X_test, y_test)
print("KNN accuracy:", knn_accuracy)
# 训练决策树模型
dt = DecisionTreeClassifier()
dt.fit(X_train, y_train)
# 测试决策树模型
dt_accuracy = dt.score(X_test, y_test)
print("Decision Tree accuracy:", dt_accuracy)
```
这段代码会生成iris数据集并将其划分为训练集和测试集。然后分别使用KNN和决策树模型进行训练和测试,并输出模型的准确率。
阅读全文