写python中利用KNN进行分类实验,通过调整参数K,对算法性能指标包括准确率、精确率、召回率、F1分数进行比较的代码
时间: 2024-06-12 08:09:25 浏览: 96
在python中利用KNN实现对iris进行分类的方法
以下是利用KNN进行分类实验并比较性能指标的Python代码示例:
```python
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.model_selection import train_test_split
# 加载数据集
# X为特征数据,y为目标数据
X, y = load_dataset()
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 初始化KNN分类器
knn = KNeighborsClassifier()
# 调整参数K的范围
k_values = [3, 5, 7, 9]
# 初始化性能指标列表
accuracy_scores = []
precision_scores = []
recall_scores = []
f1_scores = []
# 对每个K值进行实验并计算性能指标
for k in k_values:
# 设置KNN的K值
knn.n_neighbors = k
# 拟合训练数据
knn.fit(X_train, y_train)
# 预测测试数据
y_pred = knn.predict(X_test)
# 计算准确率、精确率、召回率和F1分数
accuracy = accuracy_score(y_test, y_pred)
precision = precision_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# 将结果添加到性能指标列表中
accuracy_scores.append(accuracy)
precision_scores.append(precision)
recall_scores.append(recall)
f1_scores.append(f1)
# 打印各个K值对应的性能指标结果
for i, k in enumerate(k_values):
print(f"For K = {k}:")
print(f"Accuracy: {accuracy_scores[i]}")
print(f"Precision: {precision_scores[i]}")
print(f"Recall: {recall_scores[i]}")
print(f"F1 Score: {f1_scores[i]}")
print()
```
阅读全文