SelectKBest (chi2) 如何计算分数?

How SelectKBest (chi2) calculates score?

我试图通过将特征选择方法应用于我的数据集来找到最有价值的特征。我现在使用 SelectKBest 函数。我可以生成分值并根据需要对它们进行排序,但我不明白这个分值是如何计算的。我知道理论上高分更有价值,但我需要一个数学公式或一个例子来计算深入学习这个的分数。

bestfeatures = SelectKBest(score_func=chi2, k=10)
fit = bestfeatures.fit(dataValues, dataTargetEncoded)
feat_importances = pd.Series(fit.scores_, index=dataValues.columns)
topFatures = feat_importances.nlargest(50).copy().index.values

print("TOP 50 Features (Best to worst) :\n")
print(topFatures)

提前致谢

假设您有一个特征和一个具有 3 个可能值的目标

X = np.array([3.4, 3.4, 3. , 2.8, 2.7, 2.9, 3.3, 3. , 3.8, 2.5])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 2])

     X  y
0  3.4  0
1  3.4  0
2  3.0  0
3  2.8  1
4  2.7  1
5  2.9  1
6  3.3  2
7  3.0  2
8  3.8  2
9  2.5  2

First 我们将目标二值化

y = LabelBinarizer().fit_transform(y)

     X  y1  y2  y3
0  3.4   1   0   0
1  3.4   1   0   0
2  3.0   1   0   0
3  2.8   0   1   0
4  2.7   0   1   0
5  2.9   0   1   0
6  3.3   0   0   1
7  3.0   0   0   1
8  3.8   0   0   1
9  2.5   0   0   1

然后在特征和目标之间进行点积,即将所有特征值乘以class值

observed = y.T.dot(X) 
>>> observed 
array([ 9.8,  8.4, 12.6])

接下来对特征值求和并计算class频率

feature_count = X.sum(axis=0).reshape(1, -1)
class_prob = y.mean(axis=0).reshape(1, -1)

>>> class_prob, feature_count
(array([[0.3, 0.3, 0.4]]), array([[30.8]]))

现在和第一步一样,我们取点积,得到期望矩阵和观测矩阵

expected = np.dot(class_prob.T, feature_count)
>>> expected 
array([[ 9.24],[ 9.24],[12.32]])

最后我们计算出一个chi^2值:

chi2 = ((observed.reshape(-1,1) - expected) ** 2 / expected).sum(axis=0)
>>> chi2 
array([0.11666667])

我们有一个chi^2值,现在我们需要判断它有多极端。为此,我们使用具有 number of classes - 1 自由度的 chi^2 distribution 并计算从 chi^2 到无穷大的面积,以获得 chi^2 与我们所得到的相同或更极端的概率。这是一个 p 值。 (使用来自 scipy 的卡方生存函数)

p = scipy.special.chdtrc(3 - 1, chi2)
>>> p
array([0.94333545])

SelectKBest比较:

s = SelectKBest(chi2, k=1)
s.fit(X.reshape(-1,1),y)
>>> s.scores_, s.pvalues_
(array([0.11666667]), [0.943335449873492])