【发布时间】: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