σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
XGBoost skill›Module 1 · Boosting from the ground up›Topic 1.2·~55 minIntermediate

Gradient boosting: the idea and a 30-line loop

Skill positionModule 1 of 4 · Topic 2 of 2
1.2 Gradient boosting: the idea and a 30-line loop
—Lab score— / 100Total XP—Streak—
Lecture0% read

10 min readCode examples: 8

  1. 01The idea: fit what is left over
  2. 02Small steps: the learning rate
  3. 03The stump: one question
  4. 04The loop: residuals, stump, shrink, repeat
  5. 05Rounds and overfitting
  6. 06What you will build

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.

01

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.

F₀ = mean(y) Fₘ = Fₘ₋₁ + η · hₘ(1)F is the prediction after m rounds, h the small tree fitted in round m, η (eta) the learning rate, a number between 0 and 1
rₘ = y − Fₘ₋₁(2)r is the residual: what the model after m − 1 rounds still gets wrong, row by row. Round m fits the tree hₘ to r
DefinitionResidual

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.

main.pyPython
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
  1. 1Fit the leftovers, not y.
  2. 2Add only half of the stump: that is the learning rate.
  3. 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.

02

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.

error after m rounds = (1 − η)ᵐ × error at the start(3)valid when every round's stump fits the leftovers perfectly; m is the number of rounds, η the learning rate

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.

main.pyPython
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.

03

The stump: one question

DefinitionStump

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

gain = S_L² / n_L + S_R² / n_R(4)S_L, S_R: the sums of the residuals on the left and on the right of the cut; n_L, n_R: the numbers of rows. Σr² is the same for every cut, so the largest gain is the smallest error

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.

main.pyPython
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)
  1. 1The sum on the left of each cut: one cumulative sum.
  2. 2The number of rows on the left.
  3. 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.

main.pyPython
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.

04

The loop: residuals, stump, shrink, repeat

The loop has four moves, and the lab's boost_fit is nothing more.

  1. 1
    Residualsresidual = y - pred: what is still wrong.
  2. 2
    One stump per featureFor each column, best_stump(column, residual). Keep the column whose stump leaves the smallest squared error.
  3. 3
    Shrink and addpred = pred + learning_rate * stump_predict(stump, column).
  4. 4
    RememberStore the column, the threshold and the two answers, so that new rows can be predicted later.
main.pyPython
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])
  1. 1The residuals are recomputed in every round.
  2. 2The error of this column's stump on the residuals.
  3. 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.

main.pyPython
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
05

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.

main.pyPython
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
  1. 1The error on the rows the model learned from.
  2. 2The error on the rows from 2015.
  3. 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.

main.pyPython
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
  1. 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.

Why the gap is not zero

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 the real data says56 US stocks, month-ends from January 2001 to July 2026
Training error0.0808 to 0.0793rmse on rows before 2015 after 0 and after 50 rounds
Test error0.07856 to 0.0787rmse on rows from 2015, after 0 and after 50 rounds
First questionmom <= -0.79914 of 9,292 training rows, next month +33% on average
Gap to XGBoost2.4e-08largest difference in a test prediction

Key takeaways

  • Fit the leftovers. Each round fits a small tree to the residuals and adds a fraction of it to the prediction.
  • A small step is gentle. With learning rate η the remaining error shrinks like (1 − η) per round at best; small steps need more rounds and overfit less.
  • One pass finds the best cut. Sort the feature, take a cumulative sum of the residuals, and the gain of every cut follows from the sums and counts on each side.
  • Training error always falls. Only the error on later months says whether the stumps learned something that lasts.
Quick check
Your turn. A row has the target 9, the base is 5 (the mean), and the stump of round one answers 3.0 for the leaf of this row. With learning rate 0.5, what is the row's prediction after round one?
Pick an answer.
06

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
Explorer · lab-xg-02
▾ lab-xg-02
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-02$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-02 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes