Attribute Error: 'RandomForestRegressor' object has no attribute 'best_params_'

Attribute Error: 'RandomForestRegressor' object has no attribute 'best_params_'

我在使用随机森林[=20=对我的分类进行网格搜索时遇到此错误].

from sklearn.ensemble import RandomForestRegressor
rf2 = RandomForestRegressor(random_state = 50)
rf2.fit(X_train1, y_train1)

### Grid Search ###
num_leafs = [1, 5, 10, 20, 50, 100]

parameters3 = [{'n_estimators' : range(100,800,20),
             'max_depth': range(1,20,2),
             'min_samples_leaf':num_leafs
             }]


gs3 = GridSearchCV(estimator=rf2,
                  param_grid=parameters3,
                  cv = 10,
                  n_jobs = -1)

gs3 = rf2.fit(X_train1, y_train1)

gs3.best_params_ # <- thats where I get the Error

我不知道这个问题,因为它与 SVM 和决策树的工作方式相同(当然参数不同)。

提前致谢

替换为: gs3 = rf2.fit(X_train1, y_train1)

通过这个: gs3.fit(X_train1, y_train1)

然后你就可以使用: gs3.best_params_

您的错误是由于您将 gs3 重新分配给了 RandomForest() 调用,因此 gs3 不再是 GridSearchCV 对象。

好吧,您不适合 GridSearch 对象,而是适合 model (rf2),然后将其分配给 gs3 参数。

你有:

gs3 = GridSearchCV(estimator=rf2,
                  param_grid=parameters3,
                  cv = 10,
                  n_jobs = -1)
gs3 = rf2.fit(X_train1, y_train1)
gs3.best_params_ # <- thats where I get the Error

您需要:

gs3 = GridSearchCV(estimator=rf2,
                  param_grid=parameters3,
                  cv = 10,
                  n_jobs = -1)
gs3.fit(X_train1, y_train1) # fit the GridSearchCV object
gs3.best_params_ # <- thats where I get the Error