如何在数据集上计算TF-IDF?

问题描述 投票:0回答:1

我有文章的数据集,以及这些文章中每个单词出现了多少:如何计算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?有什么建议么?我应该转换成词典还是有其他可能性?

python pandas numpy tf-idf tfidfvectorizer
1个回答
1
投票

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

然后您可以重建语料库(单词的顺序与TF-IDF的频率无关紧要)。

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

:这假定您的文本(一旦重建)可以容纳在内存中。大多数数据集都是。但是如果不是这样,并且如果您想直接从docs开始使用TF-IDF,则可能必须自己实现。

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}
© www.soinside.com 2019 - 2024. All rights reserved.