[英]local variable might be referenced before assignment in Python
I'm going through some code that implements a decision tree learner.我正在研究一些实现决策树学习器的代码。 Here is the code:
这是代码:
def calculate_entropy(self, tags):
tags_counter = Counter()
if len(tags) > 0:
for tag in tags:
tags_counter[tag] += 1
classes_probs = [float(tags_counter[tag]) / len(tags) for tag in tags_counter]
entropy = 0
for prob in classes_probs:
if prob == 0:
return 0
entropy -= prob * math.log(prob, 2)
return entropy
else:
return 0
My questions are:我的问题是:
(1) The warning is because classes_probs
may be undefined at that point. (1) 警告是因为
classes_probs
在这一点上可能未定义。 If tags
is empty, the first loop doesn't execute.如果
tags
为空,第一个循环不执行。 You can "fix" this by assigning an empty list before the first loop.您可以通过在第一个循环之前分配一个空列表来“修复”这个问题。
(2) This is called a list comprehension
. (2) 这称为
list comprehension
。 Use that search term and find a tutorial at your preferred level of writing and examples.使用该搜索词并找到您喜欢的写作和示例级别的教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.