Semester 1 · Week 13
Hyperparameter optimisation and regularisation
- Ch 17 Hyperparameter Optimisation
- Ch 18 Regularisation
Chapter 17: Hyperparameter optimisation
A search you can evaluate but can't differentiate.
Notes · slide 2
Time: 50 minutes for two chapters. About 20 on Chapter 17, 25 on Chapter 18, and 5 to check understanding.
Say: Every algorithm has dials set before training: how many trees, how deep, how fast to learn. A well-tuned ordinary algorithm can beat a badly tuned state-of-the-art one.
Key line: you can evaluate a setting, but there's no derivative of validation score with respect to tree count. So we search.
Next: parameters and hyperparameters.
Parameters and hyperparameters
- Parameters are learned during training: weights, split thresholds.
- Hyperparameters are set before training: learning rate,
n_estimators,max_depth. - They can't be solved for. They have to be searched.
- Every candidate costs a full train and validate.
Notes · slide 3
Say: Parameters are learned during training: weights, split points. Hyperparameters are set before: learning rate, number of trees, depth. Gradient descent can't reach them. You have to search.
Say: Every candidate means a full train and validate, usually several with cross-validation. That's the constraint everything else works around.
Ask: "Is the number of neighbours in KNN a parameter or a hyperparameter?" Listen for: hyperparameter.
Next: the obvious search.
Grid search
- Try every combination on a grid.
- 5 values for 4 hyperparameters: 54=625 runs.
- Add a fifth: 3,125.
The curse of dimensionality, applied to tuning.
Notes · slide 4
Say: Try every combination. Five values for four hyperparameters is 625 runs. A fifth hyperparameter makes it 3,125.
Key line: it's the curse of dimensionality again, this time in the tuning space.
Say: Grid search is only practical for about three hyperparameters or fewer, with a fast model.
Next: why random beats it.
Why random search wins
- In most problems, a few hyperparameters matter and most barely do.
- A grid spends trials covering the ones that don't matter.
- Random search tries a new value of every hyperparameter on every trial.
Same budget, more distinct values of the ones that count (Bergstra and Bengio, 2012).
Notes · slide 5
Do: draw a 3×3 grid on two axes, one important and one not. Point out that the nine trials test only three values of the important one. Then scatter nine random points: nine different values.
Say: In most problems a few hyperparameters matter and most barely do. A grid spends its budget covering the ones that don't. Random search tries a fresh value of every hyperparameter on every trial. Bergstra and Bengio showed this in 2012.
Key line: same budget, more distinct values of the hyperparameters that count.
Next: searching with a memory.
Bayesian optimisation
- Build a cheap model of score versus hyperparameters from past trials.
- Use it to pick the next most promising trial.
- Optuna's TPE sampler does this, and can prune bad trials early.
Worth it when each trial is expensive.
Notes · slide 6
Say: Grid and random search ignore what earlier trials found. Bayesian optimisation fits a quick stand-in model of score against settings, then picks the next trial where it expects to gain most. It balances trying near the best so far against exploring where it's unsure.
Say: Optuna uses a method called TPE, and can stop bad trials early. That pruning can be added to random search too.
Key line: worth it when each trial is expensive.
Next: a trap during tuning.
The validation set is sacred
- During tuning, the validation score is part of the search.
- The best score after tuning is biased upward. You picked the winner on it.
- Report the final number from an untouched test set, or nested CV.
Notes · slide 7
Say: During tuning, the validation score picks the winner. So the best score after tuning is biased upward. You chose it because it scored well on those rows.
Say: This is week 10's lesson again. Report the final number from an untouched test set, or from nested cross-validation.
Ask: "Your tuned CV score is 0.93, test is 0.90. Broken?" Listen for: no. Tuned scores are optimistic.
Next: which strategy when.
Which strategy?
| Strategy | Use when |
|---|---|
| Grid | Up to ~3 hyperparameters, fast model |
| Random | Most situations. The default |
| Bayesian (Optuna) | Expensive trials, many hyperparameters |
Search learning rates and C on a log scale.
Notes · slide 8
Say: Grid for up to about three hyperparameters on a fast model. Random for most situations: the default. Bayesian with Optuna when trials are expensive or there are many hyperparameters.
Say: Search learning rates and regularisation strength on a log scale. The difference between 0.001 and 0.01 matters as much as between 0.1 and 1.
Next: the worked example.
Worked example: three searches, same budget
Six XGBoost hyperparameters, 64 trials each, on noisy, overlapping data.
| Strategy | CV AUC | Test AUC | Wall time |
|---|---|---|---|
| Grid | 0.9185 | 0.8933 | 55.5 s |
| Random | 0.9198 | 0.8942 | 18.5 s |
| Optuna (TPE) | 0.9225 | 0.8949 | 171.5 s |
Notes · slide 9
Say: Six XGBoost hyperparameters, 64 trials each, on noisy, overlapping data built to overfit. Grid has room for only two values per hyperparameter: 2⁶ = 64.
Say: Random beats grid on CV and test. Optuna does best on both. But look at wall time: Optuna took 171.5 seconds against random's 18.5.
Ask: "So is Optuna the slow choice?" Let them commit before the next slide.
Next: what the numbers mean.
Worked example: what the numbers mean
- With two values per dimension, every grid point is a corner. It never tries the interior.
- Optuna's wall time is mostly lost parallelism: each trial waits for the one before.
- Optuna matched random search's final score after 5 trials, in 5.7 seconds.
Its advantage is fewer evaluations, not faster ones.
Notes · slide 10
Say: With two values per dimension, every grid trial sits at a corner. It never tries a middle value, where the best setting often is.
Say: Optuna's wall time is mostly lost parallelism. Each trial waits for the ones before it. Grid and random ran all their fits at once.
Key line: Optuna matched random search's final score after 5 trials, in 5.7 seconds. Its advantage is fewer trials, not faster ones.
Lab: this surprises people. Learners plot best score against trial number. Point at where each line flattens.
Next: the chapter in one idea.
Mental model
Tuning is wine tasting without tasting every bottle.
- Grid works through the menu in order.
- Random grabs bottles at random.
- Bayesian asks the sommelier, based on what you liked.
The sommelier helps when the menu is long and each tasting is expensive.
Notes · slide 11
Say: Tuning is wine tasting without tasting every bottle. Grid works through the menu in order. Random grabs bottles at random. Bayesian asks the sommelier, based on what you liked so far.
Key line: the sommelier helps when the menu is long and each tasting is expensive.
Next: Chapter 18, regularisation.
Chapter 18: Regularisation
Among models that fit equally well, prefer the simpler one.
Notes · slide 12
Time: about 25 minutes for this chapter.
Say: 98% on training data, 72% on test. A textbook overfit. The model learned the noise. Regularisation is the main tool against it.
Key line: among models that fit equally well, prefer the simpler one.
Next: constraining the memorising.
Constrain the memorising
- With enough freedom, a model memorises any training set.
- More data helps, but often isn't available.
- Regularisation adds a cost for complexity to the objective.
- Penalties, dropout, depth limits, and early stopping are all forms of it.
It trades a little more bias for a lot less variance.
Notes · slide 13
Say: Give a model enough freedom and it memorises any training set. More data helps, but often you can't get it. So you limit how much it's allowed to memorise.
Say: Regularisation adds a cost for complexity to what the model minimises. Penalties on weights, dropout, depth limits, and early stopping all do this.
Key line: it trades a little more bias for a lot less variance. Week 8's trade-off, now with a dial.
Next: how to tell which side you're on.
Learning curves
Train on growing subsets. Plot training and validation error.
| Pattern | Diagnosis | Action |
|---|---|---|
| Both high, close together | High bias | More capacity, less regularisation |
| Large gap between them | High variance | Regularise, or get more data |
| Both low, close together | Good fit | Stop |
Notes · slide 14
Say: Train on growing subsets. At each size, record training and validation error. Plot both against size.
Say: Both high and close together: high bias. The model is too simple, and more data won't help. A big gap: high variance. Regularise, or get more data. Both low and close: stop.
Say: This isn't the loss curve from week 3. That plots error against epochs. This plots error against data size, and asks whether more data would help.
Next: two real curves.
Reading learning curves

Left: both errors high and close, so high bias. Right: a wide gap, so high variance.
Notes · slide 15
Do: ask for the diagnosis in words before you reveal it. Learning curves are often misread.
Say: Left, linear regression on a sine curve. Training and validation error meet early, both around 2.2, and stay there. High bias. Right, an unconstrained tree. Training error is zero. Validation levels off near 0.75. The gap never closes. High variance.
Ask: "What would you change for each?" Listen for: a more flexible model on the left, regularisation or more data on the right.
Next: the first penalty.
Ridge (L2)
Lossridge=Loss(y,y^)+α∑wi2
- Shrinks every weight towards zero.
- Keeps every feature.
- Right when most features help but are noisy.
Notes · slide 16
Say: Ridge adds the sum of squared weights to the loss. α sets how strong the penalty is. Every weight shrinks towards zero, but none reaches it.
Key line: Ridge keeps every feature. It suits data where most features help but are noisy.
Next: a penalty that removes features.
Lasso (L1)
Losslasso=Loss(y,y^)+α∑∣wi∣
- The L1 constraint region has corners on the axes.
- Solutions land on corners, so some weights become exactly zero.
- Built-in feature selection.
Notes · slide 17
Do: draw a diamond and a circle centred on the origin, with elliptical error contours touching each. The ellipse touches the diamond at a corner, on an axis. That's a zero weight.
Say: Lasso adds the sum of absolute weights. Its constraint region has corners on the axes, so solutions often land there, and some weights become exactly zero.
Key line: Lasso selects features as it fits. Ridge can't.
Next: combining the two.
Elastic net
α(ρ∑∣wi∣+21(1−ρ)∑wi2)
- Lasso's sparsity, with Ridge's handling of correlated features.
- Lasso picks one of a correlated group almost arbitrarily. Elastic net shares weight across the group.
Notes · slide 18
Say: Elastic net mixes both penalties. ρ sets the mix. It keeps Lasso's sparsity and handles correlated features better.
Say: Give Lasso three correlated features and it tends to keep one almost at random and zero the others. Elastic net tends to keep or drop the group together.
Say: One trap. sklearn scales the fit term differently for Lasso and Elastic Net than for Ridge, so the same α means different strengths. Always tune α by cross-validation.
Next: regularisation beyond linear models.
Beyond linear models
- Dropout: randomly zero neurons during training, so none can rely on a fixed partner.
- Early stopping: stop when validation loss stops improving for a set patience.
- Trees: limit depth, require minimum samples per leaf.
- Probabilistic view: L2 is a Gaussian prior on the weights, L1 a Laplace prior.
Notes · slide 19
Say: Dropout randomly switches off neurons during training, so none can lean on a fixed partner. Early stopping halts when validation loss stops improving for a set patience. Trees: limit depth, require a minimum number of samples per leaf.
Say: There's also a probabilistic reading. L2 is like assuming weights come from a bell curve around zero. L1 is like assuming a sharper peak at zero.
Next: the worked example.
Worked example: a degree-15 polynomial
60 noisy points from a simple quadratic.
| Model | Train RMSE | Test RMSE |
|---|---|---|
| No regularisation | 1.412 | 1.912 |
| Ridge (α=2.48) | 1.819 | 1.461 |
| Lasso (α=0.076) | 1.793 | 1.455 |
Lasso also zeroes 11 of the 15 coefficients.
Notes · slide 20
Say: 60 noisy points from a simple quadratic, fitted with a degree-15 polynomial. Unregularised: training RMSE 1.412, test 1.912. It overfits.
Say: Ridge and Lasso, with α chosen by cross-validation, both bring test RMSE down to about 1.46. Lasso also zeroes 11 of the 15 coefficients.
Ask: "Lasso kept 4 terms. Should it have found exactly x and x²?" Listen for: not necessarily. It found a smaller model that generalises, not the true formula.
Next: what changed.
Worked example: what changed
- Both regularised models fit the training data worse.
- Both predict the test data better.
- Ridge even scores better on test than on train.
A deliberate increase in bias, for a bigger cut in variance.
Notes · slide 21
Say: Both regularised models fit the training data worse. Both predict the test data better. Ridge even scores better on test than on train.
Key line: a deliberate increase in bias for a bigger cut in variance. That's the whole idea of regularisation in one table.
Next: the chapter in one idea.
Mental model
Regularisation is Occam's razor with a dial.
- α sets how strongly simplicity beats fit.
- Too low: the model memorises noise.
- Too high: it can't see the signal.
Notes · slide 22
Say: Regularisation is Occam's razor with a dial. α sets how strongly simplicity beats fit. Too low and the model memorises noise. Too high and it can't see the signal. Cross-validation finds the setting.
Next: check yourself.
Check yourself
- Why does a coarse grid miss good hyperparameters?
- Your tuned CV score is 0.93 and the test score 0.90. Is something broken?
- You expect only a handful of 200 features to matter. Ridge or Lasso?
- Training and validation error are both high and close. Regularise more or less?
Notes · slide 23
Do: pairs, three minutes, then take answers.
Answers: 1. It only samples the points on the grid, often the corners. It never tries the values in between. 2. No. Tuned CV scores are optimistic. 3. Lasso. 4. Less. The model is underfitting.
This week
- Read Chapter 17: Hyperparameter Optimisation.
- Read Chapter 18: Regularisation.
- Take the Chapter 17 quiz.
- Take the Chapter 18 quiz.
- Run the notebooks: Chapter 17 (opens in a new tab),Chapter 18 (opens in a new tab).
- Optional: the further reading for week 13.
Slide 1 of 24: Hyperparameter optimisation and regularisation
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.