python - 为什么 TF-IDF 计算需要这么长时间?

标签 python dictionary nlp tf-idf

我使用 here 中的 TF-IDF 代码在我的文档库中,有 3 个 PDF 文档,每个文档长约 270 页。

# Calculating the Term Frequency, Inverse Document Frequency score
import os
import math
from textblob import TextBlob as tb

def tf(word, blob):
    return tb(blob).words.count(word) / len(tb(blob).words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in tb(blob).words)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)




# Stemming the articles
from nltk.stem import PorterStemmer
port = PorterStemmer()

bloblist = []
doclist = [pdf1, pdf2, pdf3]   # Defined earlier, not showing here as it is not relevant to the question
for doc in doclist:
    bloblist.append(port.stem(str(doc)))




# TF-IDF calculation on the stemmed articles
for index, blob in enumerate(bloblist):
    print("Top words in document {}".format(index + 1))
    scores = {word: tfidf(word, blob, bloblist) for word in tb(blob).words}
    sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    i=1
    for word, score in sorted_words[:5]:
        print("\tWord "+str(i)+": {}, TF-IDF: {}".format(word, round(score, 5)))
        i+=1

问题是,它只是继续运行,没有显示除文档 1 中的热门单词之外的任何内容。为什么计算分数需要这么长时间?我已经让它运行了一个小时了,代码还没有终止。早些时候,我尝试了 50 个奇怪的 txt 文件的代码,这些文件的长度要短得多(比如平均 2-3 段),并且能够立即显示 TF-IDF 分数。 3 个文档,每个文档 270 页,有什么问题吗?

最佳答案

有些东西是一眼就跳出来的, 1)在没有看到方法 tb 是如何实现的情况下,似乎您正在为每个单词调用 tb(blob) 。也许从每个单词返回一次的 tb(blob) 中创建一个对象会加快速度。 2)nltk 有自己的 tfidf 实现,它会更加优化并且可以加快速度。 3)你可以使用 numpy 而不是普通的 python 来实现你的实现,这肯定会加快速度。但即使这样,最好缓存结果并使用它们而不是调用可能会多次重载功能。

关于python - 为什么 TF-IDF 计算需要这么长时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50808889/

相关文章:

Python NLTK 解释一个固定的句子模式并将其标记化

python - 使用 reshape() 时 numpy 何时复制数组

python - 我如何安排在 django 中的某个时间发送电子邮件?

python - 生成基于文本的直方图

python - 查找可以最快说出的单词和单词组合

machine-learning - 使用 NLP 从字符串中查找意图的良好资源

Python - Facebook API - 需要一个工作示例

python - 如何在 Matplotlib 中为函数设置动画

arrays - 在 Swift 中解析具有错误设计结构的 JSON

python - 有没有一种 pythonic 方法来处理树结构的字典键?