【问题标题】:sklearn CountVectorizer output a matrix with empty rowssklearn CountVectorizer 输出一个空行的矩阵
【发布时间】:2015-08-04 06:32:24
【问题描述】:

我正在使用 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 中有几行全为零。为什么这可能?

【问题讨论】:

  • 您是否有可能只有一个字母的文档?标记器过滤掉这些。
  • @user3914041 是的。我认为这是可能的。你知道如何禁用删除一个字母吗?

标签: python numpy scikit-learn


【解决方案1】:

通过您的设置,仅包含一个字母单词的文档将提供全零数组。 您的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')

它应该可以工作。

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2018-04-08
    • 2021-03-22
    • 2022-12-01
    • 2016-07-27
    • 1970-01-01
    • 2018-03-20
    • 2015-09-11
    • 2019-04-13
    相关资源
    最近更新 更多