Each Tree Mops Up After the Last

Decision Trees & Ensemble LearningHard+30 XP+30

Each Tree Mops Up After the Last

A courier company predicts how many minutes a delivery will take from its distance in km. They use gradient boosting: a chain of tiny trees, where every new tree is trained on whatever error the chain still makes.

The recipe runs like this.

  1. Start flat. Every prediction begins at the average delivery time of the training records.
  2. One round per entry in thresholds, in order:
    • Work out each training record's residual: its true time minus its current prediction.
    • Build a one-question tree that asks is the distance at most t?, where t is this round's threshold. Each of its two leaves outputs the average residual of the training records that land in it. A leaf that receives no training records outputs 0.
    • Move every training record's prediction by learning_rate × the tree's output for that record.
  3. Predict. For a new distance, start from the same average and add learning_rate × each tree's output for that distance.

Task: write boost_predict(xs, ys, thresholds, learning_rate, queries) and return the final model's predictions for every distance in queries, each rounded to 4 decimal places.

  • xs[i] and ys[i] are training record i's distance and true delivery time.
  • A distance exactly equal to a threshold answers yes.
  • The learning_rate is between 0 and 1. It shrinks every correction, so each tree only fixes part of what is left.

Examples

xs = [1, 2, 4, 5, 7, 9]
ys = [12, 15, 21, 24, 33, 40]
thresholds = [4, 2, 7]
learning_rate = 0.4
queries = [1.5, 5, 10]
returns [17.0531, 28.0264, 33.348]
xs = [2, 3, 6, 8]
ys = [10, 14, 30, 38]
thresholds = [4, 4]
learning_rate = 1.0
queries = [3, 7]
returns [12.0, 34.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