σμ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.1·~50 minIntermediate

Tree depth and learning rate

Skill positionModule 2 of 4 · Topic 1 of 2
2.1 Tree depth and learning rate
—Lab score— / 100Total XP—Streak—
Lecture0% read

8 min readCode examples: 5

  1. 01What a deeper tree is
  2. 02Depth: how many questions in a row
  3. 03More trees, smaller steps
  4. 04Choose on validation, judge on test
  5. 05What you will build

Trees of depth 8 bring the training error down to 0.0407, and the error on the next years up to 0.0374. Trees of depth 3 do best, at 0.0368. The depth and the learning rate decide whether a boosted model learns or memorises.

01

What a deeper tree is

Where we are. The last topic wrote the boosting loop with stumps, trees that ask a single question, and found that XGBoost does exactly that. The open question is what changes when a tree may ask more than one question in a row. There is also a change of target: the first topics showed that mom, rev and vol say almost nothing about the *direction* of a return, but a volatile stock tends to stay volatile, so the *size* of next month's move, move = |fwd|, can be predicted. Settings only matter when there is something to find, so from here on the target is move.

DefinitionDepth

The largest number of questions asked in a row, from the top of a tree to one of its ends. A leaf is an end of the tree, where the answer sits. A tree of depth d has at most 2^d leaves: a stump (depth 1) has 2, depth 3 has up to 8.

Worked example 1. *Problem:* read one tree, and use it for a stock with vol = 0.10 and mom = -0.2. *Plan:* fit a single tree of depth 2 with a learning rate of 1 (so that its leaves are the whole correction), print it as text, and follow the questions down. *Steps:* fit, print, follow.

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")one = fit_model(fit, 1, 2, 1.0)print(one.get_booster().get_dump()[0])1row = pd.DataFrame({"mom": [-0.2], "rev": [0.0], "vol": [0.10]})print(round(fit[TARGET].mean(), 4), round(float(one.predict(row)[0]), 4))2
0:[vol<0.119252473] yes=1,no=2,missing=2
	1:[vol<0.0693260431] yes=3,no=4,missing=4
		3:leaf=-0.0180851761
		4:leaf=0.00689769536
	2:[mom<-0.673359573] yes=5,no=6,missing=6
		5:leaf=0.174876675
		6:leaf=0.0442458056

0.0619 0.0688
  1. 1Each line is a question; leaf=... is an answer.
  2. 2The average of the target and the model's prediction for the stock.

*Check:* the top question is "is vol < 0.119?". For vol = 0.10 the answer is yes, which leads to the question "is vol < 0.069?", answered no, and to the leaf 0.0069. The model starts from the average move of the fit years, 0.0619, and adds the leaf: 0.0619 + 0.0069 = 0.0688, and the prediction printed is 0.0688. *What to notice:* a depth-2 tree puts every row in one of four groups (here two groups of calm stocks and two of volatile ones, one of them stocks that fell more than 67 %, whose leaf is 0.1749). The momentum question appears only inside the volatile branch: a deeper tree can ask a different question in each branch. A stump cannot.

02

Depth: how many questions in a row

The depth sets how many groups a tree can cut the rows into, and so how detailed the model can be. A stump adds one effect per tree; a deep tree can describe a combination of features, such as "high volatility *and* a big fall". That is the power, and the danger: with enough questions a tree can single out a handful of rows that happen to share a number, and the next years will not repeat the coincidence.

Worked example 2. *Problem:* which depth is best for 100 trees at a learning rate of 0.05? *Plan:* fit one model per depth on the fit years (before 2011) and score it on those same rows and on the validation years (2011 to 2014), which the model has not seen. Count the leaves too. *Steps:* depth_table, which you write in the lab, does all of this.

main.pyPython
for row in depth_table(fit, valid, [1, 2, 3, 5, 8]):    print(row["depth"], row["leaves"], round(row["rmse_fit"], 5), round(row["rmse_valid"], 5))1print(round(rmse(valid[TARGET], fit[TARGET].mean()), 5))
1 200 0.0565 0.03726
2 400 0.05541 0.03681
3 799 0.05419 0.03675
5 2759 0.05003 0.03684
8 14068 0.04069 0.03739
0.04271
  1. 1Depth, total leaves, error on the fit years, error on the validation years.

*Check:* the fit error falls with every step of depth, from 0.0565 to 0.0407, and the number of leaves explodes, from 200 to 14,068. The validation error falls at first, from 0.03726 (stumps) to 0.03675 (depth 3), and then climbs again to 0.03739 at depth 8. The plain average scores 0.04271, so every depth finds something real. *What to notice:* the fit error keeps falling because the model is describing the fit rows ever more closely; only the validation column tells you where the real gain stops. The best depth is neither the smallest nor the largest.

A rule of thumb for stock panels: depths of 2 to 6 cover nearly all uses. Deep trees need a lot of rows per leaf. With 6,604 fit rows, depth 8 has 14,068 leaves over 100 trees, about 140 per tree, so most leaves hold a few dozen rows.

03

More trees, smaller steps

The second setting is the learning rate: the fraction of each tree that is added to the prediction. The two settings work together. A tree is a correction; the learning rate sets how much of the correction you accept. Small steps make each tree matter less, so more trees are needed to cover the same ground.

Worked example 3. *Problem:* how does the error change as trees are added, for the fit rows and for the validation rows? *Plan:* fit 100 trees of depth 3 with a big step of 0.3 and read staged_rmse on both frames at a few tree counts. *Steps:* below.

main.pyPython
model = fit_model(fit, 100, 3, 0.3)on_fit = staged_rmse(model, fit)on_valid = staged_rmse(model, valid)for k in (1, 5, 11, 25, 50, 100):1    print(k, round(on_fit[k - 1], 5), round(on_valid[k - 1], 5))print(best_rounds(model, valid))2
1 0.06029 0.04027
5 0.05611 0.03733
11 0.05469 0.03668
25 0.05356 0.03681
50 0.0516 0.03695
100 0.04914 0.03726
11
  1. 1Number of trees, error on the fit rows, error on the validation rows.
  2. 2The number of trees with the smallest validation error.

*Check:* the fit error falls all the way, from 0.06029 after one tree to 0.04914 after a hundred. The validation error falls to a minimum of 0.03668 after 11 trees, and then rises to 0.03726. *What to notice:* the right number of trees is the one where the validation curve is lowest, and stopping there is called early stopping (the next topic automates it). Past that point more trees fit noise.

Worked example 4. *Problem:* how many trees does each learning rate want? *Plan:* repeat example 3 for four rates, with depth 3 and room for 100 trees, and read the best number of trees and the best validation error. *Steps:* rate_table.

main.pyPython
for row in rate_table(fit, valid, [0.3, 0.1, 0.05, 0.01], 100, 3):    print(row["learning_rate"], row["best_rounds"], round(row["rmse_valid"], 5))
0.3 11 0.03668
0.1 55 0.03674
0.05 97 0.03675
0.01 100 0.03815

*Check:* a rate of 0.3 wants 11 trees, 0.1 wants 55 and 0.05 wants 97; the validation errors are almost the same, 0.03668, 0.03674 and 0.03675. With 0.01 the answer is 100, the most the table allowed, and the error 0.03815 is worse: the model had not finished learning. *What to notice:* halving the rate roughly doubles the trees, and a smaller rate gives a slightly smoother, slightly better model at the price of time. When best_rounds equals n_trees, the model needs more trees than you gave it.

The usual recipe

Pick a modest depth (3 to 6), set a small learning rate (0.01 to 0.1), allow many trees, and let the validation error choose how many to keep. The learning rate then costs time, not accuracy.

  • FunctionQuestion it answers
  • staged_rmse(model, frame)How does the error change tree by tree?iteration_range=(0, k)
  • leaf_counts(model)How complex is each tree?Feature == Leaf
  • depth_table(fit, valid, depths)Which depth generalises?same trees, same rate
  • best_rounds(model, valid)How many trees to keep?argmin + 1
  • rate_table(fit, valid, rates)How many trees does each rate need?room for enough trees
04

Choose on validation, judge on test

Worked example 5. *Problem:* choose the depth, the rate and the number of trees, and report an honest error. *Plan:* split the time line in three: the fit years (before 2011), the validation years (2011 to 2014) and the test years (2015 on). Choose the depth by the validation error, then the rate and the number of trees, refit on the fit years with those choices and score on the test years once. *Steps:* study runs all of it.

main.pyPython
result = study(panel)print(result["best_depth"], result["best_rate"], result["best_rounds"])print(round(result["rmse_test"], 5), round(result["rmse_test_baseline"], 5))
3 0.3 11
0.05199 0.05453

*Check:* the chosen settings are depth 3, rate 0.3 and 11 trees. On the test years the model scores 0.05199 against 0.05453 for the plain average of the fit years, about 5 % better. *What to notice:* the test error is larger than the validation error (0.052 against 0.037) because the test years are more volatile than the validation years; the comparison that counts is the model against the average on the *same* years. That the model beats the average here, and did not in the first topic, is the difference between a target that has a signal and one that does not.

Do not tune on the test years

If you try twenty settings on the test years and keep the best, the test error is a minimum over twenty tries and is too optimistic. Choosing on the validation years and looking at the test years once keeps the final number honest.

What the real data says56 US stocks; target: the size of the next month's move
Rows6,604 / 2,688 / 7,783fit years (before 2011), validation (2011 to 2014), test (2015 on)
Best depth3validation error 0.03675; stumps 0.03726, depth 8 0.03739
Rate and trees0.3 / 110.1 wants 55 trees, 0.05 wants 97
Test error0.05199the plain average scores 0.05453

Key takeaways

  • Depth sets the detail. A tree of depth d has up to 2^d leaves. Deeper trees fit the fit years better and can fit them too well.
  • The validation curve decides. The fit error always falls; keep the number of trees and the depth where the error on unseen years is lowest.
  • Rate and trees trade off. Halving the learning rate roughly doubles the trees. If the best number of trees is the most you allowed, allow more.
  • Choose once, judge once. Choose on a validation period and look at the test years a single time.
Quick check
Your turn. With a learning rate of 0.2, a model reaches its lowest validation error after 20 trees. About how many trees do you expect with a rate of 0.02?
Pick an answer.
05

What you will build

The lab follows the lecture. Task 1 reads the error tree by tree and task 2 counts the leaves of each tree. Task 3 builds the table of depths, task 4 finds the best number of trees and task 5 builds the table of learning rates. Task 6 chooses the settings on the validation years and judges them once on the test years.

Next topic: you chose the number of trees by looking at the validation curve by hand. The next topic, Regularisation and early stopping, adds penalties that keep every tree small and lets XGBoost stop on its own when the validation error stops improving.

Lab · what's graded

6 tasks · 100 pts
  • The error tree by tree15 pts
  • Count the leaves15 pts
  • The table of depths20 pts
  • How many trees to keep10 pts
  • The table of learning rates20 pts
  • Choose on validation, judge on test20 pts
Explorer · lab-xg-03
▾ lab-xg-03
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-xg-03$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

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