如何使用树林来标记特征重要性?

2024-03-28 23:53:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用sklearn来绘制树木森林的特征重要性。数据帧名为“heart”。下面是提取已排序功能列表的代码:

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

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

谢谢


Tags: 数据名称列表绘制rangetrainplt特征
3条回答

我知道这已经很古老了,但是对于后代来说,如果你想从@bakkal的解中以正确的顺序得到feature_name,你可以使用

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

问题在于:

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)

您可以在模型中使用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()

这段代码将为您提供如下绘图:

graph with labeled feature names on y axis sorted according to importance and their importance labeled on x axis

相关问题 更多 >