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

2024-04-19 22:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个词汇表,其中包括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的配方文档。请帮帮我。


Tags: forindexdocnames配方recipecorpusfeature
1条回答
网友
1楼 · 发布于 2024-04-19 22:31:01

尝试在TfidfVectorizer中增加ngram_range

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

编辑:的输出TfidfVectorizer是稀疏格式的TF-IDF矩阵(或者实际上是您所寻找格式的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

相关问题 更多 >