python - 如何在数据集上计算 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?有什么建议么?我应该转换成字典还是有另一种可能性?
解决方案
您可以执行以下操作。假设你得到了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}
推荐阅读
- javascript - Cannot read property 'online' of undefined
- python - FastAPI:如何通过 API 下载字节
- java - @PutMapping 的 JUnit RestControllerTest 抛出 InvocationTargetException
- java - 调用存储过程时返回相同的记录
- javascript - Chrome Mobile 中的隐藏 URL 栏调整大小问题是否有最新修复?
- django - 如何在自定义分页django rest框架中为每页添加多个项目
- python - 是否可以使用 discord.py 将自定义反应图像文件从您的计算机添加到您的消息中?
- bash - 循环遍历日期 Mac OSX Terminal Bash
- jquery - 从nodejs发送数据到html页面
- sql - 具有两列的 T-SQL 顺序更新