我有一个包含以下n元组的词汇表。
myvocabulary = ['tim tam', 'jam', 'fresh milk', 'chocolates', 'biscuit pudding']
我希望使用这些词来计算 TF-IDF 值。
我还有一个语料库的字典,如下所示(key=食谱编号,value=食谱)。
corpus = {1: "making chocolates biscuit pudding easy first get your favourite biscuit chocolates", 2: "tim tam drink new recipe that yummy and tasty more thicker than typical milkshake that uses normal chocolates", 3: "making chocolates drink different way using fresh milk egg"}
我目前正在使用以下代码。
from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(vocabulary = myvocabulary, stop_words = 'english')
tfs = tfidf.fit_transform(corpus.values())
现在我正在打印食谱1的令牌或n-gram,连同以下的tF-IDF值一起在corpus
中。
feature_names = tfidf.get_feature_names()
doc = 0
feature_index = tfs[doc,:].nonzero()[1]
tfidf_scores = zip(feature_index, [tfs[doc, x] for x in feature_index])
for w, s in [(feature_names[i], s) for (i, s) in tfidf_scores]:
print(w, s)
我得到的结果是巧克力1.0
。 然而,当计算TF-IDF值时,我的代码没有检测到n-grams(bigrams),如biscuit pudding
。 请告诉我我的代码哪里出错了。我想通过使用
corpus
中的食谱文档来获取myvocabulary
术语的TD-IDF矩阵。 换句话说,矩阵的行表示myvocabulary
,矩阵的列表示我的corpus
中的食谱文档。 请帮我。
tokenizer
、token_pattern
和ngram_range
参数。 - Vivek Kumar