在 Scikit Learn 中 运行 SelectKBest 之后获取特征名称的最简单方法

The easiest way for getting feature names after running SelectKBest in Scikit Learn

我想做监督学习

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

不过,我也想用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()

其中 returns 个布尔值数组。

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

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

feature_names = list(features_dataframe.columns.values)

您可以执行以下操作:

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)

这不需要循环。

# 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]

以下代码将帮助您找到前 K 个特征及其 F 分数。设,X 是 pandas 数据框,其列是所有特征,y 是 class 标签列表。

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)

对我来说这段代码工作正常而且更 'pythonic':

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

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

# 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]

Select 根据 chi2 的最佳 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`
# 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)

从 Scikit-learn 1.0 开始,transformers 有 get_feature_names_out 方法,这意味着你可以写

dataframe = pd.DataFrame(fit_transformed_features, columns=transformer.get_features_names_out())