无法重现 GridSearchCV 的结果?

数据挖掘 机器学习 Python 超参数
2022-02-18 12:40:30

我正在尝试使用 GridSearchCV 为 KnearestClassifier 找到优化的 n_neighbors 值。我能够获得优化的参数,但是当我在分类器中输入这些参数时,结果与 GridSearchCVs 的最佳结果不匹配。

clf = KNeighborsClassifier(n_neighbors=15, weights='uniform')


clf.fit(features_train, labels_train)

print('Score using optimized parameters: {}'.format(clf.score(features_test,       labels_test)))


params = {'n_neighbors':[1,10,15,20,25,30,35,40,45,50,60,70,80,90,100],    'weights':['uniform', 'distance']}
grid = GridSearchCV(clf, params, cv=10, )
grid.fit(features_train, labels_train)

print('Optimized Parameters:{}'.format(grid.best_params_))
print('Best Score from GridsearchCV parameters{}'.format(grid.best_score_))

输出:

使用优化参数得分:0.928

优化参数:{'n_neighbors': 15, 'weights': 'uniform'}

GridsearchCV 参数的最佳分数:0.962666666667

1个回答

GridsearchCV 的分数有偏差。您可以使用交叉验证来估计准确性或选择超参数;但不是两者兼而有之。如果您使用交叉验证来选择超参数的最佳选择,通过测量每个可能选项的准确性,您选择的选项的准确性往往会高估您在测试集上看到的准确性。

为避免这种偏差,请选择单独的保留验证集来估计所选参数的准确性,或使用嵌套交叉验证(或 scikit-learn Pipeline)。

请参阅https://datascience.stackexchange.com/a/17835/8560