KNN 分类(选择最佳的 K 值,并可视化模型精度与 n_neighbors 的关系)

python 复制代码
import matplotlib.pyplot as plt
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier


# 导入乳腺癌数据集
cancer = load_breast_cancer()

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(cancer.data, cancer.target, random_state=66, stratify=cancer.target)

training_accuracy = []
test_accuracy = []

# n_neighbors 取值范围为 [1, 10]
neighbors_settings = range(1, 11)

# 模型构建及模型评估
for n_neighbors in neighbors_settings:
    clf = KNeighborsClassifier(n_neighbors=n_neighbors)
    clf.fit(X_train, y_train)
    training_accuracy.append(clf.score(X_train, y_train))  # 记录训练精度
    test_accuracy.append(clf.score(X_test, y_test))  # 记录泛化精度

# 打印不同的 n_neighbors 值对应的训练精度和泛化精度 
neighbor_dict = {}
for n_neighbors in neighbors_settings:
    neighbor_dict[n_neighbors] = [training_accuracy[n_neighbors - 1], test_accuracy[n_neighbors - 1]]
print(neighbor_dict)

# 可视化模型精度与 n_neighbors 的关系
plt.plot(neighbors_settings, training_accuracy, label='training_accuracy')
plt.plot(neighbors_settings, test_accuracy, label='test_accuracy')
plt.xlabel('n_neighbors')
plt.ylabel('Accuracy')
plt.legend()
plt.show()
---------
{1: [1.0, 0.9020979020979021], 
 2: [0.9765258215962441, 0.8881118881118881], 
 3: [0.9577464788732394, 0.9230769230769231], 
 4: [0.9553990610328639, 0.9230769230769231], 
 5: [0.9483568075117371, 0.9230769230769231], 
 6: [0.9460093896713615, 0.9370629370629371], 
 7: [0.9436619718309859, 0.9300699300699301], 
 8: [0.9413145539906104, 0.9300699300699301], 
 9: [0.9342723004694836, 0.916083916083916], 
 10: [0.9389671361502347, 0.916083916083916]}
相关推荐
美狐美颜sdk37 分钟前
直播美颜SDK特效功能实战:从API调用到效果调优的全过程
人工智能·1024程序员节·美颜sdk·直播美颜sdk·第三方美颜sdk
sali-tec4 小时前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
梦想画家4 小时前
基于PyTorch的时间序列异常检测管道构建指南
人工智能·pytorch·python
Elastic 中国社区官方博客5 小时前
在 Elasticsearch 中使用 Mistral Chat completions 进行上下文工程
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
一碗绿豆汤5 小时前
机器学习第二阶段
人工智能·机器学习
用什么都重名5 小时前
DeepSeek-OCR 深度解析
人工智能·ocr·deepseek-ocr
河南骏6 小时前
RAG_检索进阶
人工智能·深度学习
灯火不休时7 小时前
95%准确率!CNN交通标志识别系统开源
人工智能·python·深度学习·神经网络·cnn·tensorflow
mit6.8247 小时前
[手机AI开发sdk] Aid_code IDE | PC浏览器同步访问
ide·人工智能·智能手机
deephub7 小时前
FastMCP 入门:用 Python 快速搭建 MCP 服务器接入 LLM
服务器·人工智能·python·大语言模型·mcp