【问题标题】:Why does best_params_ in GridSearchCV ignore the variance?为什么 GridSearchCV 中的 best_params_ 会忽略方差?
【发布时间】: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_scorestd_test_score 是最优的。但是 best_param_ 返回 k=1。

【问题讨论】:

  • 介意发布您的代码吗?我曾经在威斯康星州乳腺癌数据集上测试过 GridSearchCV,它工作得非常好。
  • @GarbageCollector 为了重现该问题,我不得不稍微尝试一下random_state。它只在某些情况下出现。
  • 创建一个自定义评分函数,以您想要的方式结合均值和标准。您甚至可以在计算中包含 k 的值。
  • @BertKellerman 感谢您的建议,但这实际上不是我的问题。我试图澄清它。

标签: python machine-learning scikit-learn cross-validation grid-search


【解决方案1】:

来自GridSearchCV source

    # Find the best parameters by comparing on the mean validation score:
    # note that `sorted` is deterministic in the way it breaks ties
    best = sorted(grid_scores, key=lambda x: x.mean_validation_score,
                  reverse=True)[0]

它按 mean_val 分数排序,就是这样。 sorted() 保留了关系的现有顺序,因此在这种情况下 k=1 是最好的。

我同意你的想法,并认为可以提交 PR 以更好地打破平局。

【讨论】:

  • 感谢您的回答。所以没有什么特殊原因为什么要忽略一般的方差?
  • 他们可能是为了满足最广泛的用例而不是为用户做出这些决定。例如,在某些情况下,假设您有足够好的准确度,预测时间将是最重要的指标。在其他情况下,训练时间可能更重要。
【解决方案2】:

在 Grid Search 中,cv_results_ 提供 std_test_score 是分数的标准差。由此您可以通过平方来计算方差误差

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多