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

标签 python scikit-learn nlp tf-idf

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

最佳答案

尝试增加 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

关于python - 在 python 中使用 sklearn 为 n-gram 计算 TF-IDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580932/

相关文章:

python - Scikit learn中的R2值是怎么计算出来的?

python - "KeyError: 0"与 xgboost、scikit-learn 和 pandas

deep-learning - BERT 输出不确定

python - 如何在 Python 中使用 NLP、RegEx 查找句子中的日期

python - 无法使用 "Hello Analytics API"从 Google Analytics 获取数据

Python Bool 和 int 比较和索引列表上的 boolean 值

python - argparse 命令行 - 给定路径后的选项

python - scikit-learn:标记化时不要分隔带连字符的单词

python - count() 和 concordance() 给出不同的计数

python - 按列表中元组的顺序将多个元组列表组合成新的元组列表(python3)