Find the best decision tree split with Gini impurity

A decision tree grows by finding, for one feature, the threshold that best separates the labels. Gini impurity of a group is 1 - sum(p_c ** 2) over its class shares.

Write best_split(x, y) for a 1D feature x and labels y. Try every threshold t in the sorted unique values of x except the largest, splitting into left (x <= t) and right (x > t). Score each split by the size-weighted Gini of the two sides. Return (best_t, best_score). On ties keep the smaller threshold.

If x has only one unique value, return (None, gini of y).

Signaturedef best_split(x, y)

Understand the idea

A decision tree splits data by asking a yes or no question like 'is x <= t?'. A good question leaves each side as pure as possible. Gini impurity measures mixing: 1 - sum of squared class shares, which is 0 for a pure group and 0.5 for a 50/50 binary mix. Each split is scored by the size-weighted average of the two sides, so a side with more rows counts more. Worked example: x = [1, 2, 3, 4], y = [0, 0, 1, 1]. Threshold 1: left [0] has Gini 0; right [0, 1, 1] has 1 - (1/9 + 4/9) = 0.444; weighted = 3/4 x 0.444 = 0.333. Threshold 2: both sides pure, score 0. Threshold 3: mirror of threshold 1, score 0.333. Best is (2, 0.0). Rule: try every sorted unique value except the largest, left is x <= t, score = (n_L/n) Gini_L + (n_R/n) Gini_R, keep the lowest, smaller t on ties. Random forests and gradient boosted trees search splits this way.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: clean splitbest_split([1, 2, 3, 10, 11, 12], [0, 0, 0, 1, 1, 1])
  • Sample 2: size weighting mattersbest_split([1, 2, 3, 4, 5], [0, 1, 1, 1, 1])
  • Test 3: noisybest_split([3, 1, 4, 1, 5, 9, 2, 6], [1, 0, 1, 0, 1, 1, 0, 0])
  • Test 4: constant featurebest_split([7, 7, 7], [0, 1, 1])