Python 为什么所有单词的TFIDF代码输出频率为0?

Python 为什么所有单词的TFIDF代码输出频率为0?,python,text,classification,Python,Text,Classification,我从中获得了这个tfidf,不知何故,我的输出文档为结果生成了所有0。有什么问题吗? 输出的示例是 河马0.0 希珀0.0 髋关节0.0 提示0.0 事后诸葛亮0.0 希尔0.0 搞笑0.0 谢谢你的帮助 # increment local count for word in doc_words: if word in terms_in_doc: terms_in_doc[word] += 1 else:

我从中获得了这个tfidf,不知何故,我的输出文档为结果生成了所有0。有什么问题吗? 输出的示例是 河马0.0 希珀0.0 髋关节0.0 提示0.0 事后诸葛亮0.0 希尔0.0 搞笑0.0

谢谢你的帮助

    # increment local count
    for word in doc_words:
        if word in terms_in_doc:
            terms_in_doc[word] += 1
        else:
            terms_in_doc[word]  = 1

    # increment global frequency
     for (word,freq) in terms_in_doc.items():
        if word in global_term_freq:
            global_term_freq[word] += 1
        else:
            global_term_freq[word]  = 1

     global_terms_in_doc[f] = terms_in_doc

print('working through documents.. ')
for f in all_files:

    writer = open(f + '_final', 'w')
    result = []
    # iterate over terms in f, calculate their tf-idf, put in new list
    max_freq = 0;
    for (term,freq) in global_terms_in_doc[f].items():
        if freq > max_freq:
            max_freq = freq
    for (term,freq) in global_terms_in_doc[f].items():
        idf = math.log(float(1 + num_docs) / float(1 + global_term_freq[term]))
        tfidf = float(freq) / float(max_freq) * float(idf)
        result.append([tfidf, term])

    # sort result on tfidf and write them in descending order
    result = sorted(result, reverse=True)
    for (tfidf, term) in result[:top_k]:
        if display_mode == 'both':
            writer.write(term + '\t' + str(tfidf) + '\n')
        else:
            writer.write(term + '\n')

tf idf的输出显然取决于您是否正确计算术语。如果你弄错了,那么结果会出乎意料。您可能希望输出每个字的原始计数以验证这一点。例如,“hipp”一词在当前文档和整个集合中出现了多少次

其他一些要点:

  • 不使用显式浮点进行除法,而是使用。它使您的代码更具可读性
  • 使用collections.defaultdict组合字典和计数器。这样可以避免在递增值之前检查值是否已存在。如果您不喜欢defaultdict,那么使用try-catch块——这比使用If语句更简单
  • 不要迭代字典的
    项()。它创建了一个全新的(键、值)对列表,并带来了巨大的计算和存储复杂性损失。迭代字典的键(
    某些字典中的k)并使用普通索引访问值(
    某些字典[k]
  • 在Python中计算列表的最大值

上述指针可能无法直接解决您的问题,但它们会使您的代码更易于阅读和理解(对于您和其他人而言),从而更容易查找和解决问题。

您将不得不隔离给您带来问题的部分。这需要编写大量代码,而且您似乎正在使用第三方库来进行标记化。如果您也提到/包含了该部分,那会有帮助。您好,很抱歉,刚刚编辑过,现在可以帮助我吗?如果您在最后的
for
循环中放入
assert tfidf==0.0,term
会发生什么情况?我得到一个错误,语法无效。因为您似乎对自己编写的代码有问题,可能值得尝试与原始代码的作者联系。d中任何术语的最大频率的除法实际上是tf的第三个备选定义,就在您引用的部分下面。很好。在再次阅读代码之后,我意识到我指出的问题根本不是真正的问题。我已经更新了我的答案。