Skip to main content
 首页 » 编程设计

python之sklearn CountVectorizer 输出一个带有空行的矩阵

2024年10月24日19exmyth

我正在使用 CountVectorizer 为每个文档生成向量。就我而言,文档是包含 1-5 个单词的短文本。

for i, doc in enumerate(documents): 
    if doc: # make sure there is no empty document. 
        corpus.append(doc) 
 
countVectorizer = CountVectorizer() 
weight_arr = countVectorizer.fit_transform(corpus) 
 
for doc_index, count_vector in enumerate(weight_arr): 
    nonzero_feature_indice = count_vector.nonzero()[1] # [1]: unique column index 
    if nonzero_feature_indice.size == 0: 
        print "EMPTY ROW!" 

我使用 CountVectorizer 的默认参数。我不会删除停用词并设置任何可能生成空文档的阈值。

{'binary': False, 'lowercase': True, 'stop_words': None, 'decode_error': u'strict', 'vocabulary': None, 'tokenizer': None, 'encoding': u'utf-8', 'dtype': <type 'numpy.int64'>, 'analyzer': u'word', 'ngram_range': (1, 1), 'max_df': 1.0, 'min_df': 1, 'max_features': None, 'input': u'content', 'strip_accents': None, 'token_pattern': u'(?u)\\b\\w\\w+\\b', 'preprocessor': None} 

我发现 weight_arr 中有几行全为零。为什么这是可能的?

请您参考如下方法:

根据您的设置,只有一个字母单词的文档将给出全零数组。 您的 tokenizer 正在过滤单字母单词。

您没有指定任何内容,但默认使用以下标记模式:

'token_pattern': u'(?u)\\b\\w\\w+\\b' 

如果你想允许一个字母的词,你可以把它改成:

'token_pattern': u'(?u)\\b\\w+\\b' 

你只需要将它传递给构造函数:

countVectorizer = CountVectorizer(token_pattern=u'(?u)\\b\\w+\\b') 

它应该可以工作。