【问题标题】:Why does CountVectorizer throw an "Empty Vocabulary error" for a bigram when there are two words?当有两个单词时,为什么 CountVectorizer 会为二元组抛出“空词汇错误”?
【发布时间】:2017-10-12 05:07:06
【问题描述】:

我有一个 CountVectorizer:

word_vectorizer = CountVectorizer(stop_words=None, ngram_range=(2,2), analyzer='word')

实现该矢量化器:

X = word_vectorizer.fit_transform(group['cleanComments'])

抛出此错误:

Traceback (most recent call last):

  File "<ipython-input-63-d261e44b8cce>", line 1, in <module>
    runfile('C:/Users/taca/Documents/Work/Python/Text Analytics/owccomments.py', wdir='C:/Users/taca/Documents/Work/Python/Text Analytics')

  File "C:\Users\taca\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)

  File "C:\Users\taca\AppData\Local\Continuum\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/taca/Documents/Work/Python/Text Analytics/owccomments.py", line 38, in <module>
    X = word_vectorizer.fit_transform(group['cleanComments'])

  File "C:\Users\taca\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 839, in fit_transform
    self.fixed_vocabulary_)

  File "C:\Users\taca\AppData\Local\Continuum\Anaconda3\lib\site-packages\sklearn\feature_extraction\text.py", line 781, in _count_vocab
    raise ValueError("empty vocabulary; perhaps the documents only"

ValueError: empty vocabulary; perhaps the documents only contain stop words

当 nGram 从中提取的文档是以下字符串时会发生此错误:“duplicate q”。文档为“ ”的任何时候都会发生这种情况。

为什么 CountVectorizer 不选择 q(或任何单个字母)作为有效词?是否有任何全面的地方列出了 CountVectorizer 引发此错误的可能原因?

编辑: 我对错误本身进行了更多挖掘,看起来它与词汇表有关。我假设标准词汇表不接受单个字母作为单词,但我不确定如何解决这个问题。

【问题讨论】:

  • 你能举出group['cleanComments']中的行的例子吗?它看起来像什么?

标签: python scikit-learn countvectorizer


【解决方案1】:

_count_vocab() 函数抛出此错误,这是CountVectorizer 类的一个方法。该类带有一个token_pattern,它定义了什么是一个单词。 token_pattern 参数说明的文档:

默认正则表达式选择 2 个或更多字母数字字符的标记

我们可以在__init__ 的默认参数中明确看到这一点:

token_pattern=r"(?u)\b\w\w+\b"

如果您想允许单字母单词,只需从此模式中删除第一个 \w 并在实例化您的 CountVectorizer 时显式设置 token_pattern

CountVectorizer(token_pattern=r"(?u)\b\w+\b", 
                stop_words=None, ngram_range=(2,2), analyzer='word')

【讨论】:

  • 完美 - 非常感谢。我慢慢地发现,一旦你进入杂草,一般来说,Sklearn 和 Python 的功能远不止这些。
猜你喜欢
  • 2016-10-18
  • 2017-09-21
  • 2016-08-15
  • 2017-10-11
  • 2018-08-31
  • 2016-09-25
  • 2020-01-15
  • 2017-12-19
  • 2020-12-05
相关资源
最近更新 更多