EVERYTHING AIAI engineering, made visual
0/18 complete
LESSON 12 · MACHINE LEARNING × AI · BUILD

Turn the knobs
before you train.

grid · random · Bayesian are three ways to search the same surface, priced by evaluations. On this one the peak is 10.000: the 4 × 4 grid stops at 9.961, sixteen random draws reach 9.986, and ten guided steps find 10.000.

75 MIN · 7 CHAPTERSPREREQ · PHASE 2, LESSON 11
FIG. 12 / THREE SEARCHES, ONE SURFACE
SYNTHETIC SURFACE · BEST-SO-FAR → TRUE 10.000 grid random Bayesian
LESSON 12TYPE · BUILD~75 MINPREREQ · PHASE 2 · LESSON 11ORIGINAL LESSON ↗
THE 60-SECOND VERSIONThen show me the knobs ↓
01 / PARAMETERS LEARN, KNOBS DECIDE

Training writes the weights. You write the knobs.

Weights, biases and split thresholds are learned — the optimizer moves them every step. The learning rate, number of trees, depth, regularization, batch size and dropout are chosen before training starts. There is one learned solution per configuration; there is no such guarantee for the configuration itself.

5⁶ = 15,625 combinations
02 / THE TEST SET IS A RECEIPT

Tuning is fitting, so do it on validation.

Every configuration comparison you make on the test set consumes it. Choose features, models and knobs on validation; touch the test split once for the final report. Run 100 trials and the winner looks about 2.5σ better than average before any real signal is counted — that is selection luck, not skill.

tune on validation · report on test
03 / SEARCH IS A BUDGET PROBLEM

Wide first, then narrow, then retrain.

Start at defaults, run 20–50 wide random trials with early stopping, read which knobs matter, then refine 50–100 trials with random or Bayesian search in the narrowed range and retrain on all training data. Grids are for two knobs you can afford to exhaust; beyond that, breadth beats precision.

random breadth → Bayesian focus → retrain
MENTAL MODEL IN ONE SENTENCE

Hyperparameter tuning is one more layer of fitting: the search fits configurations to the validation folds, so the winner’s validation score is optimistic — the honest number is a locked test set or nested cross-validation, and the cheapest way to search is wide random first, Bayesian after.

By the end you will be able to tell parameters from hyperparameters, price a grid before running it, choose random search over grid search for the right reason, explain the surrogate and acquisition split of Bayesian optimization, use early stopping and schedules to buy the same answer for less, and report a score that includes the cost of tuning.

PARAMETERS VS KNOBS

Parameters learn.
Hyperparameters decide how.

Two kinds of numbers live in a model. Training writes one kind; you write the other — and there are far more ways to write it than you can ever try.

Parameters are the numbers the optimizer updates during fit(): weights, biases, and the split thresholds a tree chooses. Hyperparameters are the numbers set before training starts that control how that learning happens. A rule of thumb: if it changes while training runs, it is a parameter; if you choose it to start training, it is a hyperparameter.

The split matters because the two kinds of numbers have completely different costs. There is exactly one set of learned parameters for a given configuration — the optimizer finds it. There is no such guarantee for the knobs, and the space is large enough that how you search it decides what you find.

TRAINING LOOPthe optimizer writes the numbersforward passlossgradientupdate weightsthousands of small updates — parametersTUNING LOOPyou write the numbersconfigurationtrain on trainscore on validationpick the next configurationone score per configuration — hyperparameters
Training runs inside tuning. Each spoke of the right wheel costs a full run of the left one, so the number of configurations is the budget that matters.
HyperparameterWhat it controlsTypical range
Learning rateStep size of each update0.001 – 1.0 · log scale
Trees / epochsHow long to train10 – 10,000
Max depthModel complexity1 – 30
Regularization λOverfitting prevention0.0001 – 100 · log scale
Batch sizeGradient-estimate noise16 – 512 · linear
Dropout rateFraction of units dropped0.0 – 0.5
Worked check: how fast does a grid grow?

A logistic regression on 8 features learns 9 parameters (8 weights + 1 bias) no matter how you configure it. Now count the knobs instead. If each has 5 reasonable values, the grid of combinations is 5 raised to the number of knobs:

5^4 = 625 (4 knobs) 5^5 = 3,125 (5 knobs) 5^6 = 15,625 (6 knobs) at 10 s per fit: 15,625 × 10 s = 156,250 s = 43.4 h = 1.8 days with 5-fold CV: 78,125 fits × 10 s = 781,250 s = 217 h = 9.0 days one more knob: 5^7 = 78,125 combos · 781,250 s = 9.0 days with 5-fold CV: 3,906,250 s = 45 days

Nothing about the model got smarter; the search just got deeper. The rest of this lesson is about spending those hours where they buy the most.

Quick check

Which of these does training write by itself, with no choice from you?

DON’T TOUCH THE TEST SET

Tune on validation.
Report on test.

Searching configurations is fitting. Do it on the test set and the number you report is the maximum of many noisy guesses, not what the model will do next.

The three-way split from Lesson 01 exists for exactly this reason. Training data fits the parameters. Validation data chooses everything else: features, architecture, and every hyperparameter. The test data measures the final result — once. Tuning on the test set folds the validation role into it, so the reported score is the best of N looks at the same rows.

That is not a small distortion. When you compare many configurations, the winner is selected partly for genuine quality and partly for luck on those specific validation rows. Report the winner’s validation score as if it were its true skill and you are reporting the luck too. The fix is structural: keep a test set that no choice ever touched, or wrap the whole tuning procedure in nested cross-validation (Chapter 06).

train · 60%validation · 20%test · 20%20–100 candidate configurationstouched oncepick the best configuration herereport exactly once, on datathat choosing never sawevery decision (which features, which knobs) consumes validation; the test set is a receipt, not a steering wheel
Tune on the validation block, report once on the test block. If the test block ever influenced a choice, it stopped being a test set.
Derivation: why best-of-N looks better than it is

Imagine 20 configurations whose true quality is identical — every difference you see is noise on the validation split. Model each estimate as a standard normal draw around the shared truth. What does the winner look like?

P(a single config looks ≥ 2σ better than truth) = 0.0228 P(all 20 look below 2σ) = 0.97725^20 = 0.631 P(at least one looks ≥ 2σ better) = 1 − 0.631 = 0.369 so in 36.9% of 20-way comparisons, a "2σ win" is pure selection luck. expected edge of the winner: E[max of 20 standard normals] ≈ 1.87σ with 40 configs: P(a ≥ 2σ win) = 1 − 0.97725^40 = 0.602 E[max of 40] ≈ 2.16σ with 100 configs: E[max of 100] ≈ 2.51σ

A 100-trial sweep guarantees that its winner looks about 2.5σ better than an average configuration before any real signal is counted. Validation is still the right place to make those choices — it just means the winner’s score is optimistic, and the honest number comes from data the search never saw.

Quick check

A pipeline tunes 40 configurations on validation and reports the best validation score as the expected test score. What did it actually measure?

GRID VS RANDOM

Grid is a floor plan.
Random is a handful of darts.

With the same budget, the two strategies buy completely different things: coverage of every combination, or resolution in each knob. Usually you want the second.

Grid search evaluates every combination in a list of values. It is exhaustive and trivially reproducible: a 3 × 3 grid of learning rate and depth runs exactly 9 fits. But the cost multiplies with every knob — the same 5 values across 6 knobs is 15,625 fits — and that exponential blow-up is the curse of dimensionality showing up in a search space. The coverage is worse than it looks, too: if only the learning rate matters, those 9 fits test 3 distinct learning rates.

Random search draws each knob from a distribution, one draw per trial. The same 9 trials test 9 distinct learning rates, and every other knob gets 9 values too. This is why random search so often wins at equal budget: it follows the Bergstra & Bengio observation that most problems have low effective dimensionality — one or two knobs do most of the work, and the rest are nearly flat. A grid wastes trials varying the flat directions; random spends them all on every direction.

The one place random beats grid for free is the search scale. Draw the learning rate and regularization strength log-uniform, so 0.001–0.01 gets as many samples as 0.1–1.0. Draw batch size and depth linearly. Match the distribution to how the knob actually behaves.

The same budget, two search strategies

One fixed surface. The grid spends its evaluations on graph paper; random spends them everywhere. Drag the reveal slider to watch each strategy’s best-so-far score climb.

budget: 16 evaluations per method grid best-so-far 9.961 random best-so-far 9.986 unique learning rates used so far: grid 4 random 16 final: random leads by 0.025 the optimum sits at lr ≈ 0.0182, between grid lines.

Change the budget and re-run: with few evaluations, breadth in the knob that matters beats precision in the knobs that do not.

Derivation: the coverage and the odds, computed

Coverage. A grid of m values per knob over k knobs is mᵏ evaluations, but if only one knob matters, the grid offers only m distinct values of it. Random search offers all mᵏ distinct values at the same price.

3 × 3 grid, 9 evals → 3 unique learning rates 9 random evals → 9 unique learning rates 5^6 = 15,625 · add one knob → ×5 again = 78,125 P(one random draw lands within 5% of the optimum) = 0.05 P(60 draws all miss) = 0.95^60 = 0.0461 P(at least one hit) = 1 − 0.0461 = 0.954 (95.4%) log-uniform over 0.001 … 1.0 (3 decades): each decade gets 1/3 ≈ 33.3% of the draws linear sampling: 1 − 0.01/0.999 = 99.1% of draws land above 0.01

The lab in numbers. The displayed surface peaks at 10.000 at lr ≈ 0.0182. A 4 × 4 grid (16 evaluations) tops out at 9.961 — its best point is lr 0.01, the nearest grid line. Sixteen random draws (seed 7) reach 9.986 by their fourth evaluation, finding lr 0.025. Over 10 seeds, random won all 10 times, scoring 9.964–10.000 (mean 9.989). Only when the grid is dense enough to land beside the optimum does it catch up: a 6 × 6 grid (36 evaluations) hits 9.9975 because 0.4 is 0.02 away from the true peak. The lesson is about budget: spend small budgets on breadth, not precision.

BAYESIAN OPTIMIZATION

Stop guessing.
Learn from every result.

Random search never notices that high learning rates diverge. A surrogate model does — and an acquisition function turns that knowledge into where to look next.

Bayesian optimization replaces guessing with two pieces. First, a surrogate model — usually a Gaussian process — is fitted to every (configuration, score) pair observed so far. At any candidate point it returns a prediction μ(x) and an uncertainty σ(x). Plain English: “the score here is probably around this, and here is how surprised I could be.”

Second, an acquisition function scores candidates using both numbers and picks the next evaluation. That score is where the exploration/exploitation trade-off lives. The classic choice is Expected Improvement (EI): the average amount by which the next evaluation is expected to beat the current best. UCB is simpler: prediction plus κ times uncertainty. Whichever you use, the rule is the same — a point wins by being promising or by being unknown.

A real Gaussian-process hunt on a 1-D objective

Four starting points, then each step fits the surrogate and evaluates where Expected Improvement is largest. Watch the uncertainty band collapse onto the peak.

observations: 4 initial + 0 EI = 4 best score so far: 0.9218 at x = 0.550 surrogate at the next pick: x = 1.000 μ = 0.520 σ = 0.628 EI = 0.0967 ← largest on the grid the EI curve is fat at both ends early on: uncertainty is an opportunity, so the optimizer spends its first step at the untouched edge x = 1.0.

Mean alone says “stay at x = 0.55 where the best score is”; EI says “x = 1.0 is unexplored, that is where the information is.” It visits the edge first, then closes in on the peak.

Derivation: the surrogate and Expected Improvement, with numbers

The surrogate. With observations y at points X, the Gaussian process prediction at a new point x* is a weighted average of the observed scores, weighted by proximity — plus an uncertainty that shrinks near observed points:

μ(x*) = k*ᵀ (K + σₙ²I)⁻¹ (y − ȳ) + ȳ σ²(x*) = k(x*, x*) − k*ᵀ (K + σₙ²I)⁻¹ k* K is the n × n grid of kernel values between observed points; k* is the n-vector of kernel values from x* to each observation. The inverse is the price of the answer — and it is tiny next to training the model itself.

The acquisition. With best score f_best so far, EI is

z = (μ(x) − f_best) / σ(x) EI(x) = (μ(x) − f_best)·Φ(z) + σ(x)·φ(z) Φ and φ are the standard-normal CDF and PDF: Φ(z) is "probability", φ(z) is "height of the bell". In words: improvement × how likely, plus uncertainty × its upside.

Worked comparison. Best so far is 0.7. Candidate A has μ = 0.8, σ = 0.25; candidate B has μ = 0.6, σ = 0.6. Which does EI evaluate?

A: z = (0.8 − 0.7)/0.25 = 0.4 Φ(0.4) = 0.6554, φ(0.4) = 0.3683 EI = 0.1 × 0.6554 + 0.25 × 0.3683 = 0.1576 B: z = (0.6 − 0.7)/0.6 = −0.1667 Φ(−0.1667) = 0.4338, φ(−0.1667) = 0.3934 EI = −0.1 × 0.4338 + 0.6 × 0.3934 = 0.1927 EI picks B — lower mean, higher uncertainty. UCB with κ = 2 agrees: A = 0.8 + 0.5 = 1.30, B = 0.6 + 1.2 = 1.80.

The lab in numbers. The four starting points leave the best at 0.9218 (x = 0.55). EI at that high-mean point is only 0.0146, while the untouched edge x = 1.0 has EI 0.0967 — so the first step explores the edge (score 0.5033). The next step exploits: x = 0.653, score 0.9812, then x = 0.633, 0.9970. Five EI steps in, the best is 0.9989; ten steps reach 0.9992. Ten guided evaluations did what random search typically needs 25–50 draws to match — the 2–5× fewer evaluations the source reports.

Quick check

After the four starting points, the surrogate's highest mean sits at x = 0.55, yet the first EI step goes to x = 1.0. Why?

EARLY STOPPING & SCHEDULES

Buy information
at the lowest price.

Not every configuration deserves the full training budget. Stopping bad runs early, and letting the learning rate move during a run, are the two cheapest tuning tricks in the book.

Early stopping ends a run when validation performance has not improved for patience consecutive epochs, and keeps the best checkpoint rather than the last one. Inside a search, this is not just a time-saver: a configuration that is clearly bad after 10 epochs does not need 200. Median pruning goes further and compares a trial’s intermediate score with the median of completed trials at the same step. Hyperband turns pruning into a tournament: start many configurations on a tiny budget, keep the best fraction, and triple the budget of the survivors.

The other cheap trick is a learning-rate scheduler. Instead of tuning one fixed constant, you choose a shape for it. A high rate early makes fast progress; a small rate late settles the solution. Schedules often beat every fixed learning rate because no single value has to serve both phases of training.

Buy the same answer for fewer epochs

Three configurations, 20 epochs each. Raise the patience and watch bad runs die earlier — the best checkpoint never changes.

lr 0.001 · too slow best 0.524 @ epoch 20 · runs to 20 (never stops) lr 0.05 · good best 0.340 @ epoch 10 · stops at 13 (saves 7 epochs) lr 0.8 · too hot best 1.050 @ epoch 2 · stops at 5 (saves 15 epochs) epochs spent: 38 of 60 — 36.7% saved patience 0 = no early stopping. patience too small stops on noise; patience 3–5 usually keeps the best checkpoint and the savings.

The good run’s best epoch is 10 whatever the patience: stop markers end the search, they do not change the checkpoint you keep. The divergence run is killed at epoch 5 — 15 epochs of compute returned to the search budget.

SchedulerRuleWhen to reach for it
Step decaylr × 0.1 every N epochsClassic CNN training
Cosine annealinglr × 0.5 × (1 + cos(πt/T))Modern default
Warmup + decaylinear rise, then cosine fallTransformers
One-cyclerise and fall over one cycleFast convergence
Reduce on plateau× factor when the metric stallsSafe default
Derivation: what patience and Hyperband actually save

Patience, computed. The good run in the lab bottoms out at 0.340 on epoch 10, then drifts up as it overfits. With patience 3 the stop lands on epoch 13 — 7 of 20 epochs returned. With patience 5 it lands on 15 — 5 of 20 saved. The divergence run bottoms out at 1.05 on epoch 2 and is killed at epoch 5 with patience 3: 15 epochs of compute handed back. Across all three runs the ledger is 38 of 60 epochs at patience 3 (36.7% saved) and 42 of 60 at patience 5 (30%).

good run: best 0.340 @ 10 · stop @ 13 (patience 3) saves 7/20 = 35% of that run diverging: best 1.050 @ 2 · stop @ 5 (patience 3) saves 15/20 = 75% of that run all three: 38/60 epochs = 36.7% saved the kept checkpoint is unchanged — stop markers end the run, they do not move the best epoch.

Hyperband, computed. Start 81 configurations at 1 epoch; keep the top third (27) and give them 3 epochs; keep the top third again (9) and give them 9 epochs.

81 × 1 = 81 epochs 27 × 3 = 81 epochs 9 × 9 = 81 epochs total = 243 epochs vs 81 × 9 = 729 = 3.00× cheaper, winner comparable with a 4th rung (3 × 27): 324 vs 2,187 = 6.75× then retrain the winner fully: 243 + 9 = 252 vs 729 (2.9×)

Cosine, computed. With lr₀ = 0.1 and T = 10 epochs, lr(t) = 0.1 × 0.5 × (1 + cos(πt/10)) gives 0.100 at t = 0, 0.050 at t = 5, and 0.000 at t = 10. One tuned constant became a schedule that starts fast and lands softly.

NESTED CROSS-VALIDATION

Two loops:
one to choose, one to judge.

Ordinary cross-validation tells you how good the winner looks. Nested cross-validation tells you how good the whole procedure — tuning included — actually is.

Tuning on a single validation split risks overfitting that split: the winning configuration may simply be the one that got lucky on those rows. Nested cross-validation separates the two jobs with two loops. The outer loop splits the data into a test part and a training part, five times. Inside each outer fold, the inner loop runs its own cross-validation on the training part to pick hyperparameters. The chosen configuration is then scored once, on the outer test part that the inner loop never touched.

Each outer fold finds its own best configuration independently — they are allowed to disagree. The mean of the outer scores is an unbiased estimate of the procedure: feature pipeline, tuning budget and all. It is not the score of one model, and it is not how you pick the final configuration for deployment; for that you tune once on the full training data. Nested CV answers the harder, more honest question: if I ran this whole workflow on fresh data, what should I expect?

Two loops, one honest number

Pick an outer fold. The inner loop tunes λ on that fold’s training rows only; the outer score is measured once on the held-out rows. The optimistic score below is what happens when the same rows do both jobs.

OUTER SPLIT · 12 rows → 4 foldsfold 1fold 2fold 3fold 4INNER SPLIT OF FOLD 1 TRAINING ROWS → 3 folds

held-out rows: 1, 5, 9 · tuned on rows 2, 3, 4, 6, 7, 8, 10, 11, 12

outer fold 1 test rows 1, 5, 9 inner winner: λ = 0.1 outer MSE: 0.1578 honest score (mean of 4 outer folds): 0.1575 optimistic score (best full-data CV): 0.1191 (λ = 0.01) optimism: 0.0384 folds picked λ = 0.1, 0.1, 0.01, 0.01 the folds disagree, so no single split is the truth.

The optimistic number is not a lie anyone tells on purpose — it is what you get when the same data chooses λ and reports the score. Nested CV separates the two jobs.

λinner CV MSE (fold 1 training rows)verdict
0.010.1743rejected
0.10.1739tuned here → evaluated once on the held-out rows
10.1936rejected
101.4955rejected

The model is one ridge weight, w = Σxy / (Σx² + λ), so the two loops cost almost nothing here. With a real model each inner fit is a full training run — the 5 × 5 × 27 = 675 fits the lesson prices below.

Derivation: the bill, computed

The two loops multiply. With 5 outer folds, 5 inner folds, and a 3 × 3 × 3 = 27-point inner grid, one full nested run costs:

5 outer × 5 inner × 27 grid = 675 model fits at 2 s per fit: 675 × 2 s = 1,350 s = 22.5 min at 5 min per fit: 675 × 5 min = 3,375 min = 56.3 h the inner winner's score is NOT the honest number; the honest number is the mean across outer folds.

The lab in numbers. On the 12-row ridge example, the optimistic approach — choose λ by scoring every λ on all rows, then report that score — gives 0.1191 MSE. Nested CV, where each fold tunes on its own training rows and is judged on its held-out rows, gives 0.1575: an optimism of 0.0384 MSE, and in RMSE terms 0.345 versus 0.397 — the optimistic protocol understates the error by about 13%. The four folds even disagreed about λ (0.1, 0.1, 0.01, 0.01), which is exactly why one split’s winner is not a truth. Use nested CV when the number will be published, compared across teams, or used to make a high-stakes decision — and plain validation splits for ordinary iteration.

Quick check

The inner loop picks λ = 0.1 in two outer folds and λ = 0.01 in the other two. What is the correct reading?

THE PLAYBOOK

Wide first. Then narrow.
Then retrain.

The workflow that survives contact with a real budget: start at the defaults, search wide with random trials, learn which knobs matter, then refine and retrain.

1. Start with library defaults. They encode years of practitioner experience and are often 80% of the way there. The first sweep is looking for the last 20%, so do not spend it re-deriving the first 80%.

2. Coarse random search, wide ranges, 20–50 trials. Use log-uniform distributions for the learning rate and regularization, linear for depth and batch size, and early stopping to kill bad runs fast. 3. Analyze what correlated with performance — Optuna’s parameter-importance plot, or just the best 10 trials side by side — and narrow the ranges. 4. Fine search with random or Bayesian methods, 50–100 trials inside the narrow space. 5. Retrain on all training data with the winning configuration, and evaluate once on the test set.

Spend the budget where the variation is: put 60% of trials on the top two knobs (almost always the learning rate plus one more) and 40% on everything else. When in doubt, run twice as many trials as you have hyperparameters — six knobs means at least 12 trials, and 50 is a strong default. Random search at 50 trials beats a carefully designed small grid more often than intuition suggests.

Walk the surface: which knob is doing the work?

Drag the probe anywhere on this validation-score heat map (or use the two sliders). The bright band runs almost straight up: learning rate sets the score, the second knob barely moves it.

probe: lr 0.126 · depth 4.1 score 9.652 best on this surface: 10.000 at lr 0.0182, depth 5.0 gap 0.348 moving the probe up or down changes the score by less than 0.02; moving it along the bright band changes it by up to 1.7.

This is why importance-aware budgets exist: spend 60% of the trials on the top two knobs, leave the flat directions at their defaults.

Derivation: a worked tuning budget

Take the budget lab’s defaults: 27 grid configurations, 5-fold validation, 200 epochs per fit, 1.5 seconds per epoch.

full grid: 27 × 5 = 135 fits × 200 epochs = 27,000 epoch-fits × 1.5 s = 40,500 s = 11.25 h nested grid: 5 × 5 × 27 = 675 fits × 200 × 1.5 s = 202,500 s = 56.25 h = 2.3 days — the price of an honest number random + early stopping: 40 trials × 5 folds = 200 fits × 60 avg epochs = 12,000 epoch-fits × 1.5 s = 18,000 s = 5.0 h = 11.3× cheaper than nested, 2.25× cheaper than the full grid — and it explores freely. the six-knob grid from Chapter 01: 15,625 × 5 × 200 × 1.5 s = 271 days 60% of that on two knobs is still 163 days

The arithmetic is not pro-search or anti-search; it is pro-order. A 5-hour random sweep plus a 1-hour Bayesian refinement and a one-day nested validation costs a fraction of the blind grid and answers a better question. And the flat directions in the surface above get their defaults, not their own experiments.

Price the sweep before you run it

Configurations × folds × epochs × seconds: change any number and the bill updates. This is the arithmetic that decides random versus grid.

Full grid
27 configs × 5 folds = 135 fits× 200 epochs = 27,000 epoch-fits× 1.5 s = 11.3 h
exhaustive, and you keep every fit until the end
Nested grid
5 outer × 5 inner × 27 = 675 fits× 200 epochs = 135,000 epoch-fits× 1.5 s = 2.3 days
the honest estimate; use it for the final report, not the sweep
Random + early stopping
40 trials × 5 folds = 200 fits× 60 avg epochs = 12,000 epoch-fits× 1.5 s = 5.0 h
2.25× cheaper than the full grid — and early stopping decides the honest epoch count

The chapter’s six-knob grid is the same formula at a bigger scale: 15,625 configs × 5 folds × 200 epochs × 1.5 s = 271 days. A 40-trial random search with early stopping finishes in 5 h.

nested / grid = 5.0× nested / random = 11.3× grid / random = 2.25× rule of thumb: 2× as many random trials as hyperparameters, then refine.
ModelTune firstRecommended searchBudget
Random forestn_estimators, max_depth, min_samples_leafRandom, ~50 trialsLow
Gradient boostinglearning_rate, n_estimators, max_depthBayesian, ~100 + early stoppingMedium
Neural networklearning_rate, weight_decay, batch_sizeBayesian or random, 100+High
SVM (RBF)C, gammaGrid on log scale, 25–50Low
Lasso / ridgealpha1D log-scale search, ~20Very low
XGBoostlearning_rate, depth, subsample, colsampleBayesian, 100–200 + early stoppingMedium

Importance tiers to guide step 3: high — learning rate, regularization, and the iteration count (replace the last one with early stopping); medium — depth or layer count, minimum samples or weight decay, subsample; low — max features, activation choice, and batch size within a reasonable range. Never search batch size on a log scale; always search learning rate and regularization on one.

CHECK YOURSELF

Five questions.
Then the terms worth keeping.

Answer before you look. The random-versus-grid question and the test-set question are exactly the ones that separate a memorized definition from a working instinct.

0 / 5 answered · 0 correct

01What is the difference between a parameter and a hyperparameter?

02Grid search over 4 hyperparameters with 5 values each requires how many evaluations?

03Why does random search often outperform grid search with the same evaluation budget?

04In Bayesian optimization, what does the acquisition function balance?

05You tune hyperparameters on the test set and report the best test performance. What is wrong with this approach?

Key terms, demystified

Click a card to swap the lazy description for what it actually means.

Exercises from the lesson

Four problems with exact numbers — grid versus random, a Hyperband bracket, an EI computation and a budget. Try first; a worked answer is one click away.

  1. Run grid search and random search with the same total budget (16 evaluations). Compare the best scores on the lesson's surface. Repeat with 10 different seeds. How often does random search win, and when can the grid catch up?
    Show one worked answer

    The 4×4 grid evaluates the same 16 points every time and tops out at 9.961 — its best point is (lr 0.01, depth 4), while the true maximum is 10.000 at (lr 0.0182, depth 5). The grid cannot see between its own lines. Sixteen random draws reached 9.986 with seed 7 and beat the grid in 10 of 10 seeds, with results between 9.964 and 10.000 (mean 9.989). The margin comes from resolution in the one knob that matters: 4 unique learning rates for the grid versus 16 for random. Grid catches up only when it is dense enough that a grid line lands near the optimum — on this surface a 6×6 grid (36 evaluations) scores 9.9975 because x = 0.4 is 0.02 away from 0.42, while 36 random evaluations score about 9.988. At small budgets, spend on random breadth, not grid precision.

  2. Implement Hyperband from scratch: start 81 configurations with 1 epoch each, keep the top third, triple the budget of the survivors, and repeat. Compare total compute against training all 81 configurations for the full budget.
    Show one worked answer

    Round 1: 81 configs × 1 epoch = 81 epochs; keep 27. Round 2: 27 × 3 = 81 epochs; keep 9. Round 3: 9 × 9 = 81 epochs; the winner is the best of those. Total = 81 + 81 + 81 = 243 epochs versus 81 × 9 = 729 for the full grid — exactly 3.00× cheaper, and no single run is longer than 9 epochs. Add a fourth rung (keep 3, give them 27 epochs): 324 epochs versus 81 × 27 = 2,187, a 6.75× saving. Finally retrain the winner for the full budget when you need the absolute best model: 243 + 9 = 252 epochs, still 2.9× under budget.

  3. Two candidate points come out of a surrogate with best-so-far 0.7: A has μ = 0.8, σ = 0.25; B has μ = 0.6, σ = 0.6. Compute Expected Improvement for each (ξ = 0) and say which one EI evaluates next. Then follow the lesson's actual Bayesian lab for six steps and describe the pattern.
    Show one worked answer

    For A: z = (0.8 − 0.7)/0.25 = 0.4, Φ(0.4) = 0.6554, φ(0.4) = 0.3683, so EI = 0.1 × 0.6554 + 0.25 × 0.3683 = 0.0655 + 0.0921 = 0.1576. For B: z = (0.6 − 0.7)/0.6 = −0.1667, Φ = 0.4338, φ = 0.3934, so EI = −0.1 × 0.4338 + 0.6 × 0.3934 = 0.1927. B wins despite the lower mean: its uncertainty is the opportunity. UCB with κ = 2 agrees (A: 0.8 + 0.5 = 1.30, B: 0.6 + 1.2 = 1.80). In the lab, after four starting points the best is 0.9218 at x = 0.55; EI at that high-mean point is only 0.015, while the untouched edge x = 1.0 has EI = 0.097 — so step 1 explores the edge (score 0.5033). Step 2 lands at x = 0.653 (0.9812), step 3 at x = 0.633 (0.9970), and by step 6 the best is 0.9989 — the surrogate is now refining around the peak. Exploration first, exploitation after.

  4. A team grids 6 hyperparameters with 5 values each, 5-fold CV, 200 epochs per fit, at 1.5 seconds per epoch. Compute the full bill. Then design a plan under 6 hours and show the arithmetic.
    Show one worked answer

    Full bill: 5⁶ = 15,625 configurations × 5 folds = 78,125 fits; × 200 epochs = 15,625,000 epoch-fits; × 1.5 s = 23,437,500 seconds = 6,510 hours ≈ 271 days. Under-6-hour plan: fix the four least important knobs at defaults, keep learning rate plus n_estimators, and run 40 random trials with patience-based early stopping. 40 trials × 5 folds = 200 fits; average 60 epochs per fit (bad runs die earlier) = 12,000 epoch-fits; × 1.5 s = 18,000 seconds = 5.0 hours. Spend the last hour on a 20-trial Bayesian refinement inside the narrowed range, and reserve the test set for a single final report.

Terms this lesson borrows from later lessons (or outside)

You do not need to master these here. Each one gets a proper treatment in its own lesson; the one-line meaning is enough to keep reading. Orange dotted underlines in the prose point back to this list.

  • Bayes' theoremposterior ∝ prior × likelihood: update a belief with evidence. Bayesian optimization is this idea applied to functions — the surrogate is a posterior over what the score could be. (Phase 1, Lesson 07)
  • expected valueThe probability-weighted average of a random outcome. Expected Improvement is literally the expected value of max(0, new score − best score). (Phase 1, Lesson 06)
  • learning rateThe step size of each gradient update. It is almost always the single most important hyperparameter, and it should be searched on a log scale, not a linear one. (Phase 1, Lesson 08)
  • overfittingFitting patterns that do not generalize. Run enough hyperparameter trials and you start overfitting the validation set the same way a model overfits training data. (Phase 2, Lesson 01)
  • train / validation / test splitFit on train, choose on validation, report on test. Hyperparameter tuning must consume only the validation part; the test part is touched exactly once. (Phase 2, Lesson 01)
  • cross-validationRotate the validation fold through k disjoint pieces of the training data so every row is validated once. Tuning with CV multiplies the cost by k — and nested CV wraps another loop around it. (Phase 2, Lesson 01)
  • regularizationAdding a penalty such as λ·Σw² to the loss so weights stay small. Its strength λ is a hyperparameter with no obvious default, which is why the nested-CV lab tunes exactly this. (Phase 2, Lesson 03)
  • gradient boostingAn ensemble that fits trees to the residuals of the previous trees. Six of its knobs — learning rate, trees, depth, min samples, subsample, column sample — are the source lesson's opening example. (Phase 2, Lesson 11)
KEEP GOING

A picture is a start.
Practice is the rest.

This lesson is a port of an open course. Everything here traces back to it — and the next step is running the code yourself.

Lesson text adapted from AI Engineering from Scratch (Phase 02, Lesson 12) and the Math Foundations Notebook reference build. Interactive figures, the six labs, the response surface shared by the hero and labs, the worked EI and Hyperband numbers, and the worked exercise answers are original to this page. Every score a lab prints is computed live from the surface or table it displays.