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]}
相关推荐
tedcloud12310 分钟前
UI-TARS-desktop部署教程:构建AI桌面自动化系统
服务器·前端·人工智能·ui·自动化·github
曦月逸霜3 小时前
啥是RAG 它能干什么?
人工智能·python·机器学习
AI医影跨模态组学3 小时前
Lancet Digit Health(IF=24.1)广东省人民医院刘再毅&南方医科大学南方医院梁莉等团队:基于可解释深度学习模型预测胶质瘤分子改变
人工智能·深度学习·论文·医学·医学影像·影像组学
应用市场3 小时前
AI 编程助手三强争霸(2026 版):Claude、Gemini、GPT 各自擅长什么?
人工智能·gpt
AC赳赳老秦3 小时前
供应链专员提效:OpenClaw自动跟踪物流信息、更新库存数据,异常自动提醒
java·大数据·服务器·数据库·人工智能·自动化·openclaw
脑极体3 小时前
从Token消耗到DAA增长,AI价值标尺正在重构
人工智能·重构
csdn小瓯3 小时前
LangGraph自适应工作流路由机制:从关键词匹配到智能决策的完整实现
人工智能·fastapi·langgraph
QYR-分析4 小时前
高功率飞秒激光器行业发展现状、市场机遇及未来趋势分析
大数据·人工智能
AI医影跨模态组学4 小时前
J Clin Oncol(IF=43.4)美国Cedars-Sinai医学中心等团队:基于计算组织学人工智能的晚期胰腺癌化疗选择预测性生物标志物的开发与验证
人工智能·机器学习·论文·医学·医学影像·影像组学
SimpleLearingAI4 小时前
聚类算法详解
算法·数据挖掘·聚类