python - 如何用树木的森林来标记特征的重要性?

标签 python numpy matplotlib scikit-learn sklearn-pandas

我使用 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)

我得到这样的情节:

enter image description here

我的问题是:如何用要素的名称替换要素的编号,以便使情节更易于理解? 我试图转换包含特征名称的字符串(这是数据框每一列的名称),但我无法达到我的目标。

谢谢

最佳答案

问题出在这里:

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

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

你需要这样的东西,假设 df 是你的 Pandas DataFrame

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

关于python - 如何用树木的森林来标记特征的重要性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37877542/

相关文章:

python - Cython 并行性和模板

javascript - 如何合并这两个 html/javascript 文件

python - 如何在Python中向稀疏矩阵添加稀疏行?

python - 如何在python中访问编码(gb18020)字符串的一部分

PHP 与应用程序服务器?

python - 在 unittest 中比较(断言相等)两个包含 numpy 数组的复杂数据结构

python - Numpy : matrix of vectors, 反转

python - 保存 Matplotlib 动画时出错

python - 使用数据框列更改 x 轴

Python - 你能绘制带等高线的直方图吗?