获取功能名称形式selectKbest

问题描述 投票:1回答:2

我使用Scikit学习selectKbest来选择最好的功能,其中大约500个来自900。如下所示,其中d是所有特征的数据帧。

from sklearn.feature_selection import SelectKBest, chi2, f_classif
X_new = SelectKBest(chi2, k=491).fit_transform(d, label_vs)

当我现在打印X_new时,它只给我数字,但我需要所选功能的名称以便以后使用它们。

我试过像X_new.dtype.names这样的东西,但我没有回来任何东西,我试图将X_new转换成数据框,但我得到的唯一列名称是

1, 2, 3, 4... 

那么有没有办法知道所选功能的名称是什么?

python numpy scikit-learn nlp feature-selection
2个回答
1
投票

以下是使用get_support()的方法:

chY = SelectKBest(chi2, k=491)
X_new = chY.fit_transform(d, label_vs)
column_names = [column[0]  for column in zip(d.columns,chY.get_support()) if column[1]]

从@AI_Learning的回答中,您可以通过以下方式获取列名:

column_names = d.columns[chY.get_support()]

0
投票

您可以使用feature_selection的.get_support()参数来获取初始数据帧中的功能名称。

feature_selector = SelectKBest(chi2, k=491)
d.columns[feature_selector.get_support()]

工作范例:

from sklearn.datasets import load_digits
import pandas as pd
from sklearn.feature_selection import SelectKBest, chi2
X, y = load_digits(return_X_y=True)
df = pd.DataFrame(X, columns= ['feaure %s'%i for i in range(X.shape[1])])

feature_selector = SelectKBest(chi2, k=20)

X_new = feature_selector.fit_transform(df, y)
X_new.shape

df.columns[feature_selector.get_support()]

输出:

指数(['feaure 5','feaure 6','feaure 13','feaure 19','feaure 20','feaure 21','feaure 26','feaure 28','feaure 30','feaure 33','很少34','很少41','很少42','很少43','很少44','很少46','很少54','很重要58','很少61','很高兴62'],dtype ='object')

© www.soinside.com 2019 - 2024. All rights reserved.