【问题标题】:The easiest way for getting feature names after running SelectKBest in Scikit Learn在 Scikit Learn 中运行 SelectKBest 后获取特征名称的最简单方法
【发布时间】:2017-02-11 20:11:19
【问题描述】:

我想做监督学习。

到目前为止,我知道对所有特征进行监督学习。

不过,我也想对 K 个最佳特征进行实验。

我阅读了文档,发现在 Scikit 中学习有 SelectKBest 方法。

不幸的是,在找到这些最佳功能后,我不确定如何创建新的数据框:

假设我想用 5 个最佳功能进行实验:

from sklearn.feature_selection import SelectKBest, f_classif
select_k_best_classifier = SelectKBest(score_func=f_classif, k=5).fit_transform(features_dataframe, targeted_class)

现在如果我要添加下一行:

dataframe = pd.DataFrame(select_k_best_classifier)

我将收到一个没有特征名称的新数据框(只有从 0 到 4 的索引)。

我应该将其替换为:

dataframe = pd.DataFrame(fit_transofrmed_features, columns=features_names)

我的问题是如何创建 features_names 列表??

我知道我应该使用:

 select_k_best_classifier.get_support()

返回布尔值数组。

数组中的真值代表右列的索引。

我应该如何将此布尔数组与我可以通过该方法获得的所有功能名称的数组一起使用:

feature_names = list(features_dataframe.columns.values)

【问题讨论】:

    标签: python pandas scikit-learn feature-selection


    【解决方案1】:
    # Fit the SelectKBest instance
    select_k_best_classifier = SelectKBest(score_func=f_classif, k=5).fit(features_dataframe, targeted_class)
    
    # Extract the required features
    new_features  = select_k_best_classifier.get_feature_names_out(features_names)
    

    【讨论】:

      【解决方案2】:

      根据 chi2 选择 Best 10 特征;

      from sklearn.feature_selection import SelectKBest, chi2
      
      KBest = SelectKBest(chi2, k=10).fit(X, y) 
      

      使用 get_support() 获取功能

      f = KBest.get_support(1) #the most important features
      

      创建名为 X_new 的新 df;

      X_new = X[X.columns[f]] # final features`
      

      【讨论】:

        【解决方案3】:

        还有另一种替代方法,但是,它不如上述解决方案快。

        # Use the selector to retrieve the best features
        X_new = select_k_best_classifier.fit_transform(train[feature_cols],train['is_attributed'])
        
        # Get back the kept features as a DataFrame with dropped columns as all 0s
        selected_features = pd.DataFrame(select_k_best_classifier.inverse_transform(X_new),
                                    index=train.index,
                                    columns= feature_cols)
        selected_columns = selected_features.columns[selected_features.var() !=0]
        

        【讨论】:

          【解决方案4】:

          这不需要循环。

          # Create and fit selector
          selector = SelectKBest(f_classif, k=5)
          selector.fit(features_df, target)
          # Get columns to keep and create new dataframe with those only
          cols = selector.get_support(indices=True)
          features_df_new = features_df.iloc[:,cols]
          

          【讨论】:

          • 一点修正:features_df_new = features_df.iloc[:,cols]
          • @volody 谢谢,我已经更新了答案。也许以前的语法可以工作?我不确定。
          【解决方案5】:

          以下代码将帮助您找到具有 F 分数的前 K 项功能。设,X 是 pandas 数据框,其列是所有特征,y 是类标签列表。

          import pandas as pd
          from sklearn.feature_selection import SelectKBest, f_classif
          #Suppose, we select 5 features with top 5 Fisher scores
          selector = SelectKBest(f_classif, k = 5)
          #New dataframe with the selected features for later use in the classifier. fit() method works too, if you want only the feature names and their corresponding scores
          X_new = selector.fit_transform(X, y)
          names = X.columns.values[selector.get_support()]
          scores = selector.scores_[selector.get_support()]
          names_scores = list(zip(names, scores))
          ns_df = pd.DataFrame(data = names_scores, columns=['Feat_names', 'F_Scores'])
          #Sort the dataframe for better visualization
          ns_df_sorted = ns_df.sort_values(['F_Scores', 'Feat_names'], ascending = [False, True])
          print(ns_df_sorted)
          

          【讨论】:

            【解决方案6】:

            对我来说,这段代码运行良好,而且更“pythonic”:

            mask = select_k_best_classifier.get_support()
            new_features = features_dataframe.columns[mask]
            

            【讨论】:

              【解决方案7】:

              您可以执行以下操作:

              mask = select_k_best_classifier.get_support() #list of booleans
              new_features = [] # The list of your K best features
              
              for bool, feature in zip(mask, feature_names):
                  if bool:
                      new_features.append(feature)
              

              然后更改您的功能名称:

              dataframe = pd.DataFrame(fit_transofrmed_features, columns=new_features)
              

              【讨论】:

              • 注意 .get_support() 必须应用于 SelectKBest(score_func=f_classif, k=5) (a class 'sklearn.feature_selection.univariate_selection.SelectKBest') ,而不是 SelectKBest(score_func=f_classif, k =5).fit_transform(X,Y)(一个numpy数组)
              猜你喜欢
              • 2019-06-30
              • 1970-01-01
              • 1970-01-01
              • 2016-06-23
              • 2021-11-02
              • 2020-10-31
              • 2016-12-29
              • 2016-05-27
              相关资源
              最近更新 更多