簡體   English   中英

獲取SelectKBest函數python的功能名稱

[英]get feature names of SelectKBest function python

我從sklearn實現了SelectKBest,我想得到K最佳col的名稱,而不僅僅是每個col的值。

我需要做什么?

我的代碼:

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

X_new.shape

X_new是一個numpy.ndarray,它有k col但沒有col名稱。

您可以獲取所選要素的索引

例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))

現在,如果您真的想獲得列的實際名稱,我們需要使用pandas

例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()

結果

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

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

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

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

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

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

print(model.get_params)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM