繁体   English   中英

浮点列表中的最大值索引 | Python

[英]Index of max value from list of floats | Python

我看过很多帖子,但似乎没有任何帮助。

我想计算词频和逆文档频率; 深度学习中使用的词袋技术。 这段代码的目的只是计算公式。 我没有在这里实现人工神经网络。

下面是一个最小的代码示例。 在for循环之后我遇到了这个问题。

import math

docs = 1000
words_per_doc = 100  # length of doc
#word_freq = 10
#doc_freq = 100
dp = 4

print('Term Frequency Inverse Document Frequency')
# term, word_freq, doc_freq
words = [['the', 10, 100], ['python', 10, 900]]
tfidf_ = []
for idx, val in enumerate(words):
  print(words[idx][0] + ':')
  word_freq = words[idx][1]
  doc_freq = words[idx][2]

  tf = round(word_freq/words_per_doc, dp)
  idf = round(math.log10(docs/doc_freq), dp)
  tfidf = round((tf*idf), dp)
  print(str(tf) + ' * ' + str(idf) + ' = ' + str(tfidf))
  tfidf_.append(tfidf)
  print()

max_val = max(tfidf)
max_idx = tfidf.index(max_val)

#max_idx = tfidf.index(max(tfidf))
lowest_idx = 1 - max_idx

print('Therefore, \'' + words[max_idx][0] + '\' semantically is more important than  \'' + words[lowest_idx][0] + '\'.')


#print('log(N/|{d∈D:w∈W}|)')

错误:

line 25, in <module>
    max_val = max(tfidf)
TypeError: 'float' object is not iterable

您正在尝试在 function 上传递 tfidf 而不是 tfidf_

tfidf 是 int 并且 tfidf_ 是你的列表

所以代码应该是

max_val = max(tfidf_)
max_idx = tfidf_.index(max_val)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM