#64 · Machine Learning · Easy
⊣ Solve on deep-ml.comCalculate the Gini Impurity for a set of classes. Gini impurity measures the probability of incorrectly classifying a randomly chosen element if it were labeled according to the class distribution.
def gini_impurity(labels):
n = len(labels)
if n == 0:
return 0.0
counts = {}
for label in labels:
counts[label] = counts.get(label, 0) + 1
impurity = 1.0
for count in counts.values():
prob = count / n
impurity -= prob ** 2
return round(impurity, 4)p_i for each class.