我尝试从我的数据框中获取每个特征的重要性权重。我使用了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 RandomForestClassifierforest = 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循环。我们为什么要使用”indices”来索引”importances”数组?为什么我们不能简单地使用以下代码:
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
回答:
这与文档中给出的不一样,请仔细看,文档中是这么说的
# FROM DOCSfor f in range(X.shape[1]): print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]]))
这是正确的,而不是
# FROM YOUR QUESTIONfor f in range(X_train.shape[1]): print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[indices[f]]))
这是错误的。如果你想使用feat_labels,你应该这样做
# CORRECT SOLUTIONfor f in range(X_train.shape[1]): print("%2d) %-*s %f" % (f + 1, 30,feat_labels[indices[f]], importances[indices[f]]))
他们使用这种方法是因为他们希望按照特征重要性的降序进行迭代,不使用”indices”会使用特征的原始顺序。两种方法都可以,唯一错误的是你提出的第一个方法 – 它混合了两种方法,并且错误地将重要性分配给了特征。