gpt4 book ai didi

python - 获取 SelectKBest 函数 python 的特征名称

转载 作者:太空狗 更新时间:2023-10-30 01:50:08 25 4
gpt4 key购买 nike

我从 sklearn 实现了 SelectKBest,我想获得 K 个最佳列的名称,而不仅仅是每个列的值。

我需要做什么?

我的代码:

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

X_new.shape

X_new 是一个 numpy.ndarray,它有 k 个列,但没有列名。

最佳答案

您可以获得所选特征的索引

示例 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)']

关于python - 获取 SelectKBest 函数 python 的特征名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46927545/

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