get feature names of SelectKBest function python

喜欢而已 提交于 2020-02-03 08:04:41

问题


I implemented SelectKBest from sklearn and I want to get the names of the K best col, not just the values of each col.

what do I need to do?

my code:

X_new = SelectKBest(chi2, k=2).fit_transform(X, y)

X_new.shape

X_new is a numpy.ndarray and it has k col but without the col names.


回答1:


You can get the indices of the selected features.

Example 1:

from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

iris = load_iris()
X, y = iris.data, iris.target

selector = SelectKBest(chi2, k=2)
selector.fit(X, y)

X_new = selector.transform(X)
X_new.shape
print(selector.get_support(indices=True))

Now if you really want to get the actual names of the columns we need to use pandas.

Example 2:

from sklearn.datasets import load_iris
from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2
import pandas as pd

iris = load_iris()
X = pd.DataFrame(iris.data, columns=iris.feature_names)
y = pd.DataFrame(iris.target)

selector = SelectKBest(chi2, k=2)
selector.fit(X, y)

X_new = selector.transform(X)
print(X_new.shape)

X.columns[selector.get_support(indices=True)]

# 1st way to get the list
vector_names = list(X.columns[selector.get_support(indices=True)])
print(vector_names)

#2nd way
X.columns[selector.get_support(indices=True)].tolist()

Result:

Index([u'petal length (cm)', u'petal width (cm)'], dtype='object')

['petal length (cm)', 'petal width (cm)']

['petal length (cm)', 'petal width (cm)']



回答2:


model= SelectKBest(f_classif, k=8).fit(X,Y)

Selected_feature_names=X.columns[model.get_support()]




回答3:


model=SelectKBest(k=5) model.fit(X,y)

print(model.get_params)



来源:https://stackoverflow.com/questions/46927545/get-feature-names-of-selectkbest-function-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!