gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:52:55 25 4
gpt4 key购买 nike

我想做监督学习。

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

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

返回 bool 值数组。

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

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

feature_names = list(features_dataframe.columns.values)

最佳答案

这不需要循环。

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

关于python - 在 Scikit Learn 中运行 SelectKBest 后获取特征名称的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39839112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com