【问题标题】:How to check whether term is empty after pruning of tfidfvectorizer修剪tfidfvectorizer后如何检查术语是否为空
【发布时间】:2018-12-24 01:49:57
【问题描述】:

我正在使用 tfidfvectorizer 对来自许多不同语料库的术语进行评分。
这是我的代码

tfidf = TfidfVectorizer(ngram_range=(1,1), stop_words = 'english', min_df = 0.5)
for corpus in all_corpus:
    tfidf.fit_transform(corpus)

每个语料库中的文档数量是多种多样的,所以在构建词汇表时,有些语料库仍然是空的并返回错误:

after pruning, no terms remain. Try a lower min_df or higher max_df

我不想更改最小或最大 DF。我需要的是当没有术语时,跳过转换过程。所以我做了一个像下面这样的条件过滤器

for corpus in all_corpus:
    tfidf.fit_transform(corpus)
    if tfidf.shape[0] > 0:
    \\execute some code here

但是,条件不起作用。有没有办法解决这个问题?

非常感谢所有答案和 cmets。谢谢

【问题讨论】:

    标签: python-3.x scikit-learn tfidfvectorizer


    【解决方案1】:

    首先,我相信您的问题的一个最小工作示例如下:

    from sklearn.feature_extraction.text import TfidfVectorizer
    tfidf = TfidfVectorizer(ngram_range=(1,1), stop_words = 'english', min_df = 0.5)
    tfidf.fit_transform(['not I you'])
    

    我无法复制包含您共享的错误消息部分的错误消息,但这给了我一个ValueError,因为我文档中的所有单词都是英文停用词。 (如果在上面的 sn-p 中删除 stop_words = 'english',代码就会运行。)

    在 for 循环的情况下处理错误的一种方法是使用 try/except 块。

    for corpus in all_corpus:
        try:
            tfidf.fit_transform(corpus)
        except ValueError:
            print('Transforming process skipped')
            # Here you can do more stuff
            continue  # go to the beginning of the for-loop to start the next iteration
        # Here goes the rest of the code for corpus for which the transform functioned
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-06
      • 1970-01-01
      • 2017-11-15
      • 2020-05-29
      • 2018-04-02
      • 2016-04-05
      • 2018-01-08
      • 2020-09-25
      相关资源
      最近更新 更多