我正在尝试在我的一个数据集上创建一个随机森林回归模型。我需要找到每个变量的重要性顺序以及它们的名称。我尝试过很少的东西,但却无法达到我的目的。以下是我在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个。
答案 0 :(得分:5)
首先,您使用了错误的名称作为变量。您正在使用important_features
。请改用 feature_importances_
。其次,它将返回一个形状[n_features,]
的数组,其中包含feature_importance的值。您需要按照这些值的顺序对它们进行排序,以获得最重要的功能。
请参阅RandomForestRegressor documentation
编辑:添加了代码
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
这将按降序打印重要特征的索引。 (首先是最重要的,依此类推)
答案 1 :(得分:0)
通过以下代码,您应该也可以按降序查看功能及其名称:
创建一个空列表
featureImpList= []
运行for循环:
for feat, importance in zip(train_df.columns, clf_ggr.feature_importances_):
temp = [feat, importance*100]
featureImp.append(temp)
fT_df = pd.DataFrame(featureImp, columns = ['Feature', 'Importance'])
print (fT_df.sort_values('Importance', ascending = False))
答案 2 :(得分:0)
importances = rf.feature_importances_
sorted_indices = np.argsort(importances)[::-1]
sorted_indices
答案 3 :(得分:0)
您可以像这样打印订单:
importances = brf.feature_importances_
sorted_indices = np.argsort(importances)[::-1]
print(*X_train.columns[sorted_indices], sep = "\n")
答案 4 :(得分:-1)
# list of column names from original data
cols = data.columns
# feature importances from random forest fit rf
rank = rf.feature_importances_
# form dictionary of feature ranks and features
features_dict = dict(zip(np.argsort(rank),cols))
# the dictionary key are the importance rank; the values are the feature name