使用RandomClassifier获取特征重要性

我尝试从我的数据框中获取每个特征的重要性权重。我使用了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”会使用特征的原始顺序。两种方法都可以,唯一错误的是你提出的第一个方法 – 它混合了两种方法,并且错误地将重要性分配给了特征。

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注