v9.1.1
Menu

Gini Impurity

easyFREEDecision TreesMachine Learning 1

Compute the Gini impurity of a set of labels.

Gini impurity measures how often a randomly chosen element would be incorrectly classified:

Gini=1−∑k=1Kpk2Gini = 1 - \sum_{k=1}^{K} p_k^2

where pkp_k is the proportion of class kk in the dataset.

A pure node (all same class) has Gini = 0. Maximum impurity for binary classification is 0.5.

Return the Gini impurity rounded to 4 decimal places.

Example

Input
labels = [1, 1, 0, 0, 0]
Output
0.48
Reasoning
  • labels is a list of 5 class labels: two belong to class 1 and three to class 0. Only how often each class appears matters, not the order or the label values themselves.
  • The class proportions are p0=35=0.6p_0 = \frac{3}{5} = 0.6 and p1=25=0.4p_1 = \frac{2}{5} = 0.4; they always add up to 1.
  • Squaring each gives p02=0.36p_0^2 = 0.36 and p12=0.16p_1^2 = 0.16. Their sum, 0.520.52, is the probability that two elements drawn at random (with replacement) share a class.
  • So Gini=1−0.52=0.48Gini = 1 - 0.52 = 0.48, the chance that the two draws disagree, which is how often a random element gets mislabelled by a random guess from the same distribution.
  • The output 0.48 is a single float, already exact at 4 decimal places.
  • Notice that it sits just below the binary maximum of 0.50.5, reached only at a perfect 50/5050/50 split of two classes. A pure list (every label the same) gives 0.0, and an empty list also returns 0.0 by convention.

Constraints

  • labels is a list of class labels (integers or strings)
  • Return a float rounded to 4 decimal places
  • Handle empty lists (return 0.0)

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.