chi2#

sklearn.feature_selection.chi2(X, y)[source]#

计算每个非负特征和类之间的卡方统计量。

此分数可用于从 X 中选择具有最高卡方检验统计值(chi-squared statistic)的 n_features 个特征。X 必须仅包含非负整数特征值,例如布尔值或频率(例如,文档分类中的词项计数),与类别相关。

如果某些特征是连续的,你需要将它们分箱,例如使用 KBinsDiscretizer

回想一下,卡方检验衡量的是随机变量之间的依赖性,因此使用此函数可以“剔除”最有可能独立于类别且因此与分类无关的特征。

用户指南中阅读更多内容。

参数:
Xshape 为 (n_samples, n_features) 的 {array-like, sparse matrix}

样本向量。

yarray-like of shape (n_samples,)

目标向量(类别标签)。

返回:
chi2ndarray of shape (n_features,)

每个特征的卡方统计量。

p_valuesndarray of shape (n_features,)

每个特征的 P 值。

另请参阅

f_classif

分类任务中标签/特征之间的 ANOVA F 值。

f_regression

回归任务中标签/特征之间的 F 值。

注意事项

此算法的复杂度为 O(n_classes * n_features)。

示例

>>> import numpy as np
>>> from sklearn.feature_selection import chi2
>>> X = np.array([[1, 1, 3],
...               [0, 1, 5],
...               [5, 4, 1],
...               [6, 6, 2],
...               [1, 4, 0],
...               [0, 0, 0]])
>>> y = np.array([1, 1, 0, 0, 2, 2])
>>> chi2_stats, p_values = chi2(X, y)
>>> chi2_stats
array([15.3,  6.5       ,  8.9])
>>> p_values
array([0.000456, 0.0387, 0.0116 ])