用于特征选择的 Sklearn Chi2

Sklearn Chi2 For Feature Selection

我正在学习用于特征选择的 chi2,并遇到了像 this

这样的代码

然而,我对 chi2 的理解是,更高的分数意味着该特征 更多 独立(因此对模型的用处较小),因此我们会对具有以下特征的特征感兴趣最低分。但是,使用 scikit 学习 SelectKBest,选择器 returns 具有 最高 chi2 分数的值。我对使用 chi2 测试的理解不正确吗?还是 sklearn 中的 chi2 分数会产生 chi2 统计数据以外的其他东西?

看下面的代码了解我的意思(大部分是从上面link复制的,除了结尾)

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

# Load iris data
iris = load_iris()

# Create features and target
X = iris.data
y = iris.target

# Convert to categorical data by converting data to integers
X = X.astype(int)

# Select two features with highest chi-squared statistics
chi2_selector = SelectKBest(chi2, k=2)
chi2_selector.fit(X, y)

# Look at scores returned from the selector for each feature
chi2_scores = pd.DataFrame(list(zip(iris.feature_names, chi2_selector.scores_, chi2_selector.pvalues_)), columns=['ftr', 'score', 'pval'])
chi2_scores

# you can see that the kbest returned from SelectKBest 
#+ were the two features with the _highest_ score
kbest = np.asarray(iris.feature_names)[chi2_selector.get_support()]
kbest

你的理解是反的。

chi2 检验的原假设是 "two categorical variables are independent"。因此,更高的 chi2 统计值意味着 "two categorical variables are dependent" 并且对分类更有用。

SelectKBest 根据较高的 chi2 值为您提供最好的两个 (k=2) 特征。因此,您需要获得它提供的那些功能,而不是在 chi2 选择器上获得 "other features"。

您从 chi2_selector.scores_ 获得 chi2 统计数据并从 chi2_selector.get_support() 获得最佳特征是正确的。它会给你 'petal length (cm)' 和 'petal width (cm)' 作为基于独立测试的 chi2 测试的前 2 个特征。希望它能澄清这个算法。