【问题标题】:How to plot top5 features_importances using RandomForestRegressor如何使用 RandomForestRegressor 绘制 top5 features_importances
【发布时间】:2019-05-31 15:37:50
【问题描述】:

我正在尝试绘制 RandomForestRegressor 模型的 feature_importance。但是,我的数据集中有 307 个特征(在 OneHotEncoding 之后),因此绘制所有特征在美学上并没有真正的帮助。

我怎样才能只绘制前 5 个(或前 10 个)的?

这是我的实际代码:

# Help function to plot feature_importances 
def plot_feature_importances(model_to_plot, features_list, x_train_set):
    # Wichtigkeit der eizelnen Features plotten! 

    plt_x = np.linspace(0,len(features_list)-1,len(features_list))

    print("Features sorted by their score:")

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(plt_x, model_to_plot.feature_importances_, width=0.5, color="blue",align='center')
    plt.gca().set_xticklabels(plt_x, rotation=60 )
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.xticks(plt_x, features_list, fontsize=12)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    print("Feature ranking:")

    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1]

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

并使用以下代码进行绘图给了我这样的结果:

plot_feature_importances(model, features, x_train)

【问题讨论】:

  • 计算特征的重要性,如果还没有,将它们放入数组中,argsort 数组,然后绘制?

标签: python matplotlib machine-learning plot random-forest


【解决方案1】:

您未能提供Minimal, Complete, and Verifiable example,因此我无法提供最终的有效答案。不过,您可以尝试以下修改后的代码。我已经删除了设置 x-ticks 的行。但那部分是微不足道的

def plot_feature_importances(model_to_plot, features_list, x_train_set):
    to_plot = 5 # <---- Define the number to plot
    importances = model_to_plot.feature_importances_
    std = np.std([tree.feature_importances_ for tree in model_to_plot.estimators_],
                 axis=0)
    indices = np.argsort(importances)[::-1][0:to_plot] # <--- Take the top 5 

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 12}

    plt.rc('font', **font)

    plt.figure(figsize=(15,7))

    plt.bar(range(to_plot), importances[indices], width=0.5, color="blue",align='center') # <--- Plot the top 5 
    plt.xticks(range(to_plot), features_list[indices], fontsize=12) # <--- add ticks
    plt.title('Features importance in decision making', position=(.5,1.05), fontsize=20)
    plt.yticks(fontsize=12)
    plt.ylabel('Relative Information %', fontsize=15)
    plt.xlabel('Features', fontsize=15)
    plt.show()

    for f in range(x_train.shape[1]):
        print("%d. Feature %s (%.2f)" % (f + 1, x_train_set.columns[indices[f]], importances[indices[f]]))

plot_feature_importances(model, features, x_train)

【讨论】:

  • 感谢您的回答。但这不是在绘制 x 刻度(只有数字 (0,1,2,3,4,5) 并且这不是在使用我的实际函数时打印图下的确切值(上面的代码)使用 f in range(x_train.shape[1]):
  • @ZelelB:是的,我删除了打印命令,因为它与绘图无关。主要问题是:它是否绘制了前 5 个特征?
  • 是的,我注意到了。无论如何,谢谢你的回答。但是我现在正试图将这些恢复到函数中,并且以某种方式对错误感到疯狂,并且没有解决这个问题:-/您能否只修改一小部分代码,以便它可以使用?这真的很有帮助!还是非常感谢
  • @ZelelB:我添加了一行plt.xticks(...)。立即查看
  • @ZelelB :这就是为什么我尽量不回答缺少a Minimal, Complete, and Verifiable example 的问题。如果上面的评论没有帮助,那么除非你提供一个 MCVE,我可以简单地复制粘贴并在我的编辑器中运行以获得上图,否则我无能为力。追逐未知事物会不必要地花费一整天时间。
猜你喜欢
  • 2015-04-20
  • 2019-11-05
  • 2019-08-17
  • 2021-07-11
  • 1970-01-01
  • 2019-01-17
  • 2020-05-13
  • 2020-09-05
  • 2015-03-09
相关资源
最近更新 更多