我正在尝试在一个数据集上创建一个随机森林回归模型。我需要找到每个变量的重要性顺序以及它们的名称。我尝试了一些方法,但没有达到我的预期。以下是我在波士顿房价数据集上尝试的示例代码:
from sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import load_bostonfrom sklearn.ensemble import RandomForestRegressorimport pandas as pdimport numpy as npboston = 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,]
的数组,其中包含特征重要性的值。你需要根据这些值对它们进行排序,以获得最重要的特征。请参阅RandomForestRegressor文档
编辑:添加了代码
important_features_dict = {}for idx, val in enumerate(rf.feature_importances_): important_features_dict[idx] = valimportant_features_list = sorted(important_features_dict, key=important_features_dict.get, reverse=True)print(f'5 most important features: {important_features_list[:5]}')
这将按降序打印重要特征的索引。(第一个是最重要的,依此类推)