Where Should the Tree Cut?

Decision Trees & Ensemble LearningMedium+20 XP+20

Where Should the Tree Cut?

A refurbishing shop prices second-hand laptops with a regression tree. Its first question is about a laptop's age in years: is the age at most ttt? Each of the two leaves then predicts the average price of the training laptops that land in it.

To choose ttt, the tree can't use Gini or entropy: those measure how mixed a group of categories is. For numbers like price, it measures the mess with variance, which is how far the prices in a group sit from that group's own average:

Var(G)=1∣G∣∑p∈G(p−pˉG)2\text{Var}(G) = \frac{1}{|G|}\sum_{p \in G}\left(p - \bar{p}_G\right)^2Var(G)=∣G∣1​p∈G∑​(p−pˉ​G​)2

Here ∣G∣|G|∣G∣ is the number of laptops in group GGG and pˉG\bar{p}_Gpˉ​G​ is their average price. A split of nnn laptops into a left group LLL and a right group RRR is scored by the weighted variance

∣L∣n Var(L)+∣R∣n Var(R)\frac{|L|}{n}\,\text{Var}(L) + \frac{|R|}{n}\,\text{Var}(R)n∣L∣​Var(L)+n∣R∣​Var(R)

and the best split is the one with the lowest score. Its variance reduction is the variance of all nnn prices minus that score.

Candidate thresholds: sort the distinct ages and try the midpoint between each neighbouring pair. Laptops with age ≤t\le t≤t go left, and the rest go right.

Task: write best_regression_split(ages, prices) and return a tuple (threshold, left_mean, right_mean, reduction) for the best split, every value rounded to 4 decimal places.

  • ages and prices are the same length, and ages is not sorted.
  • Several laptops can share an age, and a threshold never separates them.
  • If two thresholds tie for the lowest score, return the smaller one.
  • If every laptop has the same age, no split is possible: return None.

This is the question a decision tree asks whenever it predicts a number instead of a category. Each leaf predicts its group's average, so the split that keeps each group's prices tight around its own average is the split whose two averages make the smallest errors.

Examples

ages = [1, 2, 3, 4, 5, 6]
prices = [900, 850, 820, 400, 380, 350]
returns (3.5, 856.6667, 376.6667, 57600.0)
ages = [5, 1, 4, 2, 3]
prices = [300, 700, 340, 660, 620]
returns (3.5, 660.0, 320.0, 27744.0)

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