python - 为什么这个 TFIDF 代码输出所有单词的频率为 0?

标签 python text classification

我从 yebrahim 得到了这个 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”一词在当前文档以及整个集合中出现了多少次?

其他一些提示:

  • 不要使用显式 float 进行除法,而是使用 from __future__ import division 。它使您的代码更具可读性。
  • 使用 collections.defaultdict 将字典与计数器组合起来。这避免了在增加值之前必须检查该值是否已经存在。如果你不喜欢defaultdict,那么使用try-catch block ——它是faster而不是使用 if 语句。
  • 不要迭代字典的items()。它创建了一个全新的(键,值)对列表,并带来了巨大的计算和存储复杂性损失。迭代字典的键(for k in some_dictionary)并使用普通索引来访问值 (some_dictionary[k])。
  • You don't need a for loop在 Python 中计算列表的最大值。

以上提示可能无法直接解决您的问题,但它们将使您的代码更易于阅读和理解(对于您和 SO 上的人员而言),从而更容易定位和解决问题。

关于python - 为什么这个 TFIDF 代码输出所有单词的频率为 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16139464/

相关文章:

python - 滑动滑动窗口 "intelligently"?

python - 在 Tensorflow 中,如何将张量/数组添加到已包含多个张量/数组的张量/数组中。 tf.concat 和 st.stack 需要相同的形状

python - 列表推导比 for 循环有什么优势?

python - 在 Python 中限制函数执行

html - scrapy - 如何从 'div' 获取文本

python - 使用 elide 隐藏文本时的性能影响

java - 你能给我推荐一个好的 Java 库来使用 vector 空间模型执行文本分类吗?

python - 修改 Python 类

python - 需要帮助在同一目录中的文件夹中创建 txt 文件

python - 如何使用sklearn同时获得概率和标签预测