python - KNeighborsClassifier 中的 k 值
问题描述
我正在努力K
为KNeighborsClassifier
.
这是我的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
更高。14
20
1)如何选择k的最佳值。
2) 有没有其他方法来计算和找到最佳价值K
?
3)任何其他改进建议也表示赞赏。我是新手ML
解决方案
让我们首先定义什么是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
,它试图确保每个类在每个测试折叠中大致相等(即每个折叠代表数据的所有层)。
推荐阅读
- c++ - 为什么我不能 std::bit_cast 字符串文字的内容?
- c++ - 如何在 C++ 中重载“删除”运算符以打印使用它的文件的行和名称?
- excel - 如何调整左侧和右侧之间的数据大小以使它们相同?
- java - 我们如何将数据库驱动程序保留在工作之外
- python - 使用 pyinstaller 将我的程序变成 exe 后,selenium 停止工作
- c# - 使用 Azure.Messaging.ServiceBus.Administration 创建 ServiceBus 队列时出错
- python - 关于读取html文件时某些字符串飞起来的原因
- node.js - 获取 ForbiddenError:带有 multer 的无效 csrf 令牌在本地添加到图像上传路由器
- mongodb - 在 mongodb 中搜索拼写错误的单词 .net core 3
- c - 在C中将结构实例转换为另一种类型的正确方法是什么