KNN预测鸢尾花类别Python代码
时间: 2023-05-18 18:03:59 浏览: 86
python机器学习入门,KNN鸢尾花分类
5星 · 资源好评率100%
以下是KNN预测鸢尾花类别的Python代码:
```python
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
# 加载数据集
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.2, random_state=42)
# 创建KNN分类器
knn = KNeighborsClassifier(n_neighbors=3)
# 训练模型
knn.fit(X_train, y_train)
# 预测测试集
y_pred = knn.predict(X_test)
# 输出准确率
print("Accuracy:", knn.score(X_test, y_test))
```
注意:这段代码需要安装scikit-learn库。
阅读全文