簡體   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