我有一个词汇表,其中包括n个字母,如下所示。
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克,以及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值时,我的代码没有检测到n个grams(bigrams),例如biscuit pudding
。请让我知道我在哪里弄错了密码。
我想通过使用corpus
中的配方文档获得myvocabulary
项的TD-IDF矩阵。换句话说,矩阵的行表示myvocabulary
,矩阵的列表示mycorpus
的配方文档。请帮帮我。
尝试在
TfidfVectorizer
中增加ngram_range
:编辑:的输出
TfidfVectorizer
是稀疏格式的TF-IDF矩阵(或者实际上是您所寻找格式的TF-IDF矩阵的转置)。您可以打印其内容,例如:会屈服的
如果矩阵不太大,可能更容易以密集的形式检查它。
Pandas
使这非常方便:这将导致
相关问题 更多 >
编程相关推荐