RandomForestRegressor 和 feature_importances_ 错误

Posted

技术标签:

【中文标题】RandomForestRegressor 和 feature_importances_ 错误【英文标题】:RandomForestRegressor and feature_importances_ error 【发布时间】:2018-04-17 02:38:41 【问题描述】:

我正在努力从我的 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_

【问题讨论】:

【参考方案1】:

您正在尝试使用 GridSearchCV 对象上的属性。它不存在于那里。您实际需要做的是访问完成网格搜索的估算器。

通过以下方式访问属性:

importances = CV_RFR_regr.best_estimator_.feature_importances_

【讨论】:

【参考方案2】:

///

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'])

///

【讨论】:

您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。

以上是关于RandomForestRegressor 和 feature_importances_ 错误的主要内容,如果未能解决你的问题,请参考以下文章

RandomForestRegressor 只吐出 1 个预测

Lesson 9.1 集成学习的三大关键领域Bagging 方法的基本思想和 RandomForestRegressor 的实现

将 GridSearchCV 用于 RandomForestRegressor

找到样本数量不一致的输入变量:RandomForestRegressor 的 [1, 4] 错误

sklearn 中的 RandomForestRegressor 给出负分

RandomForestRegressor,特征重要性