首页 文章

如何处理从嵌套交叉验证中获得的网格搜索中的best_score?

提问于
浏览
0

我使用GridSearch和嵌套交叉验证优化了RandomForest . 之后,我知道使用最佳参数,我必须在对样本外数据进行预测之前训练整个数据集 .

我必须两次适合模型吗?一个是通过嵌套交叉验证然后使用样本外数据来查找准确度估算值?

请检查我的代码:

#Load data
for name in ["AWA"]:
for el in ['Fp1']:
    X=sio.loadmat('/home/TrainVal/{}_{}.mat'.format(name, el))['x']
    s_y=sio.loadmat('/home/TrainVal/{}_{}.mat'.format(name, el))['y']
    y=np.ravel(s_y)

    print(name, el, x.shape, y.shape) 
    print("")


#Pipeline
clf = Pipeline([('rcl', RobustScaler()),
                ('clf', RandomForestClassifier())])   

#Optimization
#Outer loop
sss_outer = StratifiedShuffleSplit(n_splits=2, test_size=0.1, random_state=1)
#Inner loop
sss_inner = StratifiedShuffleSplit(n_splits=2, test_size=0.1, random_state=1)


# Use a full grid over all parameters
param_grid = {'clf__n_estimators': [10, 12, 15],
              'clf__max_features': [3, 5, 10],
             }


# Run grid search
grid_search = GridSearchCV(clf, param_grid=param_grid, cv=sss_inner, n_jobs=-1)
#FIRST FIT!!!!!
grid_search.fit(X, y)
scores=cross_val_score(grid_search, X, y, cv=sss_outer)

#Show best parameter in inner loop
print(grid_search.best_params_)

#Show Accuracy average of all the outer loops 
print(scores.mean())

#SECOND FIT!!!
y_score = grid_search.fit(X, y).score(out-of-sample, y)
print(y_score)

2 回答

  • 1

    您需要了解一些事项 .

    当你执行"first fit"时,它将根据 sss_inner cv符合gird_search模型,并将结果存储在 grid_search.best_estimator_ 中(即根据 sss_inner 折叠的测试数据得分的最佳估计值) .

    现在你在 cross_val_score (嵌套)中使用 grid_search . "first fit"的合适型号在这里没用 . cross_val_scoreclone 估算器,在 sss_outer 的折叠上调用grid_search.fit()(这意味着来自 sss_outer 的训练数据将呈现给grid_search,它将根据 sss_inner 再次将其拆分)并显示测试数据的分数 . sss_outer . 来自 cross_val_score 的型号未安装 .

    现在在你的"second fit"中,你又像"first fit"那样适合了 . 不需要这样做,因为它已经安装好了 . 只需致电 grid_search.score() . 它将在内部从 best_estimator_ 调用 score() .

    您可以查看my answer here以了解有关使用网格搜索的嵌套交叉验证的更多信息 .

  • 1

    你的grid_search.best_estimator_包含带有best_params_参数的corss验证拟合模型,无需再次重新编译 .

    您可以使用:

    clf = grid_search.best_estimator_
    preds = clf.predict(X_unseen)
    

相关问题