随机森林回归器和特征重要性错误

10

我正在努力从我的RandomForestRegressor中提取特征重要性,但是我遇到了:

AttributeError: 'GridSearchCV'对象没有属性'feature_importances_'。

有人知道为什么会没有这个属性吗?根据文档,应该存在这个属性?

完整的代码:

from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import GridSearchCV

#Running a RandomForestRegressor GridSearchCV to tune the model.
parameter_candidates = {
    'n_estimators' : [650, 700, 750, 800],
    'min_samples_leaf' : [1, 2, 3],
    'max_depth' : [10, 11, 12],
    'min_samples_split' : [2, 3, 4, 5, 6]
}

RFR_regr = RandomForestRegressor()
CV_RFR_regr = GridSearchCV(estimator=RFR_regr, param_grid=parameter_candidates, n_jobs=5, verbose=2)
CV_RFR_regr.fit(X_train, y_train)

#Predict with testing set
y_pred = CV_RFR_regr.predict(X_test)

#Extract feature importances
importances = CV_RFR_regr.feature_importances_
2个回答

18

您正在尝试在GridSearchCV对象上使用该属性,但该属性不存在。实际上,您需要访问进行网格搜索的估算器。

通过以下方式访问属性:

importances = CV_RFR_regr.best_estimator_.feature_importances_

-1

///

clf = RandomForestClassifier() clf.fit(df.drop('name', axis=1), df['name'])

plt.figure(figsize=(10,10)) plt.bar(df.drop('name', axis=1).columns, height=clf.feature_importances_, bottom = 0, width=0.8) plt.xticks(rotation=80)

hight_rate_col = df.drop('name', axis=1).columns[clf.feature_importances_ > 0.1] x_train_rate, x_test_rate, y_train_rate, y_test_rate = train_test_split(df[hight_rate_col], df['name'])

///


你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

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