使用鸢尾花数据集来做knn的python代码实例
时间: 2024-09-19 20:10:33 浏览: 47
当然可以。使用Python的scikit-learn库进行KNN(K-Nearest Neighbors,最近邻算法)分类,以Iris(鸢尾花)数据集为例,首先需要导入所需的库并加载数据,然后训练模型、进行预测和评估性能。这是一个基本的步骤:
```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.2, random_state=42)
# 创建KNN分类器,设置k值为3(可以根据需求调整)
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)
#
阅读全文