如何使用python打印随机森林回归中重要特征的顺序?

Cod*_*ter 1 python machine-learning scikit-learn

我正在尝试在我的一个数据集上创建随机森林回归模型。我还需要找到每个变量的重要性顺序以及它们的名称。我尝试了几件事,但无法实现我想要的。以下是我在Boston Housing数据集中尝试的示例代码:

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
boston = load_boston()
rf=RandomForestRegressor(max_depth=50)
idx=range(len(boston.target))
np.random.shuffle(idx)
rf.fit(boston.data[:500], boston.target[:500])
instance=boston.data[[0,5, 10]]
print rf.predict(instance[0])
print rf.predict(instance[1])
print rf.predict(instance[2])
important_features=[]
for x,i in enumerate(rf.feature_importances_):
      important_features.append(str(x))
print 'Most important features:',', '.join(important_features)
Run Code Online (Sandbox Code Playgroud)

最重要的功能:0、1、2、3、4、5、6、7、8、9、10、11、12

如果我打印此:

impor = rf.feature_importances_
impor
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

array([  3.45665230e-02,   4.58687594e-04,   5.45376404e-03,
     3.33388828e-04,   2.90936201e-02,   4.15908448e-01,
     1.04131089e-02,   7.26451301e-02,   3.51628079e-03,
     1.20860975e-02,   1.40417760e-02,   8.97546838e-03,
     3.92507707e-01])
Run Code Online (Sandbox Code Playgroud)

我需要获取与这些值关联的名称,然后从这些功能中选择前n个。

Viv*_*mar 5

首先,您为变量使用了错误的名称。您正在使用important_features。使用feature_importances_代替。其次,它将返回一个形状数组,[n_features,]其中包含feature_importance的值。您需要按照这些值的顺序对它们进行排序,以获得最重要的功能。请参阅RandomForestRegressor文档

编辑:添加代码

important_features_dict = {}
for x,i in enumerate(rf.feature_importances_):
    important_features_dict[x]=i


important_features_list = sorted(important_features_dict,
                                 key=important_features_dict.get,
                                 reverse=True)

print 'Most important features: %s' %important_features_list
Run Code Online (Sandbox Code Playgroud)

这将以降序打印重要特征的索引。(首先是最重要的,依此类推)