简体   繁体   English

在 Python 中查找 tf-idf 时出现 fit_transform 错误

[英]Error in fit_transform while finding tf-idf in Python

import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
mylist = [
    'a a b c',
    'a c c c d e f',
    'a c d d d',
    'a d f',
]
df = pd.DataFrame({"texts": mylist})
tfidf_vectorizer = TfidfVectorizer(ngram_range=[1, 1])
tfidf_separate = tfidf_vectorizer.fit_transform(df["texts"])

I am trying to find tf-idf value for “d” in line 3. But, it is showing me empty vocabulary error "ValueError: empty vocabulary; perhaps the documents only contain stop words".我试图在第 3 行中找到“d”的 tf-idf 值。但是,它向我显示空词汇错误“ValueError:空词汇;也许文档只包含停用词”。

Any advice on how to resolve the error would be appreciated!任何有关如何解决错误的建议将不胜感激!

You can do it like this:你可以这样做:

  • define analyzer='char' so that TfidfVectorizer works with the letters;定义analyzer='char'以便 TfidfVectorizer 使用字母;
  • find the index of d in the vocabulary and use it在词汇表中找到d的索引并使用它
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
mylist = [
    'a a b c',
    'a c c c d e f',
    'a c d d d',
    'a d f',
]
df = pd.DataFrame({"texts": mylist})
tfidf_vectorizer = TfidfVectorizer(ngram_range=[1, 1], analyzer='char')
tfidf_separate = tfidf_vectorizer.fit_transform(df["texts"])
ind = tfidf_vectorizer.vocabulary_['d']
tfidf_separate.todense()[2, ind]
>>> 0.6490674853546846

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM