σμ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
  • 日本語
  • 中文
LightGBM skill›Module 3 · Tuning and ranking›Topic 3.1·~50 minIntermediate

Parameter tuning without fooling yourself

Skill positionModule 3 of 4 · Topic 1 of 2
3.1 Parameter tuning without fooling yourself
—Lab score— / 100Total XP—Streak—
Lecture0% read

9 min readCode examples: 6

  1. 01The best of many is lucky
  2. 02Searching: a grid and a random draw
  3. 03How optimistic is the winner?
  4. 04Early stopping uses the validation rows too
  5. 05The panel
  6. 06What you will build

Draw 20 models of exactly the same quality and pick the one that scores best on a small validation sample: its error falls from 0.506 to 0.384, and on fresh rows it is still 0.49. That drop is luck, and a search produces it every time. This topic builds a search, measures the luck, and shows where early stopping hides the same trap.

01

The best of many is lucky

Where we are. The last topic gave you models you can score. Now you have to choose their settings: the number of leaves, the rows per leaf, the learning rate, the number of trees. The usual method is to try many combinations, score each on validation rows, and keep the best. It works, but the winner's score on those rows is not an honest estimate of how it will do later.

DefinitionWinner's curse

The best of many noisy measurements is, on average, better than its true value, because the winner was chosen for having good luck as well as good quality. The more candidates, and the noisier the measurement, the bigger the effect.

Worked example 1. *Problem:* 20 candidates are all exactly as good, with a true error of 0.50. Each is measured on a small sample (noise of 0.05 from the choice of rows) and again on fresh rows (new noise). We pick the candidate with the best sample score among the first k. What do the sample score and the fresh score of the winner look like as k grows? *Plan:* draw the two sets of scores from one random generator and use the function best_of_k of the lab, which returns the winner among the first k with both of its scores. *Steps:* below.

main.pyPython
rng = np.random.default_rng(0)sample = 0.50 + rng.normal(0, 0.05, 20)later = 0.50 + rng.normal(0, 0.05, 20)1table = best_of_k(sample, later)2for k in (1, 5, 10, 20):    index, on_sample, on_later = table[k - 1]    print(k, index, round(on_sample, 4), round(on_later, 4))
1 0 0.5063 0.4936
5 4 0.4732 0.5452
10 9 0.4367 0.511
20 12 0.3837 0.492
  1. 1The winner among the first k, with its score on the sample and on fresh rows.
  2. 2k = 1 is no search at all; k = 20 is a search of 20.

*Check:* with k = 1 the sample score is 0.5063 and the fresh score 0.4936: both are just noise around 0.50. With k = 20 the winner (candidate 12) has a sample score of 0.3837, a fall of 0.12, and a fresh score of 0.4920, no better than before. *What to notice:* nothing was learned. The sample score of the winner fell because the search looked for the luckiest draw, and the fresh score did not follow because luck does not repeat. If you report the 0.3837, you report the winner's curse.

02

Searching: a grid and a random draw

A grid search tries every combination of a few values per setting. Three values for each of three settings is 27 models; five settings with four values each is 1,024. A random search draws a fixed number of candidates from the same space. It spends the same number of fits on more different values of each setting, which matters when only some of the settings change the result.

Worked example 2. *Problem:* build the grid of two values for each of three settings, and draw two random candidates from the larger space SPACE of the lab (6 × 6 × 4 × 3 × 3 = 1,296 combinations). *Plan:* param_grid for the first, sample_candidates with a seed for the second, so that the search can be repeated. *Steps:* below.

main.pyPython
grid = param_grid({"num_leaves": [4, 16], "min_child_samples": [20, 100], "learning_rate": [0.02, 0.05]})print(len(grid), grid[0], grid[1])for candidate in sample_candidates(SPACE, 2, 0):    print(candidate)
8 {'num_leaves': 4, 'min_child_samples': 20, 'learning_rate': 0.02} {'num_leaves': 4, 'min_child_samples': 20, 'learning_rate': 0.05}
{'num_leaves': 64, 'min_child_samples': 50, 'learning_rate': 0.1, 'n_estimators': 30, 'colsample_bytree': 0.5}
{'num_leaves': 2, 'min_child_samples': 5, 'learning_rate': 0.01, 'n_estimators': 30, 'colsample_bytree': 1.0}

*Check:* the grid has 2 × 2 × 2 = 8 candidates, and the last setting (learning_rate) changes fastest: the first two candidates differ only in the learning rate. The two random candidates are very different from each other (64 leaves and 30 trees against 2 leaves and a learning rate of 0.01); with the same seed you get the same ones again. *What to notice:* the seed makes a random search a record you can repeat and audit.

To score a candidate, fit one model with the settings of BASE and the candidate's on top, and measure the error on the rows you care about. evaluate fits once and returns one score per frame, so that the same model can be scored on the validation sample, the full validation rows and the test rows.

03

How optimistic is the winner?

Example 1 showed the effect with made-up numbers. The tool to measure it on a real search is the same table: for each k, the winner among the first k candidates chosen by the validation score, and the score of that winner somewhere else. If the second column keeps improving, the search found something; if only the first one improves, it found luck.

expected best of k ≈ true value − σ × c(k), c(k) grows slowly with k(1)σ: the noise of one measurement; c(k): about 0 for k = 1, about 1.9 for k = 20 and 2.5 for k = 100 when the candidates are equally good and the noise is normal. Fewer rows mean a larger σ
  • FunctionQuestion it answers
  • param_grid(space)What does a grid of values contain?last setting fastest
  • sample_candidates(space, n, seed)Which candidates does a random search try?one generator, repeatable
  • evaluate(params, train, others)How good is one candidate?one fit, many scores
  • best_of_k(select, report)How lucky was the winner?the first of equal ones
  • early_stop(curve, patience)When does training stop?equal is not better
04

Early stopping uses the validation rows too

The number of trees is the setting most people do not search: they let early stopping find it. LightGBM evaluates the model on the validation rows after every tree, remembers the round with the smallest error, and stops when that round is patience rounds in the past. It keeps the best round. The rule is short and the lab asks you to write it.

Worked example 3. *Problem:* the validation error after 1, 2, ... 7 rounds is 5, 4, 3, 3.5, 3.6, 3.7, 3.8. With a patience of 3, where does LightGBM stop and which round does it keep? Then a curve where the minimum comes late: 4, 3, 3, 3, 3, 2 with a patience of 2. *Plan:* the best round so far is round 3 (error 3); the rounds 4, 5 and 6 do not beat it, and at round 6 the best round is 3 rounds back. *Steps:* below.

main.pyPython
print(early_stop([5, 4, 3, 3.5, 3.6, 3.7, 3.8], 3))print(early_stop([4, 3, 3, 3, 3, 2], 2))
(3, 6)
(2, 4)

*Check:* the first curve gives (3, 6): keep round 3, stop after round 6, so rounds 7 onwards are never trained. The second gives (2, 4): the equal values in rounds 3 to 5 are not improvements, the best round stays 2, and training stops at round 4, before the 2 at round 6 is ever reached. *What to notice:* early stopping chooses the number of trees with the validation rows, so it is part of the search. The winner's curse applies to it as well: the error at the best round is slightly better than the error you will see later.

05

The panel

Worked example 4. *Problem:* on the 56 stocks, tune a LightGBM model for the size of next month's move with a small grid, then with a random search whose candidates are chosen on a 300-row validation sample, and look at what the test rows (2015 onwards) say. *Plan:* fit every candidate on the fit rows (before 2011); score on the validation rows (2011 to 2014); report the winners on the test rows. *Steps:* below.

main.pyPython
panel = build_panel(load_close())fit, valid, test = split_panel(panel)grid = param_grid({"num_leaves": [4, 16], "min_child_samples": [20, 100], "learning_rate": [0.02, 0.05]})scores = [evaluate(c, fit, [valid])[0] for c in grid]best = int(np.argmin(scores))print(best, round(min(scores), 5), round(max(scores), 5))print(round(evaluate(grid[best], fit, [test])[0], 5), round(evaluate({}, fit, [test])[0], 5))
3 0.03669 0.03745
0.05194 0.05192

*Check:* the best of the 8 candidates is the fourth (index 3, num_leaves=4, min_child_samples=100, learning_rate=0.05) with a validation error of 0.03669; the worst has 0.03745. On the test rows the tuned model scores 0.05194 and the default settings 0.05192. *What to notice:* the whole grid is within 0.0008 on the validation rows, and the tuned model is not better than the default on later months. On this panel the features say little, so there is little for the settings to improve. The gap between 0.037 (validation) and 0.052 (test) is not about tuning at all: 2015 onwards simply has larger moves.

main.pyPython
panel = build_panel(load_close())fit, valid, test = split_panel(panel)1small = valid.sample(300, random_state=1)drawn = [{**c, "subsample": 0.8, "subsample_freq": 1, "random_state": i} for i, c in enumerate(sample_candidates(SPACE, 16, 0))]2results = [evaluate(c, fit, [small, valid, test]) for c in drawn]3small_scores, valid_scores, test_scores = (list(column) for column in zip(*results))by_valid, by_test = best_of_k(small_scores, valid_scores), best_of_k(small_scores, test_scores)print(round(float(np.std(small_scores)), 5))for k in (1, 4, 8, 16):    print(k, round(by_valid[k - 1][1], 5), round(by_valid[k - 1][2], 5), round(by_test[k - 1][2], 5))
0.00183
1 0.03375 0.03766 0.05237
4 0.03353 0.03715 0.05239
8 0.03334 0.03687 0.05192
16 0.03334 0.03687 0.05192
  1. 1300 rows only: a noisy way to compare models.
  2. 2Three scores for each candidate, from one fit.
  3. 3Each winner is chosen by the small sample and reported on the other two sets.

*Check:* the 16 random candidates differ by 0.00183 (standard deviation) on the sample. The winner among the first one has a sample score of 0.03375, among the first four 0.03353, among 8 and 16 0.03334: the search keeps finding a better sample score. On the full validation rows the same winners score 0.03766, 0.03715, 0.03687, 0.03687: they improve too, so part of the gain is real, but the sample score is always lower than the full-validation score of the same model, by about 0.004. On the test rows the winners score 0.05237, 0.05239, 0.05192, 0.05192. *What to notice:* all three columns improve by a similar small amount (0.0004 to 0.0005), so this search found a little signal, and the table cannot tell how much of the gain is luck: that is the point of reporting on rows that took no part. In example 1, where every candidate was equal, the same table would show a falling first column and a flat second. The large distance between 0.033 and 0.052 is the period: 2015 onwards has larger moves.

How to keep a search honest

Choose on one set of rows (validation), report on another that played no part in the choice (test), and give the search budget (how many candidates) with the number. Use as many validation rows as you can: the noise of a score falls with the square root of the number of rows. For time series choose on several consecutive blocks and average, as in the validation topic of the XGBoost skill.

Last, early stopping on the real panel: allow 400 trees, stop after 20 rounds without improvement on the validation rows, and compare your rule with the one LightGBM applied.

main.pyPython
panel = build_panel(load_close())fit, valid, test = split_panel(panel)model = lgb.LGBMRegressor(**{**BASE, "n_estimators": 400})model.fit(fit[FEATURES], fit[TARGET], eval_set=[(valid[FEATURES], valid[TARGET])], eval_metric="rmse", callbacks=[lgb.early_stopping(20, verbose=False)])curve = model.evals_result_["valid_0"]["rmse"]print(model.best_iteration_, len(curve), early_stop(curve, 20))
119 139 (119, 139)

*Check:* LightGBM keeps round 119 and has trained 139 rounds when it stops; your early_stop returns (119, 139). *What to notice:* 119 trees out of the 400 allowed, found with the validation rows. That choice is made on 2011 to 2014, so those rows are not a clean test of the final model any more.

What the real data says56 US stocks; fit rows before 2011, valid 2011 to 2014, test 2015 onwards
Grid of 80.03669 to 0.03745validation error of the best and the worst candidate
Tuned against default0.05194 / 0.05192test error: tuning did not help on later months
Random search, 300 rows0.03375 → 0.03334sample score of the winner of the first 1 and of 16 candidates
Same winners on test0.05237 → 0.05192fresh rows: a change of the same small size
Early stoppinground 119stopped after 139 rounds; the same as LightGBM

Key takeaways

  • The winner's score is optimistic. The best of many candidates is chosen partly for luck; the more candidates and the fewer validation rows, the larger the optimism.
  • Report on rows that took no part. Choose on validation rows, report on test rows, and say how many candidates were tried.
  • Random search is repeatable. One seeded generator makes a random search a record that can be audited and extended.
  • Early stopping is a search too. It picks the number of trees with the validation rows: round of the smallest error so far, stop after patience rounds without a strictly smaller one.
Quick check
Your turn. You try 50 candidates and the best one scores 0.80 on the validation rows. Which statement is the safest?
Pick an answer.
06

What you will build

The lab follows the lecture. Task 1 builds a grid, task 2 draws random candidates and task 3 scores a candidate. Task 4 is the table that measures the winner's luck. Task 5 is the early-stopping rule. Task 6 runs the grid, the random search on a small validation sample and early stopping on the real panel.

Next topic: so far the target was a number or a yes/no. The next topic, lambdarank and group queries, ranks stocks within each month, which needs a different objective and a way to tell LightGBM which rows belong together.

Lab · what's graded

6 tasks · 100 pts
  • A grid of settings10 pts
  • Random candidates10 pts
  • Score a candidate10 pts
  • How lucky is the winner?20 pts
  • The early-stopping rule15 pts
  • Tuning on the panel35 pts
Explorer · lab-lg-05
▾ lab-lg-05
▾ data
…
bash · in-browser
learner@quantcraft:~/lab-lg-05$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-lg-05 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