用KNN实验一分类的代码
时间: 2024-10-10 08:14:05 浏览: 36
使用K-近邻算法(K-Nearest Neighbors, KNN)进行简单的一分类任务,比如在Python的scikit-learn库中是一个常见的示例。以下是基本的代码框架:
```python
# 导入所需的库
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np
# 加载数据集(这里以鸢尾花数据集为例)
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=5) # 通常选择k值为奇数,例如5或7
# 使用训练数据拟合模型
knn.fit(X_train, y_train)
# 预测测试集
predictions = knn.predict(X_test)
# 打印预测结果
print("Predictions:", predictions)
# 评估模型性能
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(y_test, predictions)
print("Accuracy:", accuracy)
阅读全文