【问题标题】:CountVectorizer gives empty vocabulary error is document is cardinal numberCountVectorizer 给出空词汇错误是文档是基数
【发布时间】:2016-08-15 11:50:59
【问题描述】:

我在将 sklearn CountVectorizer 与包含单词“one”的文档一起使用时遇到了问题。我发现当文档仅包含 POS 标签 CD(基数)的单词时会发生错误。以下文档都导致空词汇错误: ['一二'] ['一百']

ngram_code=1
cv = CountVectorizer(stop_words='english', analyzer='word', lowercase=True,\
token_pattern="[\w']+", ngram_range=(ngram_code, ngram_code))
cv_array = cv.fit_transform(['one', 'two'])

得到错误: ValueError:空词汇;也许文档只包含停用词

以下不会导致错误,因为(我认为)基数词与其他词混合: ['一','二','人']

有趣的是,在这种情况下,词汇表中只添加了“人”,没有添加“一”、“二”:

cv_array = cv.fit_transform(['one', 'two', 'people'])
cv.vocabulary_
Out[143]: {'people': 0}

作为单个 word 文档的另一个示例,['hello'] 可以正常工作,因为它不是基数:

cv_array = cv.fit_transform(['hello'])
cv.vocabulary_
Out[147]: {'hello': 0}

由于像“一”、“二”这样的词不是停用词,我希望它们由 CountVectorizer 处理。我该如何处理这些词?

补充:“系统”这个词我也遇到了同样的错误。为什么这个词会出错?

cv_array = cv.fit_transform(['system'])

ValueError:空词汇;也许文档只包含停用词

【问题讨论】:

    标签: scikit-learn


    【解决方案1】:

    他们之所以会得到一个空的词汇表是因为这些词属于 sklearn 使用的停用词列表。您可以查看列表here 或测试:

    >>> from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
    
    >>> 'one' in ENGLISH_STOP_WORDS 
    True
    
    >>> 'two' in ENGLISH_STOP_WORDS 
    True
    
    >>> 'system' in ENGLISH_STOP_WORDS 
    True
    

    如果您想处理这些单词,只需像这样初始化您的 CountVectorizer:

    cv = CountVectorizer(stop_words=None, ...
    

    【讨论】:

    • 非常感谢您的回答。它启发了我。当然 CountVectorizer 函数将使用 sklearn 停用词。我错误地查看了 nltk 停用词,这是我在调用 CountVectorizer 之前分别用于标记化的内容。我在做: from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) 'one' in stop_words Out[7]: False 这就是我感到困惑的原因。然而,有趣的是 nltk stop_words 和 sklearn stop_words 是不同的!非常感谢。
    • 很高兴为您提供帮助,您真的很倒霉,您测试的几乎所有单词都在 sklearn 的停用词集中。
    猜你喜欢
    • 2017-12-19
    • 2018-08-31
    • 2017-10-11
    • 2016-09-25
    • 2020-01-15
    • 2017-10-12
    • 2017-09-21
    • 2015-05-07
    • 2015-12-16
    相关资源
    最近更新 更多