【问题标题】:Python TfidfVectorizer throwing : empty vocabulary; perhaps the documents only contain stop words"Python TfidfVectorizer 抛出:空词汇;也许文件只包含停用词”
【发布时间】:2014-01-22 14:32:10
【问题描述】:

我正在尝试使用 Python 的 Tfidf 来转换文本语料库。 但是,当我尝试 fit_transform 时,我得到一个值错误 ValueError: empty words;也许文档只包含停用词。

In [69]: TfidfVectorizer().fit_transform(smallcorp)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-69-ac16344f3129> in <module>()
----> 1 TfidfVectorizer().fit_transform(smallcorp)

/Users/maxsong/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/text.pyc in fit_transform(self, raw_documents, y)
   1217         vectors : array, [n_samples, n_features]
   1218         """
-> 1219         X = super(TfidfVectorizer, self).fit_transform(raw_documents)
   1220         self._tfidf.fit(X)
   1221         # X is already a transformed view of raw_documents so

/Users/maxsong/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/text.pyc in fit_transform(self, raw_documents, y)
    778         max_features = self.max_features
    779 
--> 780         vocabulary, X = self._count_vocab(raw_documents, self.fixed_vocabulary)
    781         X = X.tocsc()
    782 

/Users/maxsong/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/text.pyc in _count_vocab(self, raw_documents, fixed_vocab)
    725             vocabulary = dict(vocabulary)
    726             if not vocabulary:
--> 727                 raise ValueError("empty vocabulary; perhaps the documents only"
    728                                  " contain stop words")
    729 

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

我在这里阅读了 SO 问题:Problems using a custom vocabulary for TfidfVectorizer scikit-learn 并尝试了 ogrisel 的建议,即使用 TfidfVectorizer(**params).build_analyzer()(dataset2) 来检查文本分析步骤的结果和这似乎按预期工作:下面的sn-p:

In [68]: TfidfVectorizer().build_analyzer()(smallcorp)
Out[68]: 
[u'due',
 u'to',
 u'lack',
 u'of',
 u'personal',
 u'biggest',
 u'education',
 u'and',
 u'husband',
 u'to',

还有什么我做错了吗?我正在喂它的语料库只是一根巨大的长字符串,中间有换行符。

谢谢!

【问题讨论】:

  • 我遇到了同样的问题,从 v0.19 降级到 0.18

标签: python pandas scikit-learn tf-idf


【解决方案1】:

我猜这是因为你只有一个字符串。尝试将其拆分为字符串列表,例如:

In [51]: smallcorp
Out[51]: 'Ah! Now I have done Philosophy,\nI have finished Law and Medicine,\nAnd sadly even Theology:\nTaken fierce pains, from end to end.\nNow here I am, a fool for sure!\nNo wiser than I was before:'

In [52]: tf = TfidfVectorizer()

In [53]: tf.fit_transform(smallcorp.split('\n'))
Out[53]: 
<6x28 sparse matrix of type '<type 'numpy.float64'>'
    with 31 stored elements in Compressed Sparse Row format>

【讨论】:

  • 这应该是正确的答案。关于此的文档的任何链接?我在任何地方都找不到它
  • 本文档中有一个例子。 scikit-learn.org/stable/modules/…(在第 4.2.3.3 节中,语料库变量)
【解决方案2】:

在 0.12 版本中,我们将最小文档频率设置为 2,这意味着只考虑出现至少两次的单词。为了使您的示例正常工作,您需要设置min_df=1。从 0.13 开始,这是默认设置。 所以我猜你使用的是 0.12,对吧?

【讨论】:

    【解决方案3】:

    如果你坚持只有一个字符串,你也可以把你的单个字符串作为一个元组。而不是:

    smallcorp = "your text"

    你宁愿把它放在一个元组中。

    In [22]: smallcorp = ("your text",)
    In [23]: tf.fit_transform(smallcorp)
    Out[23]: 
    <1x2 sparse matrix of type '<type 'numpy.float64'>'
        with 2 stored elements in Compressed Sparse Row format>
    

    【讨论】:

      【解决方案4】:

      我在大型语料库上运行 TF-IDF Python 3 脚本时遇到了类似的错误。一些小文件(显然)缺少关键字,引发错误消息。

      我尝试了几种解决方案(如果len(filtered = 0,则将虚拟字符串添加到我的filtered 列表中,...),但都没有帮助。最简单的解决方案是添加 try: ... except ... continue 表达式。

      pattern = "(?u)\\b[\\w-]+\\b"
      cv = CountVectorizer(token_pattern=pattern)
      
      # filtered is a list
      filtered = [w for w in filtered if not w in my_stopwords and not w.isdigit()]
      
      # ValueError:
      # cv.fit(text)
      # File "tfidf-sklearn.py", line 1675, in tfidf
      #   cv.fit(filtered)
      #   File "/home/victoria/venv/py37/lib/python3.7/site-packages/sklearn/feature_extraction/text.py", line 1024, in fit
      #   self.fit_transform(raw_documents)
      #   ...
      #   ValueError: empty vocabulary; perhaps the documents only contain stop words
      
      # Did not help:
      # https://stackoverflow.com/a/20933883/1904943
      #
      # if len(filtered) == 0:
      #     filtered = ['xxx', 'yyy', 'zzz']
      
      # Solution:
      try:
          cv.fit(filtered)
          cv.fit_transform(filtered)
          doc_freq_term_matrix = cv.transform(filtered)
      except ValueError:
          continue
      

      【讨论】:

      • 嘿@Victoria,在我看来,在这种情况下,您只是避免执行您想要的操作(矢量化)。你对这里的理解是什么?
      【解决方案5】:

      我也遇到了同样的问题。 将 int(nums) 列表转换为 str(nums) 列表没有帮助。 但我转换为:

      ['d'+str(nums) for nums in set] #where d is some letter which mention, we work with strings
      

      这有帮助。

      【讨论】:

        猜你喜欢
        • 2021-01-10
        • 1970-01-01
        • 2019-07-29
        • 2020-12-05
        • 2020-06-04
        • 2012-09-27
        • 2019-07-08
        相关资源
        最近更新 更多