首页 > 解决方案 > 如何在数据集上计算 TF-IDF?

问题描述

我有文章的数据集,这些文章中每个单词出现了多少:如何计算 TF-IDF?

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns; sns.set()
from sklearn.cluster import KMeans
import pandas as pd
import sklearn as sk
import math 

data = pd.read_csv('D:\\Datasets\\NIPS_1987-2015.csv', index_col ="word")

# retrieving row by loc method
first = data["1987_1"]
second = data["1987_2"]

print(first, "\n\n\n", second)

我得到这个数据库:

word
abalone        0
abbeel         0
abbott         0
abbreviate     0
abbreviated    0
          ..
zoo            0
zoom           0
zou            0
zoubin         0
zurich         0
Name: 1987_1, Length: 11463, dtype: int64 


 word
abalone        0
abbeel         0
abbott         0
abbreviate     0
abbreviated    0
          ..
zoo            0
zoom           0
zou            0
zoubin         0
zurich         0
Name: 1987_2, Length: 11463, dtype: int64

那么从这里如何计算TF-IDF?有什么建议么?我应该转换成字典还是有另一种可能性?

标签: pythonpandasnumpytf-idftfidfvectorizer

解决方案


您可以执行以下操作。假设你得到了docs一个对象列表,pd.Series每个对象代表单个文档的词频分布。

然后你可以重建一个语料库(单词的顺序并不重要,只是频率对 TF-IDF 很重要)。

最后,您使用sklearn.feature_extraction.text.TfidfVectorizer将您的语料库转换为 TF-IDF 值。

注意:这假设您的文本(一旦重建)可以适合内存。大多数数据集都是。但如果不是这种情况,并且如果您想要直接从 TF-IDF docs,您可能必须自己实现它。

import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

# docs = [pd.Series(...), pd.Series(..), ...]

rep_docs = [" ".join(d.repeat(d).index.values) for d in docs]

tfidf = TfidfVectorizer()
tfidf.fit(rep_docs)
res = tfidf.transform(rep_docs[:1])

print(res)
print(tfidf.vocabulary_)

产生,

# TF IDF values
(0, 10) 0.2773500981126146
(0, 8)  0.2773500981126146
(0, 5)  0.8320502943378437
(0, 4)  0.2773500981126146
(0, 1)  0.2773500981126146

# Vocabulary
{'sat': 8, 'the': 10, 'mat': 4, 'bark': 1, 'moon': 5, 'on': 7, 'at': 0, 'swam': 9, 'to': 11, 'ocean': 6, 'fish': 3, 'cat': 2}

推荐阅读