使用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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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