使用knn模型对sklearn 鸢尾花 数据集进行分类。
时间: 2023-12-29 19:03:19 浏览: 64
python KNN算法实现鸢尾花数据集分类
好的,下面是对sklearn鸢尾花数据集使用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模型并训练
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, y_train)
# 预测测试集并计算准确率
y_pred = knn.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
结果输出:
```
Accuracy: 1.0
```
说明使用KNN模型对该数据集进行分类时,可以达到100%的准确率。
阅读全文