使用knn模型对sklearn 鸢尾花 数据集进行分类,并给出代码
时间: 2023-12-29 07:02:29 浏览: 88
python KNN算法实现鸢尾花数据集分类
好的,下面是使用KNN模型对鸢尾花数据集进行分类的代码:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
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)
# 创建KNN模型,设置k值为3
knn = KNeighborsClassifier(n_neighbors=3)
# 在训练集上拟合KNN模型
knn.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = knn.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
```
输出结果为:
```
Accuracy: 97.78%
```
阅读全文