【问题标题】:Extract feature columns from training data set based on RFE output根据 RFE 输出从训练数据集中提取特征列
【发布时间】:2021-03-15 11:13:34
【问题描述】:

我想对具有 400 个特征/列的数据集(x_ vals)和一个标签(标签列)

我做了一个这样的训练和测试数据集:

X_train, X_test, y_train, y_test = train_test_split(x_vals,labels,test_size=0.2)

#然后我确定了哪些 x_train 列最能预测我的标签:

logreg = LogisticRegression()
rfe = RFE(logreg)
rfe = rfe.fit(X_train, y_train)
print(rfe.support_)
print(rfe.ranking_)

print(rfe.support_[0])

rfe.support_ 的输出是一个 True/False 列表,应该保存在数据集中;例如

[ True False False  True False  True False  True False False False  True
  True  True  True  True False False  True False False  True False  True
  True  True False  True  True  True  True  True False  True  True False

(实际上它的长度是 400)

我要做的就是找出最有效的方法,在 X_train 中仅保留 rfe.support_ 中显示为 True 的列(即仅保留预测特征)

我能想到一个缓慢的方法:

for each_col in dataframe:
      get the index of each_col
      get the value of that index in rfe.support_
      if the value == 'False': 
           remove col from dataframe

我觉得这很麻烦,在我开始之前我想知道有没有更pythonic的方法来做到这一点?

【问题讨论】:

    标签: python pandas scikit-learn


    【解决方案1】:

    您可以通过pd.drop 选择要删除的列名来实现此目的。示例代码:

    >>> df = pd.DataFrame(np.arange(12).reshape(3, 4),columns=['A', 'B', 'C', 'D'])
    >>> df
       A  B   C   D
    0  0  1   2   3
    1  4  5   6   7
    2  8  9  10  11
    >>> keep_list = [True, False, False, True]
    
    # Get the names of the columns which are False - i.e. columns to delete
    >>> columns_to_remove = df.columns.values[np.logical_not(keep_list)]
    >>> columns_to_remove
    array(['B', 'C'], dtype=object)
    
    # Returns our dataframe without columns 'B' and 'C'
    >>> df.drop(columns=columns_to_remove)
       A   D
    0  0   3
    1  4   7
    2  8  11
    

    说明

    我们要删除不保留的列。因此,我们使用np.logical_not(keep_list) 翻转逻辑。然后我们可以使用df.columns.values[np.logical_not(keep_list)] 索引我们希望删除的列名,然后使用df.drop(columns=columns_to_remove) 删除这些列。

    【讨论】:

      猜你喜欢
      • 2021-08-20
      • 2018-11-17
      • 2022-11-15
      • 2012-07-06
      • 2016-05-06
      • 2019-08-03
      • 2019-06-16
      • 2020-03-19
      • 2018-05-23
      相关资源
      最近更新 更多