2017-01-27 45 views
3

我想绘制随机森林模型的要素重要性并将每个要素重要性映射回原始系数。我设法创建了一个显示重要性并使用原始变量名称作为标签的图形,但现在它按照它们在数据集中的顺序排序变量名称(而不是按重要性排序)。我如何按照功能重要性排序?谢谢!将列名称映射到随机森林要素重要性

enter image description here

我的代码是:

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() 
+0

你还没有包括你目前得到的情节? –

+0

已编辑!我不确定剧情增加了多少价值,因为我只是想改变底部x标签的顺序。对于小字体的道歉,这是将大部分图片放入屏幕截图的唯一方法。 – yogz123

+0

'plt.bar(范围(x_dummies.shape [1]),重要性[indices], color =“r”,yerr = std [indices],align =“center”)'? –

回答

6

一个排序通用的解决方案将是扔的特征/重要性有关成数据帧,并将其绘制之前进行排序:

import pandas as pd 
%matplotlib inline 
#do code to support model 
#"data" is the X dataframe and model is the SKlearn object 

feats = {} # a dict to hold feature_name: feature_importance 
for feature, importance in zip(data.columns, model.feature_importances_): 
    feats[feature] = importance #add the name/value pair 

importances = pd.DataFrame.from_dict(feats, orient='index').rename(columns={0: 'Gini-importance'}) 
importances.sort_values(by='Gini-importance').plot(kind='bar', rot=45) 
1

我使用Sam的类似解决方案:

import pandas as pd 
important_features = pd.Series(data=brf.feature_importances_,index=x_dummies.columns) 
important_features.sort_values(ascending=False,inplace=True) 

我总是只打印使用print important_features列表中,但绘制你总是可以使用Series.plot

0

另一种简单的方式来获得一个排序列表

importances = list(zip(xgb_classifier.feature_importances_, df.columns)) 
importances.sort(reverse=True) 

下一个代码添加了一个可视化的,如果有必要

pd.DataFrame(importances, index=[x for (_,x) in importances]).plot(kind = 'bar')