我正在尝试在我的一个数据集上创建一个随机森林回归模型。我还需要找到每个变量的重要性顺序及其名称。我尝试了一些事情,但无法实现我想要的。下面是我在 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)
最重要的特征:0、1、2、3、4、5、6、7、8、9、10、11、12
如果我打印这个:
impor = rf.feature_importances_
impor
我得到以下输出:
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])
我需要获取与这些值关联的名称,然后从这些特征中选出前 n 个。
最佳答案
首先,您使用了错误的变量名称。您正在使用 important_features
。请改用 feature_importances_
。其次,它将返回一个形状为 [n_features,]
的数组,其中包含 feature_importance 的值。您需要按照这些值的顺序对它们进行排序以获得最重要的功能。
查看RandomForestRegressor documentation
编辑:添加代码
important_features_dict = {}
for idx, val in enumerate(rf.feature_importances_):
important_features_dict[idx] = val
important_features_list = sorted(important_features_dict,
key=important_features_dict.get,
reverse=True)
print(f'5 most important features: {important_features_list[:5]}')
这将按降序打印重要特征的索引。 (第一个最重要,依此类推)
关于python - 如何使用python打印随机森林回归中重要特征的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128545/