AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

我正在使用网格搜索来调整我的模型(随机森林、线性回归等)的参数。所以我将 gs 个对象保存在 grid_searches:

gs = GridSearchCV(model, params, cv=cv, n_jobs=n_jobs,
                  verbose=verbose, scoring="mean_squared_error", refit=refit)
gs.fit(trainX,trainy)
grid_searches[key] = gs

然后我想访问每个模型的最佳估计器以进行预测:

def predict(testX, testy, grid_searches):
    keys = models.keys()
    for k in keys:
        print("Predicting with %s." % k)
        yhat = grid_searches[k].best_estimator_.predict(testX)

错误如下:

AttributeError: 'GridSearchCV' object has no attribute 'best_estimator_'

那么我应该如何使用网格搜索找到的最佳模型进行预测?

从代码摘录中不清楚您如何设置 refit。根据 docsbest_estimator_ 仅在 True 时可用。如果 False,您应该仍然能够从 grid_scores_ 中找到性能最佳的参数,然后将它们与 set_params() 一起使用。