【问题标题】:How does sklearn random forest index feature_importances_sklearn 随机森林索引如何特征_importances_
【发布时间】:2014-04-17 04:38:11
【问题描述】:

我在 sklearn 中使用了 RandomForestClassifier 来确定我的数据集中的重要特征。我如何能够返回实际的特征名称(我的变量标记为 x1、x2、x3 等)而不是它们的相对名称(它告诉我重要的特征是“12”、“22”等)。以下是我目前用于返回重要功能的代码。

important_features = []
for x,i in enumerate(rf.feature_importances_):
    if i>np.average(rf.feature_importances_):
        important_features.append(str(x))
print important_features

此外,为了理解索引,我能够找出重要的特征“12”实际上是什么(它是变量 x14)。当我将变量 x14 移动到训练数据集的 0 索引位置并再次运行代码时,它应该告诉我特征“0”很重要,但事实并非如此,就好像它看不到那个特征列出的第一个特性实际上是我第一次运行代码时列出的第二个特性(特性'22')。

我在想也许 feature_importances_ 实际上是使用第一列(我放置 x14 的位置)作为其余训练数据集的一种 ID,因此在选择重要特征时忽略了它。任何人都可以对这两个问题有所了解吗?提前感谢您的任何帮助。

编辑
以下是我存储功能名称的方式:

tgmc_reader = csv.reader(csvfile)
row = tgmc_reader.next()    #Header contains feature names
feature_names = np.array(row)


然后我加载了数据集和目标类

tgmc_x, tgmc_y = [], []
for row in tgmc_reader:
    tgmc_x.append(row[3:])    #This says predictors start at the 4th column, columns 2 and 3 are just considered ID variables.
    tgmc_y.append(row[0])     #Target column is the first in the dataset


然后继续将数据集拆分为测试和训练部分。

from sklearn.cross_validation import train_test_split

x_train, x_test, y_train, y_test = train_test_split(tgmc_x, tgmc_y, test_size=.10, random_state=33)


然后拟合模型

from sklearn.ensemble import RandomForestClassifier

rf = RandomForestClassifier(n_estimators=1, criterion='entropy', max_features=2, max_depth=5, bootstrap=True, oob_score=True, n_jobs=2, random_state=33)
rf = rf.fit(x_train, y_train)


然后返回重要特征

important_features = []
for x,i in enumerate(rf.feature_importances_):
    if i>np.average(rf.feature_importances_):
        important_features.append((x))


然后我采纳了你的建议(非常感谢!)

important_names = feature_names[important_features > np.mean(important_features)]
print important_names


它确实返回了变量名。

['x9' 'x10' 'x11' 'x12' 'x13' 'x15' 'x16']


所以你肯定解决了我的问题的一部分,这太棒了。但是当我回去打印我的重要特征的结果时

print important_features


它返回以下输出:

[12, 22, 51, 67, 73, 75, 87, 91, 92, 106, 125, 150, 199, 206, 255, 256, 275, 309, 314, 317]


我将其解释为它认为第 12、22、51 等变量是重要的变量。所以这将是我在代码开头告诉它索引观察值的第 12 个变量:

tgmc_x.append(row[3:])


这种解释正确吗? 如果这是正确的,当我将第 12 个变量移动到原始数据集中的第 4 列(我告诉它开始使用我刚刚引用的代码读取预测值)并再次运行代码时,我得到以下输出:

[22, 51, 66, 73, 75, 76, 106, 112, 125, 142, 150, 187, 191, 199, 250, 259, 309, 317]


这似乎不再识别该变量。此外,当我将相同的变量移动到原始数据集中的第 5 列时,输出如下所示:

[1,22, 51, 66, 73, 75, 76, 106, 112, 125, 142, 150, 187, 191, 199, 250, 259, 309, 317]


这看起来像它再次识别它。最后一件事,在我通过您的建议返回变量名称后,它给了我一个包含 7 个变量的列表。当我使用我最初做的代码返回重要变量时,它给了我一个更长的重要变量列表。为什么是这样?再次感谢您的所有帮助。我真的很感激!

【问题讨论】:

    标签: python scikit-learn random-forest feature-selection


    【解决方案1】:

    Feature Importances 返回一个数组,其中每个索引对应于训练集中该特征的估计特征重要性。内部没有排序,它与训练期间赋予它的特征一一对应。

    如果您将特征名称存储为 numpy 数组并确保它与传递给模型的特征一致,则可以利用 numpy 索引来执行此操作。

    importances = rf.feature_importances_
    important_names = feature_names[importances > np.mean(importances)]
    print important_names
    

    【讨论】:

    • 感谢您的快速响应。我已将 feature_names 存储在一个 numpy 数组中,如果您方便时可以查看一下,我将编辑我的评论以包含代码。
    • 重要性如何解释?假设您有两个具有重要性 [0.8,0.2] 的特征,这是否意味着第一个特征占预测的 80% 或......?
    【解决方案2】:

    这是我用来打印和绘制特征重要性的内容,包括名称,而不仅仅是值

    importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(clf.feature_importances_,3)})
    importances = importances.sort_values('importance',ascending=False).set_index('feature')
    print importances
    importances.plot.bar()
    

    完整示例

    from sklearn.ensemble import RandomForestClassifier
    from sklearn.cross_validation import train_test_split
    import numpy as np
    import pandas as pd
    
    # set vars
    predictors = ['x1','x2']
    response = 'y'
    
    X = df[predictors]
    y = df[response]
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20)
    
    # run model
    clf = RandomForestClassifier(max_features=5)
    clf.fit(X_train.values, y_train.values)
    
    #show to plot importances
    importances = pd.DataFrame({'feature':X_train.columns,'importance':np.round(clf.feature_importances_,3)})
    importances = importances.sort_values('importance',ascending=False).set_index('feature')
    print importances
    importances.plot.bar()
    

    【讨论】:

      【解决方案3】:

      获取变量解释:

      regressor.score(X, y)
      

      获取变量的重要性:

      importances = regressor.feature_importances_
      print(importances)
      

      【讨论】:

        猜你喜欢
        • 2020-05-16
        • 2020-08-19
        • 2015-09-28
        • 2021-05-09
        • 2016-07-23
        • 2014-09-03
        • 2017-07-19
        • 2021-08-29
        • 2022-01-18
        相关资源
        最近更新 更多