PIXELBANKv8.2.1
Menu

Gini Impurity

Compute the Gini impurity of a set of labels.

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

Gini=1k=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:
  • First, we calculate the proportion of each class in the dataset: p0=35p_0 = \frac{3}{5} for class 0 and p1=25p_1 = \frac{2}{5} for class 1.
  • Then, we apply the Gini impurity formula: Gini=1(p02+p12)=1((35)2+(25)2)Gini = 1 - (p_0^2 + p_1^2) = 1 - (\left(\frac{3}{5}\right)^2 + \left(\frac{2}{5}\right)^2)
  • The calculation yields: Gini=1(925+425)=11325=1225=0.48Gini = 1 - \left(\frac{9}{25} + \frac{4}{25}\right) = 1 - \frac{13}{25} = \frac{12}{25} = 0.48
  • The final output is the Gini impurity rounded to 4 decimal places, which is 0.48000.4800, but since it's already in the correct format, the output is 0.48\boxed{0.48}

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)
Editor

Test Results

0/0
Run code to see test results.