σμ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 2 · Trees and regularisation›Topic 2.2·~50 minIntermediate

Regularisation and early stopping

Skill positionModule 2 of 4 · Topic 2 of 2
2.2 Regularisation and early stopping
—Lab score— / 100Total XP—Streak—
Lecture0% read

8 min readCode examples: 6

  1. 01Penalties on leaves and splits
  2. 02Reading a fitted tree
  3. 03What each setting does
  4. 04Early stopping: let validation say when
  5. 05Choose a setting, stop early, judge once
  6. 06What you will build

A leaf made of 2 rows can answer 0.033 when every one of them says 0.05, while a leaf of 200 rows answers 0.0498. A penalty of one number makes the first leaf modest and barely touches the second, and that is most of regularisation.

01

Penalties on leaves and splits

Where we are. The last topic chose the depth, the learning rate and the number of trees by looking at the validation years. But inside a tree, every leaf still answers with the plain average of its residuals, however few rows it holds. A leaf of two rows that happen to be large will say "large" with full confidence. Regularisation adds a price to that confidence.

Take the residuals of the rows in a node: the truth minus what the model predicted so far. Let n be their count and S their sum. For a squared error the best answer for a leaf is the mean, S / n. XGBoost adds a number to the count, called lambda (reg_lambda), and the answer becomes the following.

leaf answer = S / (n + λ)(1)S: the sum of the residuals in the leaf; n: their count; λ (lambda, reg_lambda): the penalty, 1 by default. The learning rate multiplies the answer afterwards
DefinitionRegularisation

Anything that makes a model less eager to follow the training rows: shrinking the answers of small leaves (lambda), refusing splits that gain too little (gamma), demanding a minimum of rows in a leaf (min_child_weight), or training each tree on a random part of the rows and columns (subsample, colsample).

Worked example 1. *Problem:* three leaves hold 2, 20 and 200 rows, and every row has the residual 0.05. What does each leaf answer with lambda = 1, and with lambda = 10? *Plan:* the plain mean is 0.05 in all three; the answer is S / (n + λ) with S = 0.05 n. *Steps:* compute the six answers.

main.pyPython
for n in (2, 20, 200):    rows = np.full(n, 0.05)    print(n, round(leaf_weight(rows, 0.0), 4), round(leaf_weight(rows, 1.0), 4), round(leaf_weight(rows, 10.0), 4))1
2 0.05 0.0333 0.0083
20 0.05 0.0476 0.0333
200 0.05 0.0498 0.0476
  1. 1The answer with lambda 0, 1 and 10.

*Check:* with lambda = 1 the leaf of 2 rows answers 0.0333 (two thirds of 0.05) and the leaf of 200 rows answers 0.0498; with lambda = 10 the small leaf answers 0.0083 and the big one 0.0476. *What to notice:* the penalty is a fixed number added to a count, so it matters a lot to small leaves and hardly at all to big ones. It acts as a vote of doubt that fades with evidence. The simple method, using the mean, treats two rows and two hundred rows alike.

A split is judged the same way. Before the split the node has the sum S and the count n; after it, two nodes with their own. The gain measures how much better the two parts describe the residuals than the parent did.

gain = S_L² / (n_L + λ) + S_R² / (n_R + λ) − S² / (n + λ)(2)L and R: the rows that go left and right; S and n of the whole node are the sums of the two sides. XGBoost records this number for every split it makes

Worked example 2. *Problem:* a node holds four rows with the residuals 1, 1, -1, -1. A split puts the two positive ones on the left and the two negative ones on the right. What is the gain for lambda = 0 and for lambda = 2, and which values of gamma keep the split? *Plan:* the sums are 2 and -2, the counts 2 and 2, and the parent has sum 0 and count 4. *Steps:* compute.

main.pyPython
left, right = [1.0, 1.0], [-1.0, -1.0]for lam in (0.0, 2.0):    print(lam, split_gain(left, right, lam))print(keeps_split(left, right, 0.0, 3.9), keeps_split(left, right, 0.0, 4.0), keeps_split(left, right, 2.0, 1.9))
0.0 4.0
2.0 2.0
True False True

*Check:* with lambda = 0 the gain is 2²/2 + 2²/2 − 0 = 4; with lambda = 2 it is 4/4 + 4/4 − 0 = 2. A split with gamma 3.9 is kept, with gamma 4.0 it is not (equal is not enough), and with lambda = 2 a gamma of 1.9 keeps it. *What to notice:* the penalty lambda makes every split look less valuable, and gamma sets the minimum gain for a split to be kept. Together they decide whether a branch is grown at all: a split that does not pay for itself is never made.

02

Reading a fitted tree

XGBoost records the numbers behind every node of a fitted tree. That makes the formulas checkable: they must reproduce what the library stored. Worked example 3. *Problem:* fit a single stump on the fit years with a learning rate of 1 and read its top question, its gain and its two leaves. Then recompute the gain with your formula from the residuals on each side. *Plan:* stump_summary reads the tree; the rows on each side are the ones whose value is below the threshold or not.

main.pyPython
panel = build_panel(load_close())fit = split_by_date(panel, "1900-01-01", "2011-01-01")valid = split_by_date(panel, "2011-01-01", "2015-01-01")test = split_by_date(panel, "2015-01-01")residuals = (fit[TARGET] - fit[TARGET].mean()).to_numpy()for lam in (0.0, 1.0, 50.0):    top = stump_summary(fit_model(fit, 1, 1, 1.0, reg_lambda=lam))1    yes = fit[top["feature"]].to_numpy() < top["threshold"]2    print(lam, top["feature"], round(top["threshold"], 3), round(top["gain"], 3), round(split_gain(residuals[yes], residuals[~yes], lam), 3), top["left_cover"], top["right_cover"], round(top["left_leaf"], 4), round(top["right_leaf"], 4))
0.0 vol 0.119 2.832 2.832 5700.0 904.0 -0.0082 0.052
1.0 vol 0.119 2.83 2.83 5700.0 904.0 -0.0082 0.0519
50.0 vol 0.119 2.701 2.701 5700.0 904.0 -0.0082 0.0493
  1. 1The top question of the first tree, read from the model.
  2. 2The same gain computed from the formula.

*Check:* the top question is "is vol < 0.119?" for all three values of lambda. The gain XGBoost recorded and the gain from the formula agree: 2.832, 2.830 and 2.701. The two leaves hold 5,700 and 904 rows and answer -0.0082 and 0.052 (for lambda 0), moving only in the third decimal. *What to notice:* at the top of a tree, where the leaves are big, even lambda = 50 changes little. The penalty bites lower in the tree, where the nodes are small.

03

What each setting does

The settings that XGBoost exposes are different ways to say "be less sure". reg_lambda shrinks the answers, as above. gamma drops splits whose gain is too small. min_child_weight refuses a split that would leave fewer than that many rows in a child (for a squared error each row has weight 1). subsample trains each tree on a random share of the rows, and colsample_bytree on a random share of the columns, so that no tree can lean on one lucky row or one column.

Worked example 4. *Problem:* which of these settings generalises best on the validation years, for 60 deep trees (depth 6, rate 0.1)? *Plan:* settings_table fits one model per setting and reports its total leaves and its errors on the fit and the validation years. *Steps:* below.

main.pyPython
grid = [{"reg_lambda": 0.0}, {}, {"reg_lambda": 50.0}, {"min_child_weight": 50}, {"gamma": 0.05}, {"subsample": 0.7, "colsample_bytree": 0.7}]for row in settings_table(fit, valid, grid):    print(str(row["settings"]).ljust(46), row["leaves"], round(row["rmse_fit"], 5), round(row["rmse_valid"], 5))
{'reg_lambda': 0.0}                            3170 0.04468 0.03739
{}                                             3065 0.04589 0.03722
{'reg_lambda': 50.0}                           2412 0.05253 0.03681
{'min_child_weight': 50}                       1056 0.05352 0.03693
{'gamma': 0.05}                                245 0.05458 0.03694
{'subsample': 0.7, 'colsample_bytree': 0.7}    2831 0.04749 0.03738

*Check:* with no penalty at all (reg_lambda 0) the 60 trees have 3,170 leaves, fit the fit years best (0.04468) and score 0.03739 on the validation years. Every penalty trims the leaves and raises the fit error, and most of them lower the validation error: lambda 50 gives 0.03681, a minimum of 50 rows per leaf 0.03693, a gamma of 0.05 0.03694 with only 245 leaves. Sampling rows and columns changes little here (0.03738). *What to notice:* the fit error goes up and the validation error goes down: the model gives up some detail of the fit years to keep what repeats. The gamma of 0.05 cuts the leaves from 3,065 (the default) to 245 for a similar validation error: a much smaller model that is as good.

  • SettingWhat it does
  • reg_lambdaShrinks every leaf answer; more for small leaves.default 1
  • gammaThe minimum gain for a split to be kept.default 0
  • min_child_weightThe minimum weight (rows, for a squared error) in a child.default 1
  • subsample / colsample_bytreeTrain each tree on a random part of the rows / columns.random_state fixes it
  • early_stopping_roundsStop when the validation error has not improved for this many trees.needs an eval_set
04

Early stopping: let validation say when

The last topic found the number of trees by reading a curve by hand. XGBoost can do it while it trains: give it a validation set and a patience. After every tree it scores the validation rows; when the score has not improved for patience trees in a row, it stops. The model keeps the position of the best tree.

Worked example 5. *Problem:* train with room for 500 trees and a patience of 20, and see where it stops. *Plan:* use fit_early_stopping with the defaults (depth 4, rate 0.05). *Steps:* below.

main.pyPython
stopped = fit_early_stopping(fit, valid)print(stopped["best_trees"], stopped["trees_run"])print(round(float(stopped["model"].best_score), 5))
70 90
0.03677

*Check:* the best number of trees is 70 and 90 were trained: 20 more than the best, the patience. The best validation score is 0.03677. *What to notice:* model.best_iteration counts from 0 (it is 69), so the number of trees is one more; the trees after the best are trained only to prove that nothing better was coming. When you score new rows, use the first best_trees trees.

The validation years are used up

Early stopping chooses the best moment on the validation years, so the validation score is a little optimistic: it is the best of many looks. That is why the test years stay untouched until the end.

05

Choose a setting, stop early, judge once

Worked example 6. *Problem:* put it together. *Plan:* choose the regularisation setting by the validation error of the table, train with it and stop early, then score on the test years once. *Steps:* study.

main.pyPython
result = study(panel)print(result["best_settings"], result["best_trees"], result["trees_run"])print(round(result["rmse_valid"], 5), round(result["rmse_test"], 5), round(result["rmse_test_baseline"], 5))
{'reg_lambda': 50.0} 142 162
0.0367 0.05192 0.05453

*Check:* the best setting is a lambda of 50, early stopping keeps 142 trees (162 were trained), the validation score is 0.0367 and the test score 0.05192, against 0.05453 for the plain average. *What to notice:* the regularised, early-stopped model is about 5 % better than the average on the test years, the same as the model of the last topic (0.05199). The settings changed the way the model gets there, with a smoother fit and fewer leaves per tree, and not the accuracy: the features hold a limited amount of signal and several routes reach it.

What the real data says56 US stocks; target: the size of the next month's move
Leaves, no penalty3,17060 trees of depth 6; validation error 0.03739
Leaves, lambda 502,412validation error 0.03681, the best of the six settings
Leaves, gamma 0.05245validation error 0.03694: a model 13 times smaller
Early stopping142 of 162trees kept and trees trained, patience 20
Test error0.05192the plain average scores 0.05453

Key takeaways

  • Penalties are doubt. Lambda shrinks small leaves more than big ones; gamma and min_child_weight refuse splits that do not pay for themselves.
  • The formulas are checkable. The leaf answer S / (n + λ) and the gain of a split are the numbers XGBoost stores in every tree.
  • Less detail, same signal. Penalties lower the fit error's advantage and give smaller models that predict as well on unseen years.
  • Let validation say when. Early stopping ends training when the validation error stops improving; the best number of trees is best_iteration + 1.
Quick check
Your turn. A leaf holds 4 rows with the residuals 0.1, 0.1, 0.1 and 0.1. What does it answer with lambda = 1? (before the learning rate)
Pick an answer.
06

What you will build

The lab follows the lecture. Task 1 is the answer of a leaf with the penalty and task 2 the gain of a split; task 3 decides whether a split is kept. Task 4 reads the top of a fitted tree, task 5 stops a model early and task 6 compares regularisation settings. Task 7 chooses a setting on the validation years, stops early with it and judges the result once on the test years.

Next topic: so far every feature column was complete. The next topic, Missing values and categorical features, gives XGBoost columns with holes and a column of sectors, and shows what the trees do with them.

Lab · what's graded

7 tasks · 100 pts
  • A leaf with a penalty10 pts
  • The gain of a split15 pts
  • Is the split kept10 pts
  • Read a fitted tree15 pts
  • Early stopping20 pts
  • Compare the settings15 pts
  • Choose, stop early, judge once15 pts
Explorer · lab-xg-04
▾ lab-xg-04
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-04$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-xg-04 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