【问题标题】:HOW TO LABEL the FEATURE IMPORTANCE with forests of trees?如何在森林中标记特征重要性?
【发布时间】:2016-10-19 01:17:52
【问题描述】:

我使用 sklearn 来绘制森林的特征重要性。数据框被命名为“心脏”。这里是提取排序特征列表的代码:

importances = extc.feature_importances_
indices = np.argsort(importances)[::-1]
print("Feature ranking:")

for f in range(heart_train.shape[1]):
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

然后我以这种方式绘制列表:

f, ax = plt.subplots(figsize=(11, 9))
plt.title("Feature ranking", fontsize = 20)
plt.bar(range(heart_train.shape[1]), importances[indices],
    color="b", 
    align="center")
plt.xticks(range(heart_train.shape[1]), indices)
plt.xlim([-1, heart_train.shape[1]])
plt.ylabel("importance", fontsize = 18)
plt.xlabel("index of the feature", fontsize = 18)

我得到这样的情节:

我的问题是:如何将功能的 NUMBER 替换为功能的名称,以使情节更易于理解? 我试图转换包含特征名称的字符串(即数据框每一列的名称),但我无法达到我的目标。

谢谢

【问题讨论】:

标签: python numpy matplotlib scikit-learn sklearn-pandas


【解决方案1】:

问题出在这里:

plt.xticks(range(heart_train.shape[1]), indices)

indices 是从您的 np.argsort(importances)[::-1] 返回的索引数组,它没有您希望在 X 轴上显示为刻度的功能名称

假设 df 是你的 Pandas 数据框,你需要这样的东西

feature_names = df.columns # e.g. ['A', 'B', 'C', 'D', 'E']
plt.xticks(range(heart_train.shape[1]), feature_names)

【讨论】:

  • 谢谢!现在我必须将正确的列与正确的重要性相匹配。
  • 您是否弄清楚如何将正确的列与正确的重要性相匹配?
【解决方案2】:

我看到这是旧的,但为了后代,如果你想以正确的顺序从@bakkal 的解决方案中获得feature_name,你可以使用

feature_names = [features_names[i] for i in indices]

【讨论】:

    【解决方案3】:

    您可以在模型中使用 xgboost 通过使用方法-plot_importance(model) 以简单的方式绘制特征的重要性

    from xgboost import plot_importance,XGBClassifier model=XGBClassifier(n_estimators=1000,learning_rate=0.5) x_train,x_test,y_train,y_test=model_selection.train_test_split(features,label,test_size=0.2) model.fit(x_train,y_train,early_stopping_rounds=5,eval_set=[(x_test,y_test)]) plot_importance(model) plt.show()

    这段代码给你一个这样的情节:

    【讨论】:

      猜你喜欢
      • 2021-05-09
      • 2018-04-01
      • 2021-08-29
      • 2019-01-09
      • 2016-04-09
      • 1970-01-01
      • 2020-08-28
      • 2021-08-15
      • 2020-05-26
      相关资源
      最近更新 更多