如何访问 Scikit Learn 嵌套交叉验证分数

How to access Scikit Learn nested cross-validation scores

我正在使用 python,我想将嵌套交叉验证与 scikit learn 结合使用。我找到了一个很好的 example:

NUM_TRIALS = 30
non_nested_scores = np.zeros(NUM_TRIALS)
nested_scores = np.zeros(NUM_TRIALS)
# Choose cross-validation techniques for the inner and outer loops,
# independently of the dataset.
# E.g "LabelKFold", "LeaveOneOut", "LeaveOneLabelOut", etc.
inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)
outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)

# Non_nested parameter search and scoring
clf = GridSearchCV(estimator=svr, param_grid=p_grid, cv=inner_cv)
clf.fit(X_iris, y_iris)
non_nested_scores[i] = clf.best_score_

# Nested CV with parameter optimization
nested_score = cross_val_score(clf, X=X_iris, y=y_iris, cv=outer_cv)
nested_scores[i] = nested_score.mean()

如何访问嵌套交叉验证中的最佳参数集以及所有参数集(及其相应的分数)?

您无法从 cross_val_score 访问单个参数和最佳参数。 cross_val_score 在内部所做的是克隆提供的估计器,然后在其上调用 fitscore 方法,并在各个估计器上使用给定的 Xy

如果你想在每次拆分时访问参数,你可以使用:

#put below code inside your NUM_TRIALS for loop
cv_iter = 0
temp_nested_scores_train = np.zeros(4)
temp_nested_scores_test = np.zeros(4)
for train, test in outer_cv.split(X_iris):
    clf.fit(X_iris[train], y_iris[train])
    temp_nested_scores_train[cv_iter] = clf.best_score_
    temp_nested_scores_test[cv_iter] = clf.score(X_iris[test], y_iris[test])
    #You can access grid search's params here
nested_scores_train[i] = temp_nested_scores_train.mean()
nested_scores_test[i] = temp_nested_scores_test.mean()

Vivek Kumar 的回答基于使用显式外部 cv for 循环。如果 OP 想要基于 sklearn 的交叉验证工作流程访问最佳估算器和最佳参数,我建议使用 cross_validate 而不是 cross_val_score,因为前者允许您 return 估算器。使用 cross_validate 的额外好处是您可以指定多个指标。

from sklearn.model_selection import cross_validate
scoring = {"auroc": "roc_auc"} # [1]
nested_scores = cross_validate(clf, X=X_iris, y=y_iris, cv=outer_cv, return_estimator=True, random_state=0)

然后您可以从每个 cv 折叠中访问最佳模型:

best_models = nested_scores['estimator']
for i, model in enumerate(best_models):
    best_model = model.best_estimator_
    best_params = model.best_params_

[1] 获取可用分数列表 https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter