【发布时间】:2018-03-16 19:06:01
【问题描述】:
我有一个包含 n-gram 的词汇表,如下所示。
myvocabulary = ['tim tam', 'jam', 'fresh milk', 'chocolates', 'biscuit pudding']
我想用这些词来计算 TF-IDF 值。
我还有一个语料库字典如下(key = recipe number,value = recipe)。
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())
现在我正在corpus 中打印配方 1 的令牌或 n-gram 以及 tF-IDF 值,如下所示。
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)
我得到的结果是chocolates 1.0。但是,我的代码在计算 TF-IDF 值时没有检测到诸如biscuit pudding 之类的 n-grams(bigrams)。请让我知道我在哪里弄错了代码。
我想通过使用 corpus 中的配方文档来获取 myvocabulary 术语的 TD-IDF 矩阵。换句话说,矩阵的行代表myvocabulary,矩阵的列代表我corpus的食谱文档。请帮帮我。
【问题讨论】:
-
查看 TfidfVectorizer 中的
tokenizer、token_pattern和ngram_range参数。
标签: python scikit-learn nlp tf-idf