【发布时间】:2018-05-31 01:34:37
【问题描述】:
GridSearchCV 中的best_param_ 的documentation 状态:
best_params_: 字典在保留数据上给出最佳结果的参数设置。
据此,我假设“最佳结果”是指在我的 k-folds 上的最佳分数(最高准确度/最低错误)和最低方差。
但是,我们在cv_results_ 中看到的情况并非如此:
这里best_param_ 返回k=5 而不是k=9 其中mean_test_score 和方差将是最佳的。
我知道我可以使用cv_results_ 的输出实现我自己的评分函数或我自己的best_param 函数。但是,首先不考虑方差的原因是什么?
我在这种情况下通过将 KNN 应用于具有 70% 训练拆分和 3 倍交叉验证的 iris 数据集。
编辑:示例代码:
import numpy as np
import pandas as pd
from sklearn import neighbors
from sklearn import model_selection
from sklearn import datasets
X = datasets.load_iris().data
y = datasets.load_iris().target
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, train_size=0.7, test_size=0.3, random_state=62)
knn_model = neighbors.KNeighborsClassifier()
param_grid = [{"n_neighbors" : np.arange(1, 31, 2)}]
grid_search = model_selection.GridSearchCV(knn_model, param_grid, cv=3, return_train_score=False)
grid_search.fit(X_train, y_train.ravel())
results = pd.DataFrame(grid_search.cv_results_)
k_opt = grid_search.best_params_.get("n_neighbors")
print("Value returned by best_param_:",k_opt)
results.head(6)
它生成的表格与上图不同,但情况相同:对于 k=5,mean_test_score 和 std_test_score 是最优的。但是 best_param_ 返回 k=1。
【问题讨论】:
-
介意发布您的代码吗?我曾经在威斯康星州乳腺癌数据集上测试过 GridSearchCV,它工作得非常好。
-
@GarbageCollector 为了重现该问题,我不得不稍微尝试一下
random_state。它只在某些情况下出现。 -
创建一个自定义评分函数,以您想要的方式结合均值和标准。您甚至可以在计算中包含 k 的值。
-
@BertKellerman 感谢您的建议,但这实际上不是我的问题。我试图澄清它。
标签: python machine-learning scikit-learn cross-validation grid-search