解读 sklearns 的 GridSearchCV 最好成绩

Interpreting sklearns' GridSearchCV best score

我想知道 GridSearchCV 返回的分数与 R2 计算的指标之间的差异,如下所示。在其他情况下,我收到的网格搜索分数非常负面(同样适用于 cross_val_score),我将不胜感激解释它是什么。

from sklearn import datasets
from sklearn.model_selection import (cross_val_score, GridSearchCV)
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import accuracy_score, r2_score
from sklearn import tree

diabetes = datasets.load_diabetes()
X = diabetes.data[:150]
y = diabetes.target[:150]
X = pd.DataFrame(X)

parameters = {'splitter':('best','random'), 
              'max_depth':np.arange(1,10), 
              'min_samples_split':np.arange(2,10), 
              'min_samples_leaf':np.arange(1,5)}

regressor = GridSearchCV(DecisionTreeRegressor(), parameters, scoring = 'r2', cv = 5)
regressor.fit(X, y)

print('Best score: ', regressor.best_score_)
best = regressor.best_estimator_
print('R2: ', r2_score(y_pred = best.predict(X), y_true = y))

The question 由 @Davide 在评论中链接,它回答了为什么你得到正 R2 分数 - 你的模型比常量预测表现更好。同时,如果您的模型在其他情况下表现不佳,您可能会在其他情况下获得负值。

值差异的原因是 regressor.best_score_ 是在您所做的 5 倍分割中的特定折叠上评估的,而 r2_score(y_pred = best.predict(X), y_true = y) 评估的是同一模型(regressor.best_estimator_) 但在完整样本上(包括用于训练该估计器的 (5-1) 倍子集)

regressor.best_score_ 是最佳参数组合的遗漏测试折叠的 r2 分数的平均值。

在您的示例中,cv=5,因此数据将被拆分为训练和测试折叠 5 次。该模型将安装在火车上并在测试中评分。这5个考试成绩取平均得到分数。请参阅 documentation

"best_score_: Mean cross-validated score of the best_estimator"

对所有参数组合重复上述过程。并将其最好的平均分分配给 best_score_.

您可以查看 以了解 GridSearchCV 的完整工作

找到最佳参数后,在完整数据上训练模型。

r2_score(y_pred = best.predict(X), y_true = y)

与训练模型的数据相同,因此在大多数情况下,它会更高。