使用sklearn在Python中计算n-grams的TF-IDF

10

我有一个包含以下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中的食谱文档。 请帮我。

2
请查看TfidfVectorizer中的tokenizertoken_patternngram_range参数。 - Vivek Kumar
2个回答

22

尝试增加TfidfVectorizer中的ngram_range

tfidf = TfidfVectorizer(vocabulary = myvocabulary, stop_words = 'english', ngram_range=(1,2))

编辑:TfidfVectorizer的输出是稀疏格式的TF-IDF矩阵(实际上是您要查找的格式的转置)。您可以像这样打印出其内容:

feature_names = tfidf.get_feature_names()
corpus_index = [n for n in corpus]
rows, cols = tfs.nonzero()
for row, col in zip(rows, cols):
    print((feature_names[col], corpus_index[row]), tfs[row, col])

应该产生什么结果

('biscuit pudding', 1) 0.646128915046
('chocolates', 1) 0.763228291628
('chocolates', 2) 0.508542320378
('tim tam', 2) 0.861036995944
('chocolates', 3) 0.508542320378
('fresh milk', 3) 0.861036995944
如果矩阵不是很大,以密集形式检查它可能更容易。 Pandas 使这非常方便:
import pandas as pd
df = pd.DataFrame(tfs.T.todense(), index=feature_names, columns=corpus_index)
print(df)

这导致

                        1         2         3
tim tam          0.000000  0.861037  0.000000
jam              0.000000  0.000000  0.000000
fresh milk       0.000000  0.000000  0.861037
chocolates       0.763228  0.508542  0.508542
biscuit pudding  0.646129  0.000000  0.000000

1
非常感谢。它有效了 :) 有什么方法可以查看我的TF-IDF矩阵吗?“我想通过使用语料库中的配方文档来获取我的词汇术语的TD-IDF矩阵。换句话说,矩阵的行代表我的词汇,而矩阵的列代表我语料库的配方文档。” - user8566323

1

@user8566323 尝试使用

df = pd.DataFrame(tfs.todense(), index=feature_names, columns=corpus_index)

替代

df = pd.DataFrame(tfs.T.todense(), index=feature_names, columns=corpus_index)

即在不对矩阵进行转置(T)的情况下。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接