【问题标题】:Why is TF-IDF calculation taking so much time?为什么 TF-IDF 计算要花这么多时间?
【发布时间】:2018-06-12 03:37:14
【问题描述】:

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

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

【问题讨论】:

    标签: python dictionary nlp tf-idf


    【解决方案1】:

    有些东西从粗略的一瞥中弹出, 1)没有看到方法 tb 是如何实现的,但是您似乎为每个单词调用tb(blob)。也许从 tb(blob) 为每个单词返回一次的任何内容创建一个对象会加快速度。 2)nltk 有自己的tfidf 实现,它会更加优化并且可以加快速度。 3)你可以做你的实现,但使用numpy而不是香草python,这肯定会加快速度。但即使这样,缓存结果并使用它们而不是多次调用可能很重的函数会是一个更好的主意.

    【讨论】:

      【解决方案2】:

      正如另一个答案提到的那样,你打电话给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)。

      【讨论】:

      • 我这样做了,但似乎没有任何区别。代码仍然运行了几个小时没有输出。
      • 在这种情况下,听起来您应该运行分析器 - 似乎您正在做的事情不会花费那么长时间。
      猜你喜欢
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      相关资源
      最近更新 更多