理解卡方特征选择的问题

5 投票
1 回答
2569 浏览
提问于 2025-04-16 12:15

我一直在搞不懂卡方特征选择。现在我有两个类别,正类和负类,每个类别里都有不同的词和词频。我需要用卡方特征选择来提取每个类别最具代表性的词。不过问题是,我得到的正类和负类的词完全一样。下面是我用来选择特征的Python代码:

#!/usr/bin/python

# import the necessary libraries
import math

class ChiFeatureSelector:
    def __init__(self, extCorpus, lookupCorpus):
        # store the extraction corpus and lookup corpus
        self.extCorpus = extCorpus
        self.lookupCorpus = lookupCorpus

    def select(self, outPath):
            # dictionary of chi-squared scores
        scores = {}

        # loop over the words in the extraction corpus
        for w in self.extCorpus.getTerms():
            # build the chi-squared table
            n11 = float(self.extCorpus.getTermCount(w))
            n10 = float(self.lookupCorpus.getTermCount(w))
            n01 = float(self.extCorpus.getTotalDocs() - n11)
            n00 = float(self.lookupCorpus.getTotalDocs() - n10)

            # perform the chi-squared calculation and store
            # the score in the dictionary
            a = n11 + n10 + n01 + n00
            b = ((n11 * n00) - (n10 * n01)) ** 2
            c = (n11 + n01) * (n11 + n10) * (n10 + n00) * (n01 + n00)
            chi = (a * b) / c
            scores[w] = chi

        # sort the scores in descending order
        scores = sorted([(v, k) for (k, v) in scores.items()], reverse = True)
        i = 0

        for (v, k) in scores:
            print str(k) + " : " + str(v)
            i += 1

            if i == 10:
                break

这是我如何使用这个类的(为了简洁省略了一些代码,另外,我已经检查过这两个数据集里没有完全相同的数据)。

# perform positive ngram feature selection
print "positive:\n"
f = ChiFeatureSelector(posCorpus, negCorpus)
f.select(posOutputPath)

print "\nnegative:\n"
# perform negative ngram feature selection
f = ChiFeatureSelector(negCorpus, posCorpus)
f.select(negOutputPath)

我觉得问题可能出在我计算词/文档表的时候,但我不太确定。也许我对某些东西理解得不够透彻。有没有人能给我指个方向?

1 个回答

2

在两个类别的情况下,如果交换这两个数据集,特征的卡方排名是一样的。这些特征是两个类别之间差异最大的。

撰写回答