【问题标题】:GridSearchCV giving score from the best estimator different from the one indicated in refit parameterGridSearchCV 给出的分数来自与 refit 参数中指示的不同的最佳估计器
【发布时间】:2021-05-12 23:11:27
【问题描述】:

我正在使用 GridSearchCV 进行超参数优化

scoring_functions = {'mcc': make_scorer(matthews_corrcoef), 'accuracy': make_scorer(accuracy_score), 'balanced_accuracy': make_scorer(balanced_accuracy_score)}

grid_search = GridSearchCV(pipeline, param_grid=grid, scoring=scoring_functions, n_jobs=-1, cv=splitter, refit='mcc')

我将 refit 参数设置为 'mcc',因此我希望 GridSearchCV 选择最佳模型来最大化该指标。然后我计算一些分数

preds = best_model.predict(test_df)
metrics['accuracy'] = round(accuracy_score(test_labels, preds),3)
metrics['balanced_accuracy'] = round(balanced_accuracy_score(test_labels, preds),3)
metrics['mcc'] = round(matthews_corrcoef(test_labels, preds),3)

我得到了这些结果

"accuracy": 0.891, "balanced_accuracy": 0.723, "mcc": 0.871

现在,如果我这样做是为了在同一个测试集上获得模型的分数(不是先计算预测),就像这样

best_model = grid_search.best_estimator_
score = best_model.score(test_df, test_labels)

我得到的分数是这样的

"score": 0.891

如您所见,这是准确度,而不是 mcc 分数。根据 score 函数的文档,它说

返回给定数据的分数,如果估计器已经过调整。

这使用由提供的评分定义的分数,以及 best_estimator_.score 方法,否则。

我没有正确理解。我想如果我像我在 GridSearchCV 中使用 refit 参数指定的那样改装模型,结果应该是用于改装模型的评分函数?我错过了什么吗?

【问题讨论】:

  • 你的best_estimator_是什么模型,例如随机森林、knn...?
  • 随机森林我用 random_state 种子在管道上传递它,所以结果不应该改变

标签: python-3.x scikit-learn scoring gridsearchcv


【解决方案1】:

当您访问属性best_estimator_ 时,您将进入底层基础模型,忽略您对GridSearchCV 对象所做的所有设置:

best_model = grid_search.best_estimator_
score = best_model.score(test_df, test_labels)

您应该改用grid_search.score(),并且通常与该对象进行交互。例如预测时,使用grid_search.predict()

这些方法的签名与标准 Estimator 的签名相同(拟合、预测、得分等)。

您可以使用底层模型,但它不一定会继承您对网格搜索对象本身所做的配置。

【讨论】:

  • 好的谢谢,我会试试的。但是,如果您没有使用在交叉验证期间找到的最佳估计器,那么拥有 best_estimator_ 对象的目的是什么?我会报告回来看看它是否有效。如果这行得通,它现在将为我节省很多额外的工作。
  • @Atirag 正是不需要恢复到grid_search.best_estimator_,并且能够在grid_search对象本身的级别上完成这项工作.这里确实使用了best_estimator_(注意你得到了相同的精度),但是它的.score 方法对grid_search 中使用的其他评分方法一无所知。
猜你喜欢
  • 2022-07-19
  • 2020-04-30
  • 2017-05-19
  • 2020-11-09
  • 2019-08-18
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2021-04-02
相关资源
最近更新 更多