属性错误:'GridSearchCV'对象没有'best_params_'属性。

22

网格搜索是一种寻找我们指定的组合中任何模型的最佳参数的方法。我已经按照以下方式对我的模型进行了网格搜索,并希望找到使用此网格搜索确定的最佳参数。

from sklearn.model_selection import GridSearchCV
# Create the parameter grid based on the results of random search 
param_grid = {
    'bootstrap': [True],'max_depth': [20,30,40, 100, 110],
    'max_features': ['sqrt'],'min_samples_leaf': [5,10,15],
    'min_samples_split': [40,50,60], 'n_estimators': [150, 200, 250]
}
# Create a based model
rf = RandomForestClassifier()
# Instantiate the grid search model
grid_search = GridSearchCV(estimator = rf, param_grid = param_grid, 
                          cv = 3, n_jobs = -1, verbose = 2)

现在我想找到网格搜索的最佳参数作为输出

grid_search.best_params_

错误:

----> grid_search.best_params_
AttributeError: 'GridSearchCV' object has no attribute 'best_params_'

我错过了什么?

2个回答

37

如果没有将数据拟合,就无法得到最佳参数。

拟合数据。

grid_search.fit(X_train, y_train)

现在寻找最佳参数。

grid_search.best_params_

grid_search.best_params_需要在拟合X_trainy_train后才能使用。


0

如果我们查看源代码, 可以发现best_params_fit()方法中定义,因此必须在GridSearchCVRandomizedSearchCV对象上调用它,就如同@noob说的

如果您在拟合数据后仍然遇到此错误,则可能传递了多个评分指标。选择其中一个作为重新拟合的指标,错误将消失。这是因为如果没有选择,不清楚要使用哪个指标来确定best_params_

gs = GridSearchCV(
    rf, param_grid, 
    scoring=['precision', 'recall'], refit=False,
    n_jobs=-1)
gs.fit(X_train, y_train)
gs.best_params_                                       # <---- error

gs = GridSearchCV(
    rf, param_grid, 
    scoring=['precision', 'recall'], refit='recall',
#                                    ^^^^^^^^^^^^^^   # <---- choose refit metric
    n_jobs=-1)
gs.fit(X_train, y_train)
gs.best_params_                                       # <---- OK

如果您看到以下错误信息而来到此处:

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

然后,再次,因为best_estimator_是在fit()方法中定义的,请检查是否已经拟合了数据。如果即使在拟合数据之后仍然出现错误,则refit再次是罪魁祸首。要设置best_estimator_,必须保持refit=True,以便可以使用best_params_将整个数据再次拟合到估算器(在下面的示例中为随机森林)上。

best_ = GridSearchCV(rf, param_grid, refit=False, n_jobs=-1).fit(X_train, y_train).best_estimator_  # <---- error
best_ = GridSearchCV(rf, param_grid, refit=True, n_jobs=-1).fit(X_train, y_train).best_estimator_   # <---- OK
#                                    ^^^^^^^^^^

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接