Decision Tree Splits: Every Feature, Every Midpoint

Classic MLHard+20 XP+20

Decision Tree Splits: Every Feature, Every Midpoint

This is how a decision tree actually makes a decision: try every question it could ask, score each one, and keep the winner. There's no cleverness to it — it's a brute-force search, and the whole algorithm is in how you enumerate the candidates.

Task: write best_split(features, labels) returning [feature_index, threshold] — the single best question of the form "is feature f at most t?".

How to enumerate the candidate thresholds for one feature:

  1. Collect that feature's values, de-duplicated and sorted.
  2. For each neighbouring pair, the candidate threshold is their midpoint: (a + b) / 2.

That's it — midpoints between observed values, so a threshold always sits in a gap rather than on top of a data point.

To score a candidate, split the rows into left (feature value ≤ threshold) and right (greater), and compute the size-weighted Gini impurity of the two groups. Lower is better.

Gsplit=nLn(1−∑ipi2)L+nRn(1−∑ipi2)RG_{\text{split}} = \frac{n_L}{n}\left(1 - \sum_i p_i^2\right)_L + \frac{n_R}{n}\left(1 - \sum_i p_i^2\right)_RGsplit​=nnL​​(1−i∑​pi2​)L​+nnR​​(1−i∑​pi2​)R​

Tie-breaking, in this order: lowest impurity wins; on a tie, the lower feature index; on a further tie, the smaller threshold.

  • features is a list of rows, all the same length. labels lines up with it.
  • Every feature has at least two distinct values, so there's always at least one candidate.
  • Round the returned threshold to 4 decimal places.

A feature with k distinct values offers k - 1 questions, so the search is wider than it first looks — and this one function, called recursively on each side, is a whole decision tree.

Numeric Features Can Split Too

Drag the threshold and watch both the groups and the quality meter react.

1570
Age > 35? 4 left, 5 right
Good

Green means “buys the product”, red means “doesn't”. Different cut points produce very different groups.

Examples

features = [[2], [3], [10], [12]]
labels = [0, 0, 1, 1]
returns [0, 6.5]
features = [[1, 5], [2, 5], [3, 1], [4, 1]]
labels = [0, 0, 1, 1]
returns [0, 2.5]

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