首页 > 解决方案 > KNeighborsClassifier 中的 k 值

问题描述

我正在努力KKNeighborsClassifier.

这是我的iris数据集代码:

k_loop = np.arange(1,30)
k_scores = []
for k in k_loop:
    knn = KNeighborsClassifier(n_neighbors=k)
    cross_val = cross_val_score(knn, X, y, cv=10 , scoring='accuracy')
    k_scores.append(cross_val.mean())

我在每个循环中取了 cross_val_score 的平均值并绘制了它。

plt.style.use('fivethirtyeight')
plt.plot(k_loop, k_scores)
plt.show()

这就是结果。

线图

你可以看到在 to 之间时准确度k更高。1420

1)如何选择k的最佳值。

2) 有没有其他方法来计算和找到最佳价值K

3)任何其他改进建议也表示赞赏。我是新手ML

标签: pythonpython-3.xmachine-learningknn

解决方案


让我们首先定义什么是K

K是算法咨询以决定给定数据点属于哪个类别的选民数量。

换句话说,它用于K划分每个类的边界。这些边界将每个类别与其他类别隔离开来。

因此,边界随着 值的增加而变得更平滑K

所以从逻辑上讲,如果我们增加到K无穷,它最终将成为任何类的所有点,取决于总多数!。但是,这会导致所谓的高偏差(即欠拟合)。

相反,如果我们K只让等于1 ,那么训练样本的误差将始终为零。这是因为离任何训练数据点最近的点就是它自己。然而,我们最终会过度拟合边界(即高方差),因此它不能泛化任何新的和看不见的数据!

不幸的是,没有经验法则。选择在K某种程度上受最终应用程序和数据集的驱动。


建议的解决方案

使用GridSearchCV对估计器的指定参数值执行详尽搜索。所以我们用它来尝试找到 的最佳值K

对我来说,当我想设置 的最大阈值时,我没有超过每个类中的元素数量的最大类K,并且到目前为止它并没有让我失望(见后面的例子,看看我我在谈论

例子:

import numpy as np
from sklearn import svm, datasets
from sklearn.model_selection import GridSearchCV, RepeatedStratifiedKFold
from sklearn.neighbors import KNeighborsClassifier

iris = datasets.load_iris()
X, y = iris.data, iris.target
# get the max class with respect to the number of elements
max_class = np.max(np.bincount(y))
# you can add other parameters after doing your homework research
# for example, you can add 'algorithm' : ['auto', 'ball_tree', 'kd_tree', 'brute']
grid_param = {'n_neighbors': range(1, max_class)}
model = KNeighborsClassifier()
cv = RepeatedStratifiedKFold(n_splits=10, n_repeats=2)
clf = GridSearchCV(model, grid_param, cv=cv, scoring='accuracy')
clf.fit(X, y)
print("Best Estimator: \n{}\n".format(clf.best_estimator_))
print("Best Parameters: \n{}\n".format(clf.best_params_))
print("Best Score: \n{}\n".format(clf.best_score_))

结果

Best Estimator: 
KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=17, p=2,
           weights='uniform')

Best Parameters: 
{'n_neighbors': 17}

Best Score: 
0.98

关于更新RepeatedStratifiedKFold

简而言之,它KFold重复多次n_repeats的,为什么?因为它可能会降低偏差并在统计数据方面为您提供更好的估计。

此外Stratified,它试图确保每个类在每个测试折叠中大致相等(即每个折叠代表数据的所有)。


推荐阅读