【问题标题】:How to plot feature importance for random forest in python如何在python中绘制随机森林的特征重要性
【发布时间】:2021-08-15 00:32:55
【问题描述】:

我创建了一个随机森林模型,并想绘制特征重要性

model_RF_tune = RandomForestClassifier(random_state=0, n_estimators = 80, 
min_samples_split =10, max_depth= None, max_features = "auto",)

我已经尝试定义一个函数:

def plot_feature_importances_health(model):
    n_features = model.data.shape
    plt.barh(range(n_features), model.feature_importances_, align = "center")
    plt.yticks(np.arrange(n_features), df_health_reconstructed.feature_names)
    plt.xlabel("Feature importance")
    plt.ylabel("Feature")
    plt.ylim(-1, n_features)

但是这个 plot_feature_importances_health(model_RF_tune)

给出这个结果: AttributeError: 'RandomForestClassifier' 对象没有属性 'data'

如何正确绘制?

【问题讨论】:

标签: python classification random-forest


【解决方案1】:

并非所有模型都可以执行model.data。你想试试我的代码吗?但是,这些代码仅绘制了前 10 个特征。

# use RandomForestClassifier to look for important key features
n = 10    # choose top n features
rfc = RandomForestClassifier(random_state=SEED, n_estimators=200, max_depth=3)
rfc_model = rfc.fit(X, y)

(pd.Series(rfc_model.feature_importances_, index=X.columns)
    .nlargest(n)
    .plot(kind='barh', figsize=[8, n/2.5],color='navy')
    .invert_yaxis())    # most important feature is on top, ie, descending order

ticks_x = np.linspace(0, 0.5, 6)   # (start, end, number of ticks)
plt.xticks(ticks_x, fontsize=15, color='black')
plt.yticks(size=15, color='navy' )
plt.title('Top Features derived by RandomForestClassifier', family='fantasy', size=15)
print(list((pd.Series(rfc_model.feature_importances_, index=X.columns).nlargest(n)).index))

【讨论】:

  • 我收到此响应:AttributeError: 'numpy.ndarray' 对象没有属性 'columns'。你知道那是什么意思吗?
  • 我认为它与index=X.columns 有关。我已将我的 X 指定为 DataFrame,而您的 X 是一个 numpy 数组。您可以将其转换为 DataFrame,或手动插入特征列 index=['col1', 'col2', etc]
【解决方案2】:

这个好像对我有用

%matplotlib inline
#do code to support model
#"data" is the X dataframe and model is the SKlearn object
feats = {} # a dict to hold feature_name: feature_importance
for feature, importance in zip(dataframe_name.columns, 
model_name.feature_importances_):
     feats[feature] = importance #add the name/value pair 


importances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini- 
importance'})
importances.sort_values(by='Gini-importance').plot(kind='barh', 
color="SeaGreen",figsize=(10,8))

【讨论】:

    猜你喜欢
    • 2021-08-29
    • 2021-05-09
    • 1970-01-01
    • 2020-05-26
    • 2017-10-21
    • 2021-05-13
    • 2017-01-06
    • 2016-04-09
    • 2015-05-12
    相关资源
    最近更新 更多