使用RandomClassifier Scikit获取功能重要性

时间:2016-04-06 11:20:28

标签: machine-learning scikit-learn random-forest feature-extraction feature-selection

我尝试从数据框中获取每个要素的重要性权重。 我使用scikit文档中的代码:

names=['Class label', 'Alcohol',
'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium',
'Total phenols', 'Flavanoids',
'Nonflavanoid phenols',
'Proanthocyanins',
'Color intensity', 'Hue',
'OD280/OD315 of diluted wines',
'Proline']
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None,names=names)



from sklearn.ensemble import RandomForestClassifier
forest = RandomForestClassifier(n_estimators=10000,
 random_state=0,
 n_jobs=-1)
forest.fit(X_train, y_train)

feat_labels = df_wine.columns[1:]
importances = forest.feature_importances_ 
indices = np.argsort(importances)[::-1]
for f in range(X_train.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[indices[f]]))

但是尽管我理解了np.argsort方法,但我还是不理解这个FOR循环。 为什么我们使用"指数"索引"进口"阵列?为什么我们不能简单地使用这样的代码:

for f in range(X_train.shape[1]):
print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[f]))

使用" importances [indices [f]]"(前5行)的输出:

 1) Alcohol                        0.182483
 2) Malic acid                     0.158610
 3) Ash                            0.150948
 4) Alcalinity of ash              0.131987
 5) Magnesium                      0.106589

" importances [f]"(前5行)的输出:

 1) Alcohol                        0.106589
 2) Malic acid                     0.025400
 3) Ash                            0.013916
 4) Alcalinity of ash              0.032033
 5) Magnesium                      0.022078

1 个答案:

答案 0 :(得分:0)

这不是文档中的内容,仔细看,它说

# FROM DOCS
for f in range(X.shape[1]):
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))

这是正确的,而不是

# FROM YOUR QUESTION
for f in range(X_train.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[indices[f]]))

这是错误的。如果你想使用feat_labels你应该

# CORRECT SOLUTION
for f in range(X_train.shape[1]):
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[indices[f]], importances[indices[f]]))

使用它们的方法是因为它们希望以特征重要性的递减顺序迭代,而不使用“索引”将使用特征的排序。两者都很好,唯一不正确的是你提出的第一个 - 这是两种方法的混合,并错误地赋予功能重要性。

相关问题