如何在修剪tfidfvectorizer后检查术语是否为空

问题描述 投票:1回答:1

我正在使用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

但是,这种情况无法奏效。有办法解决这个问题吗?

所有答案和评论都非常感谢。谢谢

python-3.x scikit-learn tfidfvectorizer
1个回答
2
投票

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

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,因为我的文档中的所有单词都是英语停用词。 (如果删除上面代码段中的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
© www.soinside.com 2019 - 2024. All rights reserved.