Gini Impurity: Weighing Both Sides of a Split

Classic MLMedium+15 XP+15

Gini Impurity: Weighing Both Sides of a Split

A decision tree picks a question to ask by trying lots of them and keeping whichever one leaves the two resulting groups purest — closest to containing a single class.

Gini impurity scores one group. If the group's class fractions are p1,p2,…p_1, p_2, \dotsp1​,p2​,…:

G=1−∑ipi2G = 1 - \sum_i p_i^2G=1−i∑​pi2​

All one class gives 0. An even two-way mix gives 0.5. That's the worst a two-class group can be.

A split produces two groups, so you need one number for the pair. Take the average of their impurities, weighted by how many examples each one holds:

Gsplit=nLnGL+nRnGRG_{\text{split}} = \frac{n_L}{n} G_L + \frac{n_R}{n} G_RGsplit​=nnL​​GL​+nnR​​GR​

Task: write split_gini(left_labels, right_labels) returning that weighted impurity, rounded to 4 decimal places.

  • Labels can be numbers or strings, and there may be more than two classes.
  • One side may be empty. An empty group has impurity 0 and weight 0, so it contributes nothing — just don't divide by its size.
  • n is the total across both sides, never zero.

The weighting is the part people get wrong. Without it, a split that peels off one pure example and leaves a mess behind would score beautifully, and a tree built that way would grow one useless branch at a time.

What Does Gini Actually Ask?

Draw two balls from each bag, with your eyes closed. How often do they come out different colors?

Bag A
RedRedRedRed
Bag B
RedBlueGreenYellow

That chance of a mismatch is exactly what the Gini Index measures. A pure bag can never mismatch. A mixed bag almost always does.

Examples

left_labels = [0, 0]
right_labels = [1, 1]
returns 0.0
left_labels = [0, 0, 1]
right_labels = [1, 1]
returns 0.2667

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run