Python KNN 学习曲线

学习曲线的目的是选择更好的模型参数。以最近邻算法为例,选取最近的多少个数据点,才能达到最优。可以控制训练集不动,调整最近的点的个数,绘制学习曲线。

import matplotlib.pyplot as plt

score = []
krange=range(1,21) # K值取值范围
for i in krange:
    clf=KNN(n_neighbors=i)
    clf=clf.fit(Xtrain,Ytrain)
    score.append(clf.score(Xtest,Ytest))
plt.plot(krange, score)

结果:

可以找出最大值所在的索引,找出最佳的k值选择点:

bestindex=score.index(max(score))
print(bestindex+1)
print(score[bestindex])

输出:

8
0.935672514619883

猜你喜欢

转载自www.cnblogs.com/heenhui2016/p/10986869.html