I am currently working on a decision tree and need to calculate the entropy in a label vector y (an numpy array). I tried the two following methods to use the entropy formula:
entropy = sum(-len(y[y == label]) / len(y) * np.log2(len(y[y == label]) / len(y)) for label in labels)
and
entropy = 0
for label in labels:
cond = y == label
fraction = len(y[cond]) / len(y)
entropy += -fraction * np.log2(fraction)
return entropy
When timing the two methods the seconds approach is the fastest. Why is that? I guess it is because I calculate the fraction two times in the same loop in the first approach. Is there any way to make the first approach faster?
"labels" in the above snippets are the following:
labels = np.unique(y)