我正在尝试绘制随机森林模型的特征重要性并将每个特征重要性映射回原始系数。我设法创建了一个显示重要性的图,并使用原始变量名称作为标签,但现在它按照变量名称在数据集中的顺序(而不是按重要性顺序)对变量名称进行排序。我如何按照功能重要性对它们进行排序?谢谢!
我的代码是:
importances = brf.feature_importances_
std = np.std([tree.feature_importances_ for tree in brf.estimators_],
axis=0)
indices = np.argsort(importances)[::-1]
# Print the feature ranking
print("Feature ranking:")
for f in range(x_dummies.shape[1]):
print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
# Plot the feature importances of the forest
plt.figure(figsize=(8,8))
plt.title("Feature importances")
plt.bar(range(x_train.shape[1]), importances[indices],
color="r", yerr=std[indices], align="center")
feature_names = x_dummies.columns
plt.xticks(range(x_dummies.shape[1]), feature_names)
plt.xticks(rotation=90)
plt.xlim([-1, x_dummies.shape[1]])
plt.show()
原文由 yogz123 发布,翻译遵循 CC BY-SA 4.0 许可协议
一种通用的解决方案是将特征/重要性放入数据框中并在绘图之前对它们进行排序: