Skip to main content
 首页 » 编程设计

python之了解 sklearn.feature_extraction.text 的 CountVectorizer 类中的 _count_vocab 方法

2024年11月01日10jirigala

我在 CountVectorizer 中使用 fit_transform 方法,我正在通读代码以尝试理解它在做什么。我对 CountVectorizer 中的 _count_vocab 方法有点困惑,特别是在嵌套的 for 循环下。对于原始文档,我有一个句子列表,并且 fixed_vocab = False。

def _count_vocab(self, raw_documents, fixed_vocab): 
    """Create sparse feature matrix, and vocabulary where fixed_vocab=False""" 
    if fixed_vocab: 
        vocabulary = self.vocabulary_ 
    else: 
        # Add a new value when a new vocabulary item is seen 
        vocabulary = defaultdict(None) 
        vocabulary.default_factory = vocabulary.__len__ 
 
    analyze = self.build_analyzer() 
    j_indices = _make_int_array() 
    indptr = _make_int_array() 
    indptr.append(0) 
    for doc in raw_documents: 
        for feature in analyze(doc): 
            try: 
                j_indices.append(vocabulary[feature]) 
            except KeyError: 
                # Ignore out-of-vocabulary items for fixed_vocab=True 
                continue 
        indptr.append(len(j_indices)) 
    if not fixed_vocab: 
        # disable defaultdict behaviour 
        vocabulary = dict(vocabulary) 
        if not vocabulary: 
            raise ValueError("empty vocabulary; perhaps the documents only" 
                             " contain stop words") 
 
    # some Python/Scipy versions won't accept an array.array: 
    if j_indices: 
        j_indices = np.frombuffer(j_indices, dtype=np.intc) 
    else: 
        j_indices = np.array([], dtype=np.int32) 
    indptr = np.frombuffer(indptr, dtype=np.intc) 
    values = np.ones(len(j_indices)) 
 
    X = sp.csr_matrix((values, j_indices, indptr), 
                      shape=(len(indptr) - 1, len(vocabulary)), 
                      dtype=self.dtype) 
    X.sum_duplicates() 
    return vocabulary, X 

这里的词汇表是一个空的 defaultdict 对象。因此 j_indices 不会追加元素,因为词汇表是空的,所以词汇表 [feature] 返回一个错误并且错误被忽略,继续下一个 for 循环迭代。它将继续对 raw_documents 中的所有文档以及 analyze(doc) 返回的标记中的所有功能执行此操作。最后,j_indices 和 indptr 是空的 array.array 对象。

我以为 _count_vocab 会创建自己的词汇对象,并在遇到新词汇时附加值,但它看起来不像。

在这种情况下,我应该向它提供我自己的词汇表吗?我没有字典,请问哪里可以弄到字典?

感谢您的帮助。

请您参考如下方法:

vocabulary[feature] returns an error and the error is ignored

没有错误,因为 vocabulary 是一个 defaultdict。发生的事情是

>>> vocabulary = defaultdict(None) 
>>> vocabulary.default_factory = vocabulary.__len__ 
>>> j_indices = [] 
>>> analyzed = ["foo", "bar", "baz", "foo", "quux"] 
>>> for feature in analyzed: 
...     j = vocabulary[feature] 
...     print("%s %d" % (feature, j)) 
...     j_indices.append(j) 
...      
foo 0 
bar 1 
baz 2 
foo 0 
quux 3 

结果

>>> dict(vocabulary) 
{'bar': 1, 'foo': 0, 'baz': 2, 'quux': 3} 
>>> j_indices 
[0, 1, 2, 0, 3] 

因此这段代码可以正常工作。 KeyError 捕获是针对 fixed_vocab=True 的情况。