我在使用Python,并希望使用Scikit Learn进行嵌套交叉验证。我找到了一个非常好的示例:
NUM_TRIALS = 30non_nested_scores = np.zeros(NUM_TRIALS)nested_scores = np.zeros(NUM_TRIALS)# 独立于数据集,选择内外循环的交叉验证技术。# 例如"LabelKFold", "LeaveOneOut", "LeaveOneLabelOut"等inner_cv = KFold(n_splits=4, shuffle=True, random_state=i)outer_cv = KFold(n_splits=4, shuffle=True, random_state=i)# 非嵌套参数搜索和评分clf = GridSearchCV(estimator=svr, param_grid=p_grid, cv=inner_cv)clf.fit(X_iris, y_iris)non_nested_scores[i] = clf.best_score_# 带参数优化的嵌套CVnested_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
内部所做的操作是克隆提供的估计器,然后在给定的X
、y
上对单个估计器调用fit
和score
方法。
如果你想在每个分割点访问参数,你可以使用以下代码:
# 将下面的代码放入你的NUM_TRIALS循环中cv_iter = 0temp_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]) # 你可以在这里访问网格搜索的参数nested_scores_train[i] = temp_nested_scores_train.mean()nested_scores_test[i] = temp_nested_scores_test.mean()