A loop of about 30 lines and XGBoost's 50 trees make the same predictions, down to 2e-08. And on the months after 2015 that model is no better than a plain average. This topic builds the loop, so that you can see why both facts are true.
The idea: fit what is left over
Where we are. In the first topic you built an XGBoost model, predicted next month's return with it and found that it did not beat the plain average on later months. The question that left open is what fit actually does. Here you write it yourself, for the simplest case: a squared error and the smallest possible trees.
Boosting starts from a first guess, the average of the target, and then improves it in rounds. In each round it looks at what the current prediction still gets wrong, fits a small tree to those mistakes, and adds a fraction of that tree to the prediction.
The truth minus the current prediction, one number per row. A positive residual means the model predicted too low, a negative one too high.
Why is it called *gradient* boosting? For a squared error, ½(y − F)², the slope of the error with respect to the prediction F is −(y − F). So the residual is the *downhill direction* of the error, and fitting a tree to it is a step downhill. For other errors (the objectives topic of this skill) the residual is replaced by their slope, and the loop stays the same.
Worked example 1. *Problem:* four rows with one feature x = 1, 2, 3, 4 and the target y = 3, 5, 9, 13. Boost two rounds with learning rate η = 0.5. *Plan:* start from the mean, compute the residuals, fit the best stump to them, add half of it, and do it once more. *Steps:* below; the function best_stump is the one you write in the lab, and for now you only use it.
x = np.array([1.0, 2.0, 3.0, 4.0])y = np.array([3.0, 5.0, 9.0, 13.0])pred = np.full(4, y.mean())for round_number in (1, 2): residual = y - pred1 stump = best_stump(x, residual)2 pred = pred + 0.5 * stump_predict(stump, x)3 print(round_number, residual.round(2).tolist(), tuple(round(v, 2) for v in stump), pred.round(3).tolist(), round(rmse(y, pred), 3))
1 [-4.5, -2.5, 1.5, 5.5] (2.5, -3.5, 3.5) [5.75, 5.75, 9.25, 9.25] 2.358 2 [-2.75, -0.75, -0.25, 3.75] (3.5, -1.25, 3.75) [5.125, 5.125, 8.625, 11.125] 1.431
- 1Fit the leftovers, not y.
- 2Add only half of the stump: that is the learning rate.
- 3Each line shows the round, its residuals, its stump, the new prediction and the error.
*Check:* the mean is 7.5, so the first residuals are -4.5, -2.5, 1.5, 5.5. The best question is "is x <= 2.5?" with the answers -3.5 (the mean of the first two residuals) and 3.5. Half of that moves the prediction to 5.75 and 9.25. The error falls from 3.84 (the mean alone) to 2.36, then to 1.43. *What to notice:* each round fixes part of the error, and the second stump asks a different question (x <= 3.5) because the leftovers changed. A simple method, fitting one big tree to y, would need many questions at once; boosting asks one question at a time.
Small steps: the learning rate
Why add only a fraction of each stump? If you add all of it, one round can fit the training rows so closely that the model memorises noise. With a small step, a single unlucky stump changes the prediction only a little, and later stumps can correct it. The price is that more rounds are needed. When a stump fits the leftovers perfectly, the arithmetic is exact.
Worked example 2. *Problem:* six rows, x = 1..6 and y = 0, 0, 0, 10, 10, 10. How many rounds does it take to get close to a perfect fit with η = 1, 0.5 and 0.1? *Plan:* the mean is 5, so the starting error is 5; one stump fits the leftovers (-5 on the left, +5 on the right) perfectly, so equation 3 applies. Compute the curve with the loop and compare. *Steps:* fit 10 rounds for each learning rate and read the error after 1, 3 and 10 rounds.
X = np.arange(1.0, 7.0).reshape(-1, 1)y = np.array([0.0, 0.0, 0.0, 10.0, 10.0, 10.0])for eta in (1.0, 0.5, 0.1): curve = boost_curve(boost_fit(X, y, 10, eta), X, y) print(eta, [round(curve[m], 3) for m in (0, 1, 3, 10)], [round(5 * (1 - eta) ** m, 3) for m in (0, 1, 3, 10)])
1.0 [5.0, 0.0, 0.0, 0.0] [5.0, 0.0, 0.0, 0.0] 0.5 [5.0, 2.5, 0.625, 0.005] [5.0, 2.5, 0.625, 0.005] 0.1 [5.0, 4.5, 3.645, 1.743] [5.0, 4.5, 3.645, 1.743]
*Check:* for η = 0.5 the error is 5, 2.5, 0.625, 0.005, which is 5 × 0.5^m for m = 0, 1, 3, 10; the second list is the formula and it matches the loop. For η = 1 the error is 0 after one round, and for η = 0.1 it is still 1.743 after ten rounds. *What to notice:* a small learning rate is slow but gentle. The usual choice is a small η (0.01 to 0.1) and as many rounds as the validation error allows.
The stump: one question
The smallest tree: one yes/no question about one feature, x <= threshold?, and two answers, one for each side. The best answers for a squared error are the means of the residuals on each side.
To find the best question, try every threshold halfway between two neighbouring different values of the feature. Doing this naively recomputes two means for every threshold. There is a shortcut. Let S_L be the sum of the residuals on the left, n_L their count, and S_R, n_R the same for the right. The squared error left after the split is Σr² − gain, where
Sort the rows by the feature once. Then S_L for every cut is a cumulative sum, and one pass gives the gain of all cuts. Worked example 3. *Problem:* find the best stump for x = 1..5 and the residuals 2, 1, 0, -1, -3. *Plan:* list the four cuts, the sum and count on the left, the gain of each, and take the largest. *Steps:* below.
x = np.array([1.0, 2.0, 3.0, 4.0, 5.0])r = np.array([2.0, 1.0, 0.0, -1.0, -3.0])left_sum = np.cumsum(r)[:-1]1left_n = np.arange(1, len(r))2gain = left_sum**2 / left_n + (r.sum() - left_sum) ** 2 / (len(r) - left_n)3print(left_sum.tolist(), gain.round(2).tolist(), (r**2).sum())print(best_stump(x, r))
[2.0, 3.0, 3.0, 2.0] [6.25, 9.83, 11.0, 10.0] 15.0 (3.5, 1.0, -2.0)
- 1The sum on the left of each cut: one cumulative sum.
- 2The number of rows on the left.
- 3The gain of every cut at once.
*Check:* the four cuts have the gains 6.25, 9.83, 11.0, 10.0, so the third wins, halfway between x = 3 and x = 4, at 3.5; the answers are the means (2 + 1 + 0) / 3 = 1.0 and (-1 - 3) / 2 = -2.0. The squared error left is 15 - 11 = 4. *What to notice:* nothing was recomputed for each cut. This is why the search is fast, and XGBoost does the same on all features at once.
Worked example 4. *Problem:* what if two rows have the same x? *Plan:* they cannot be separated by a question about x, so a cut between equal values is not allowed. *Steps:* try x = 1, 1, 2, 2 and r = 1, 3, 10, 12.
print(best_stump([1, 1, 2, 2], [1, 3, 10, 12]))print(best_stump([5, 5, 5], [1, 2, 6]))
(1.5, 2.0, 11.0) (5.0, 3.0, 3.0)
*Check:* only one cut is possible, at 1.5, with the means 2.0 and 11.0. With a single distinct value there is no question to ask, so the stump gives the mean on both sides. *What to notice:* ignoring this rule is a classic bug: a cut between two equal values puts rows with the same x on different sides.
The loop: residuals, stump, shrink, repeat
The loop has four moves, and the lab's boost_fit is nothing more.
- 1Residuals
residual = y - pred: what is still wrong. - 2One stump per featureFor each column,
best_stump(column, residual). Keep the column whose stump leaves the smallest squared error. - 3Shrink and add
pred = pred + learning_rate * stump_predict(stump, column). - 4RememberStore the column, the threshold and the two answers, so that new rows can be predicted later.
base = float(y.mean())pred = np.full(len(y), base)stumps = []for _ in range(n_rounds): residual = y - pred1 best = None for column in range(X.shape[1]): stump = best_stump(X[:, column], residual) error = float(np.sum((residual - stump_predict(stump, X[:, column])) ** 2))2 if best is None or error < best[0]: best = (error, column, stump) _, column, stump = best stumps.append({"feature": column, "threshold": stump[0], "left": stump[1], "right": stump[2]}) pred = pred + learning_rate * stump_predict(stump, X[:, column])
- 1The residuals are recomputed in every round.
- 2The error of this column's stump on the residuals.
- 3Only a fraction of the stump is added.
A model is the base, the learning rate and the list of stumps. To predict a new row, start from the base and add learning_rate times the answer of every stump, each looking at its own column. Worked example 5. *Problem:* does boost_fit reproduce the hand computation of example 1? *Plan:* fit two rounds on the same four rows and print the model and its predictions.
X = np.array([[1.0], [2.0], [3.0], [4.0]])y = np.array([3.0, 5.0, 9.0, 13.0])model = boost_fit(X, y, 2, 0.5)print(model["base"], model["stumps"])print(boost_predict(model, X).round(3).tolist())
7.5 [{'feature': 0, 'threshold': 2.5, 'left': -3.5, 'right': 3.5}, {'feature': 0, 'threshold': 3.5, 'left': -1.25, 'right': 3.75}]
[5.125, 5.125, 8.625, 11.125]*Check:* the base is 7.5, the two stumps are the ones found by hand (2.5 with -3.5 and 3.5, then 3.5 with -1.25 and 3.75), and the predictions 5.125, 5.125, 8.625, 11.125 are what the loop printed at the end of example 1 would give for the second round. *What to notice:* the model is a few numbers. All the learning of a boosted model is in the list of questions and answers.
- FunctionQuestion it answers
- best_stump(x, r)Which question about one feature fits the leftovers best?midpoints, cumulative sums
- stump_predict(stump, x)What does a stump say for each value?equal goes left
- boost_fit(X, y, n_rounds, learning_rate)Which stumps, in which order?residuals each round
- boost_predict(model, X)What does the model say for new rows?base + η × the sum
- boost_curve(model, X, y)How does the error change with the rounds?n_rounds + 1 values
Rounds and overfitting
Worked example 6. *Problem:* boost 50 stumps with η = 0.1 on the real panel (stocks before 2015) and see the error on the training rows and on the rows from 2015. *Plan:* fit the loop, compute the curve on both parts, and look at the first stump. *Steps:* below.
model = boost_fit(X_train, y_train, 50, 0.1)train_curve = boost_curve(model, X_train, y_train)test_curve = boost_curve(model, X_test, y_test)1for m in (0, 1, 5, 10, 25, 50):2 print(m, round(train_curve[m], 5), round(test_curve[m], 5))first = model["stumps"][0]print(FEATURES[first["feature"]], round(first["threshold"], 3), round(first["left"], 3), round(first["right"], 4))3
0 0.08084 0.07856 1 0.08066 0.07857 5 0.08018 0.07858 10 0.07992 0.07858 25 0.07957 0.07865 50 0.07928 0.0787 mom -0.799 0.323 -0.0005
- 1The error on the rows the model learned from.
- 2The error on the rows from 2015.
- 3The first question the loop chose.
*Check:* on the training rows the error falls at every round, from 0.08084 to 0.07928. On the test rows it starts at 0.07856 (the plain average) and ends at 0.0787: it never goes below the start. The first stump asks "is mom <= -0.799?" and answers +0.323 on the left. *What to notice:* that left side holds only 14 of the 9,292 training rows, stock-months after a fall of 80 % or more (in 2001 to 2003 and 2009), whose next month averaged +33 %. The greedy search found the few extreme rows because they reduce the squared error the most. None of the test rows has such a fall, so that part of the model never fires after 2015. The model learned a fact about a handful of crash months.
Now the comparison that makes the loop trustworthy. With a squared error, XGBoost with trees of depth 1 does what you wrote, provided that its two extra safeguards are switched off: reg_lambda=0 (by default XGBoost shrinks every answer a little) and tree_method="exact" (the search over all midpoints, like yours; the default hist groups values into bins). The starting guess is set to the training mean.
reference = xgb.XGBRegressor(n_estimators=50, max_depth=1, learning_rate=0.1, reg_lambda=0, tree_method="exact", base_score=float(y_train.mean()), n_jobs=1, random_state=0)1reference.fit(X_train, y_train)theirs = reference.predict(X_test)mine = boost_predict(model, X_test)print(round(rmse(y_test, mine), 5), round(rmse(y_test, theirs), 5), f"{np.max(np.abs(mine - theirs)):.1e}")
0.0787 0.0787 2.4e-08
- 1reg_lambda=0, exact search and a fixed start make XGBoost a plain stump booster.
*Check:* the two test errors are the same to five digits, and the largest difference between a prediction of yours and one of XGBoost's is 2.4e-08, about the precision of the 32-bit numbers XGBoost works with. *What to notice:* nothing is hidden inside fit. Every other setting of the next topics (deeper trees, regularisation, other objectives) is a change to one of these lines.
XGBoost stores the features and the answers as 32-bit floats; yours are 64-bit. Rounding at the eighth digit is the whole difference, so a gap near 1e-7 or smaller means the two loops are the same loop.
What you will build
The lab follows the lecture. Task 1 finds the best stump for one feature, task 2 applies a stump. Task 3 is the boosting loop and task 4 predicts with its result. Task 5 computes the error after every round. Task 6 boosts 50 stumps on the real panel and checks your loop against XGBoost.
Next topic: every tree in this topic was a stump, one question deep. The next topic, Tree depth and learning rate, lets the trees ask more questions, and shows how the depth and the learning rate decide between a model that is too simple and one that memorises.
Lab · what's graded
6 tasks · 100 pts- The best stump20 pts
- Apply a stump10 pts
- The boosting loop25 pts
- Predict10 pts
- The error after every round15 pts
- Your loop against XGBoost20 pts