knn和决策树的鸢尾花
时间: 2023-08-07 15:30:20 浏览: 149
好的,以下是基于KNN和决策树算法对鸢尾花数据集进行分类的示例代码:
```python
# 导入鸢尾花数据集
from sklearn.datasets import load_iris
iris = load_iris()
# 划分训练集和测试集
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)
# KNN算法分类
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier()
knn.fit(X_train, y_train)
knn_pred = knn.predict(X_test)
# 决策树算法分类
from sklearn.tree import DecisionTreeClassifier
dtc = DecisionTreeClassifier()
dtc.fit(X_train, y_train)
dtc_pred = dtc.predict(X_test)
# 计算分类准确率
from sklearn.metrics import accuracy_score
knn_acc = accuracy_score(y_test, knn_pred)
dtc_acc = accuracy_score(y_test, dtc_pred)
print("KNN算法准确率:", knn_acc)
print("决策树算法准确率:", dtc_acc)
```
运行上述代码,可以得到KNN算法和决策树算法在鸢尾花数据集上的分类准确率。可以根据准确率等指标进行比较和分析,选择最适合实际问题的算法。
阅读全文