如何使用Python打印随机森林回归中重要特征的顺序?

我正在尝试在一个数据集上创建一个随机森林回归模型。我需要找到每个变量的重要性顺序以及它们的名称。我尝试了一些方法,但没有达到我的预期。以下是我在波士顿房价数据集上尝试的示例代码:

from sklearn.ensemble import RandomForestClassifierfrom sklearn.datasets import load_bostonfrom sklearn.ensemble import RandomForestRegressorimport pandas as pdimport numpy as npboston = load_boston()rf=RandomForestRegressor(max_depth=50)idx=range(len(boston.target))np.random.shuffle(idx)rf.fit(boston.data[:500], boston.target[:500])instance=boston.data[[0,5, 10]]print rf.predict(instance[0])print rf.predict(instance[1])print rf.predict(instance[2])important_features=[]for x,i in enumerate(rf.feature_importances_):      important_features.append(str(x))print 'Most important features:',', '.join(important_features)

最重要的特征:0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12

如果我打印这个:

impor = rf.feature_importances_impor

我得到以下输出:

array([  3.45665230e-02,   4.58687594e-04,   5.45376404e-03,     3.33388828e-04,   2.90936201e-02,   4.15908448e-01,     1.04131089e-02,   7.26451301e-02,   3.51628079e-03,     1.20860975e-02,   1.40417760e-02,   8.97546838e-03,     3.92507707e-01])

我需要得到与这些值相关联的名称,然后从这些特征中选出前n个。


回答:

首先,你使用了错误的变量名称。你使用的是important_features。应该使用feature_importances_。其次,它会返回一个形状为[n_features,]的数组,其中包含特征重要性的值。你需要根据这些值对它们进行排序,以获得最重要的特征。请参阅RandomForestRegressor文档

编辑:添加了代码

important_features_dict = {}for idx, val in enumerate(rf.feature_importances_):    important_features_dict[idx] = valimportant_features_list = sorted(important_features_dict,                                 key=important_features_dict.get,                                 reverse=True)print(f'5 most important features: {important_features_list[:5]}')

这将按降序打印重要特征的索引。(第一个是最重要的,依此类推)

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中创建了一个多类分类项目。该项目可以对…

发表回复

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