繁体   English   中英

在 python 中使用 sklearn 为 n-gram 计算 TF-IDF

[英]Calculate TF-IDF using sklearn for n-grams in python

我有一个包含 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 值时不会检测 n-gram(二元语法),例如biscuit pudding 请让我知道我在哪里弄错了代码。

我想通过使用corpus中的食谱文档来获取myvocabulary术语的 TD-IDF 矩阵。 换句话说,矩阵的行代表我的myvocabulary表,矩阵的列代表我的corpus的食谱文档。 请帮我。

尝试增加ngram_range中的TfidfVectorizer

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

@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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM