首页 > 解决方案 > 为什么 TF-IDF 计算要花这么多时间?

问题描述

我在我的文档语料库中使用此处的 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

问题是,它只是继续运行,没有显示任何超出Top words in document 1. 为什么计算需要这么长时间scores?我已经让它运行了一个小时,并且代码还没有终止。早些时候,我尝试了 50 个长度更短的 txt 文件的代码(例如,平均 2-3 段),它能够立即显示 TF-IDF 分数。3 个 270 页的文档有什么问题?

标签: pythondictionarynlptf-idf

解决方案


正如另一个答案提到的那样,您打电话tb(blob)太多了;对于一个包含 N 个单词的文档,您将其称为 N^2 次以上。那总是会很慢。您需要进行如下更改:

for index, blob in enumerate(bloblist):
    print("Top words in document {}".format(index + 1))
    # XXX use textblob here just once
    tblob = tb(blob)
    scores = {word: tfidf(word, tblob, bloblist) for word in tblob.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

您还需要更改 tfidf 函数,以便它们每次都使用tblob而不是调用。tb(blob)


推荐阅读