编程语言
首页 > 编程语言> > python – 在Scikit Learn中运行SelectKBest后获取功能名称的最简单方法

python – 在Scikit Learn中运行SelectKBest后获取功能名称的最简单方法

作者:互联网

我想进行有监督的学习.

到现在为止,我知道要对所有功能进行监督学习.

但是,我还想进行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)

解决方法:

您可以执行以下操作:

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)

标签:python,pandas,scikit-learn,feature-selection
来源: https://codeday.me/bug/20190928/1828365.html