随机森林和Python

时间:2017-12-06 12:32:00

标签: python feature-selection random-forest

我有一个具有72个特征的数据集的随机森林模型:目标是找到特征重要性并将其用于特征选择。

rf = RandomForestRegressor(n_estimators=XXX)  
rf.fit(X, y)

我无法获得具有其特征值的预测变量列表,它只提供72个特征重要性数字,这与每个特征名称的映射非常不一致, 有没有办法把名字和重要性放在一起 喜欢

  

0.55656
  B 0.4333

2 个答案:

答案 0 :(得分:1)

假设您的要素已分配到名为feature_labels的列表

您可以按如下方式打印要素重要性,

for feature in zip(feature_labels, rf.feature_importances_):
    print(feature)

以上分数是每个变量的重要性分数。这里要记住的是所有重要性得分加起来都是100%。

为了识别和选择最重要的功能,

# Create a selector object that will use the random forest classifier to identify
# features that have an importance of more than 0.15
sfm = SelectFromModel(rf, threshold=0.15)

# Train the selector
sfm.fit(X_train, y_train)

'''SelectFromModel(estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_split=1e-07, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            n_estimators=10000, n_jobs=-1, oob_score=False, random_state=0,
            verbose=0, warm_start=False),
        prefit=False, threshold=0.15)'''

# Print the names of the most important features
for feature_list_index in sfm.get_support(indices=True):
    print(feature_labels[feature_list_index])

这将根据阈​​值设置打印出您最重要的功能名称。

答案 1 :(得分:0)

feature_importance_方法保持树被训练的特征顺序。因此,您可以在原始要素列表和feature_importance_返回值之间使用zip函数来获取每个要素的重要性。