Same Question, Different Rows

Decision Trees & Ensemble LearningMedium+20 XP+20

Same Question, Different Rows

A letting agent wants a monthly rent estimate from a single number: a flat's floor area in m². One small tree on its own is too jumpy, so they build a bagged ensemble of them.

Every tree asks the same question, is the area at most threshold?, but each one learns its two answers from its own bootstrap sample: a list of training rows drawn with replacement. The samples have been drawn in advance and are handed to you, so the results are reproducible.

Task: write bagged_predict(xs, ys, samples, threshold, queries) and return the ensemble's rent estimate for every area in queries, each rounded to 4 decimal places.

  • xs[i] and ys[i] are the floor area and the monthly rent of training row i.
  • samples holds one list of row indices per tree. An index can appear more than once, and every appearance counts as a separate training row for that tree: the sample [3, 3, 7] trains its tree on row 3 twice and row 7 once.
  • A tree's yes leaf (area <= threshold) predicts the average rent of the tree's training rows that answer yes. Its no leaf predicts the average rent of the rows that answer no.
  • If a leaf receives none of its tree's rows, it predicts the average rent of that tree's whole sample instead.
  • The ensemble's estimate is the plain average of its trees' estimates.

Some ensembles draw their samples without replacement instead, so no index repeats inside a list. This variant is called pasting, and your function must handle those lists with exactly the same rules.

Every tree here asks an identical question, yet the trees still disagree, because each one saw a different mix of rows. That disagreement is what the average smooths out.

Draw a Bootstrap Sample

Draw 10 records from the dataset, with replacement. Watch which records get picked more than once, and which get skipped.

Bootstrap Sample (in draw order)
4296696273
Original Dataset
12×23456×3789×210

This time, 4of the 10 original records weren't picked at all, while others were drawn more than once. Sampling with replacement means every draw is independent, so this changes each time.

Examples

xs = [40, 55, 60, 72, 85, 95]
ys = [900, 1150, 1200, 1500, 1750, 2100]
samples = [[0, 0, 2, 3, 5, 5], [1, 2, 2, 4, 4, 3], [0, 1, 3, 3, 3, 4]]
threshold = 65
queries = [50, 90]
returns [1069.4444, 1709.7222]
xs = [30, 45, 50, 70, 80]
ys = [700, 950, 1000, 1400, 1600]
samples = [[0, 2, 3], [1, 3, 4], [0, 1, 4]]
threshold = 60
queries = [35, 60, 75]
returns [875.0, 875.0, 1500.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