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]}
相关推荐
m0_626535204 分钟前
MRR(Mean Reciprocal Rank)和 NDCG(Normalized Discounted Cumulative Gain)
人工智能·机器学习
长和信泰光伏储能5 分钟前
探索未来能源:光伏储能技术解析
大数据·人工智能·能源
寻道码路7 分钟前
LangChain4j Java AI 应用开发实战(二十六):多模型集成策略 —— OpenAI、DeepSeek、阿里百炼混合使用
java·开发语言·人工智能·ai
直接冲冲冲12 分钟前
65-批量归一化
人工智能·深度学习·计算机视觉
树獭非懒12 分钟前
六、Plan-and-Solve智能体:学会三思而后行
人工智能·llm·agent
武子康14 分钟前
调查研究-214 OpenAI:Agent 不是更聪明的聊天框,而是新的工作组织方式
人工智能·openai·agent
火山引擎开发者社区15 分钟前
告别手动翻资料:用 Agent Plan 搞定销售档案与问答
人工智能
鹰影4716 分钟前
一款AI笔记助手和远程同步的markdown笔记idea-note
人工智能·笔记·rust·typescript·react
城事漫游Molly20 分钟前
如何写出有说服力的研究论文Introduction——论证框架切入法
人工智能·论文写作·ai for science·博士生必读
行业研究员21 分钟前
解决方案 | 腾讯云天御金融反电诈解决方案
人工智能·金融·腾讯云·金融反电诈·双模反诈