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:
答案 0 :(得分:0)
(1) The warning is because classes_probs
may be undefined at that point. If tags
is empty, the first loop doesn't execute. You can "fix" this by assigning an empty list before the first loop.
(2) This is called a list comprehension
. Use that search term and find a tutorial at your preferred level of writing and examples.