Model Selection
How to choose a model that works tomorrow, not just today. The bias–variance decomposition, honest error estimation with cross-validation, the curse of dimensionality and three ways to fight it, analytical criteria (AIC/BIC), and the ensembles — bagging and boosting — that bend the trade-off.
01 · Motivation
Why does this matter?
Chapter 02 taught you how to fit a model to a dataset. The question that decides whether your work is worth anything is the next one: does it also work on data it has never seen? A degree-9 polynomial can pass through all ten of your training points and be useless on the eleventh.
Choosing among candidate models, complexities, and regularisation strengths so the chosen one generalises is the whole job of this chapter. Three uncomfortable realities motivate the machinery that follows.
Training error lies
The number you minimise during training is the model’s score on data it has already memorised — an optimistically biased estimate of fresh-data behaviour. The bigger the model, the bigger the lie.
No model wins everywhere
The No Free Lunch theorem says: averaged over all conceivable problems, every learner has the same accuracy. The “best” model is a property of the problem, not the algorithm.
The trade-off is irreducible
Test error splits into bias (wrong on average), variance (jittery sample to sample), and noise (inherent randomness). The first two fight; the third never goes away.
The model-selection problem in one sentence
Among many models you could fit — different complexities, feature subsets, regularisation strengths — pick the one whose expected error on unseen data is lowest. Since you don’t have unseen data while choosing, you need honest estimates of that quantity. That is what cross-validation, AIC/BIC, and held-out sets are for.
The No Free Lunch theorem
Before obsessing over the perfect model, a sobering result: we are not shopping for a universal winner.
Averaged uniformly over all target functions , every learner is equally (un)accurate. If beats on some problems, there must be others where beats .
The proof is a one-line counting argument: for every target where the learner beats chance on the unseen points by margin , there is a mirror target that agrees with on the training data and disagrees on every unseen point — so the learner is beaten by the same . The pair cancels.
What NFL really tells you (and what it doesn't)
NFL does not say all algorithms are equally good on the problems you actually care about. Real problems are smooth, low-dimensional, structured — far from random. NFL just kills the dream of a one-algorithm-fits-all winner, and justifies a healthy habit: try several models, compare them honestly, let the data decide.
02 · Intuition
The idea in plain language
Forget formulas for a moment. The whole chapter rests on one image: throwing darts at a bullseye.
The true answer for a test input is the centre of the target. Every time you draw a fresh training set and refit, you throw one dart — the model’s prediction. Over many resamples you accumulate a constellation, and two things describe it:
- How far the average dart lands from the centre — the systematic miss. That is bias. A simple model (a line fitting a curve) has high bias: more data won’t help it reach the truth on average.
- How spread out the darts are around their own average — the jitter. That is variance. A flexible model (degree-15 on 10 points) has high variance: each new training set flings it somewhere new.
The decomposition in one breath
Expected test error bias² variance noise. Three non-negative terms. Noise is fixed by the problem — you can’t fight it. Bias and variance are yours to control: simpler models lower variance but raise bias; more flexible models do the reverse. Picking a model is finding the bottom of their sum.
The U-curve of generalisation
Put model complexity (polynomial degree, number of features, tree depth) on the horizontal axis and error on the vertical. Bias² falls as complexity grows; variance rises; their sum plus noise is a U. On the left the model underfits (bias dominates); on the right it overfits (variance dominates); the sweet spot is in the middle.
Training error is not on this graph
Training error falls monotonically as complexity grows — degree-9 through 10 points hits exactly zero. That number is useless for picking a model. The U-curve is the test error: the thing you care about, and the thing you must estimate without peeking at the test set.
The curse of dimensionality
As you add features, the input space’s volume grows exponentially. To densely cover even a fraction of a -dimensional cube you need on the order of points — real datasets never come close. The geometry turns hostile:
Sparsity
Even with millions of samples, a 100-D space is mostly empty. Every test point sits in a region the training set never visited.
Distance concentration
In high dimensions, all pairs of points end up roughly equidistant. “Nearest neighbour” stops meaning anything.
Variance explosion
More features ⇒ more parameters ⇒ more sample-noise fitted ⇒ higher variance. Adding a useless feature can strictly worsen generalisation unless you regularise.
'If a model doesn't work, add more features'
The intuitive move is often exactly wrong. The curse says: drop features, project to a lower dimension, or regularise. More features only help when they carry signal and the sample size scales with them — otherwise you are just buying variance.
The curse is why every technique below exists. Feature selection, regularisation, and dimensionality reduction all say the same thing: trade a little representational power for a lot of statistical stability. And a fourth family — ensembles — bends the curve down instead of sliding along it.
03 · Formalism
Definitions and equations
- f
- the true (unknown) function generating targets.
- t
- the observed target , with , .
- D
- a training set of i.i.d. samples from .
- yD
- the model fitted on , evaluated at : .
- ȳ
- the average model — what you’d predict averaging over infinitely many training sets.
The bias–variance decomposition
Compute the expected squared error at a single test point and watch three terms emerge.
1 · Split the target
With ,
2 · Expand around the mean model
Add and subtract inside the bracket:
3 · Cross terms vanish
is mean-zero and independent of , and by definition of . So all three cross terms have zero expectation, leaving
How to talk about each term in an oral
- Bias — the gap between the truth and the model’s expected prediction. Driven by a hypothesis class that is too small/rigid. Falls as the model gets richer.
- Variance — the average squared distance between a single fit and the expected fit. Driven by sensitivity to the sample. Falls with more data, a smaller class, or regularisation.
- Noise — , the irreducible floor. No model drives it below zero.
Integrated over the input distribution you get the same three terms weighted by where the data lives — recognise both the pointwise and integral forms.
Estimating prediction error honestly
The decomposition is theoretical — you can’t compute it without knowing . What you can do is estimate total error from data. Training error is optimistically biased and always falls with complexity — useless alone. The true error is what you want; the rest of this section replaces that integral with something computable.
Training set
Fits each candidate’s parameters by minimising the training loss.
Validation set
Picks among candidates — , polynomial degree, feature subset. Tunes hyperparameters.
Test set
Locked in a vault. Touched once, at the very end, for a final unbiased number. Peek and it stops being unbiased — no exceptions.
The cardinal sin of ML
Using the test set in any way during model selection — peeking, tuning, “one quick check” — taints it. The number it then produces is optimistically biased. The honest fix is brutal: set that test set aside as compromised and find a fresh one.
Cross-validation fixes the wastefulness of a single split. Partition the training pool into equal folds; for each fold , fit on the other and score on fold ; average:
Every example validates exactly once and trains in folds. Slightly pessimistic (each fit sees samples) but far lower variance than one split. Defaults: ; when fits are costly; (leave-one-out) for tiny data — almost unbiased but slow and high-variance.
Analytical alternatives: , AIC, BIC, adjusted
CV refits times. For huge data or slow models, analytical penalties add a complexity term to the training error and pick the smallest penalised score (largest, for adjusted ):
| Criterion | Formula | Notes |
|---|---|---|
| Mallows’ | penalty #params , calibrated by noise. Small is good. | |
| AIC | KL distance to the truth (up to constants); under Gaussian noise. | |
| BIC | penalty grows with — punishes complexity harder, prefers smaller models. | |
| Adjusted | can decrease when a useless feature is added. Large is good. |
AIC vs BIC — when to use which
AIC is consistent for prediction — asymptotically picks the lowest-prediction-error model even if the truth isn’t in your candidate set. BIC is consistent for identification — if the true model is in the set, BIC finds it with probability as . Rule of thumb: predict → AIC, infer → BIC. On borderline cases BIC prefers the simpler model.
Three capacity-control families
Feature selection
Discard features. Filter — rank each feature offline (correlation, mutual information, F-test), keep the top ; fast but blind to interactions. Wrapper — search subsets by refitting the learner (forward stepwise, backward elimination); honours the real loss, costly. Embedded — selection happens inside the fit (lasso’s zeros weights; trees skip unused features).
Regularisation
Keep all features, shrink their weights. Ridge () shrinks smoothly, closed-form, keeps all features. Lasso () drives some weights to exactly zero (embedded selection), no closed form. The strength is itself a hyperparameter — tune it on a log grid with CV, then refit.
Dimensionality reduction
Build new features that summarise the space. PCA projects onto the directions of maximum variance. Unlike feature selection it mixes features rather than dropping them.
The 'select best by training RSS' trap
Within a fixed size , comparing subsets by training RSS is fine — same complexity, same bias. But comparing across sizes by training RSS always picks the biggest model. Across sizes you must use CV, , AIC, BIC, or held-out error.
Optional depth PCA in five steps, and four ways it can mislead you
- Centre: — non-negotiable; PCA finds directions through the centroid.
- Covariance: .
- Diagonalise: . The eigenvector with the largest eigenvalue is PC1 — the direction of maximum variance; the next-largest orthogonal one is PC2, and so on.
- Project: with ; component captures a fraction of the variance. Pick at the elbow of the cumulative-variance plot (e.g. 90–95%).
- Reconstruct (optional): . Lossy by — which is how PCA denoises: throwing away small-eigenvalue directions throws away noise.
Four failure modes: (i) variance ≠ predictive signal — a low-variance but relevant feature gets discarded (consider LDA, or CV the choice of ); (ii) multiple clusters — the principal axis runs between clusters, hiding the most informative dimension; (iii) nonlinear manifolds — linear projection collapses a Swiss roll wrongly (use kernel PCA, ISOMAP, autoencoders); (iv) cost — diagonalising is ; use truncated SVD on directly above .
Ensembles: bending the trade-off
Every technique so far slides the dial between bias and variance. Ensembles combine many models so the combined error beats any component’s.
Bagging — variance through averaging. If are i.i.d. with variance , then — averaging cuts variance by without changing the mean. Refits of the same model on the same data are perfectly correlated, not independent, so bagging manufactures approximate independence by bootstrap resampling: draw samples (with replacement, size ), fit one model each, and average (or majority-vote):
Bias ≈ that of one base model; variance much lower. Shines for unstable base learners — deep trees, neural nets — where small data perturbations cause wildly different fits.
Boosting — sequential bias reduction. Train learners sequentially, each focusing on what its predecessors got wrong; combine by weighted vote. The classic is AdaBoost:
1 · Initialise
for every example. Repeat steps 2–5 for .
2 · Fit and score
Normalise , train weak learner on the weighted data, compute the weighted error . If , stop — no longer better than chance.
3 · Confidence
Smaller (larger ) means a more reliable learner. Both notations appear in exams.
4 · Re-weight
— correctly classified examples are multiplied by (down-weighted); misclassified ones keep their weight (relatively up-weighted).
5 · Renormalise and repeat
Rescale the weights to sum to one, then continue with round .
Signed form for binary ; arg-max form (slide notation) for multi-class. Schapire’s theorem: training error decays as — exponentially in when each learner has a bounded edge.
| Bagging | Boosting | |
|---|---|---|
| Targets | variance | bias (and some variance) |
| Training | parallel | sequential |
| Best base learner | high-variance, low-bias (deep trees) | weak, high-bias (stumps) |
| Sample weighting | equal, bootstrap | up-weight errors |
| Combination | average / majority vote | weighted vote () |
| Noise sensitivity | robust | fragile — can overfit noisy labels |
04 · Worked example
Bias, variance, and k-fold CV by hand
Part A · Bias and variance of two learners
The truth is , evaluated at the test point , with noise variance . Training sets have points at . Compare Learner A (predicts the mean of the training targets, ignoring ) and Learner B (OLS line).
1 · Learner A — expected prediction
The training mean is , so .
2 · Learner A — bias², variance, total
Bias² (large — too simple). Variance comes only from : . Total , dominated by bias.
3 · Learner B — expected prediction
OLS recovers the truth in expectation: , , so .
4 · Learner B — bias², variance, total
Bias² . Propagating noise through the OLS variance formula, . Total , dominated by noise.
| Learner | Bias² | Variance | Noise | Total |
|---|---|---|---|---|
| A (constant) | 0.250 | 0.010 | 0.040 | 0.300 |
| B (linear, OLS) | 0.000 | 0.018 | 0.040 | 0.058 |
Learner A has lower variance but loses by a factor of five on bias. A degree-10 “Learner C” would show the mirror: zero bias, comically large variance. Model selection keeps both small.
Part B · 4-fold CV on 12 points
Twelve points, four candidate degrees, (3 examples per fold). For each candidate: split into folds , fit on the other nine, score on the held-out three, average the four MSEs, and pick the smallest .
| Model | Fold 1 | Fold 2 | Fold 3 | Fold 4 | |
|---|---|---|---|---|---|
| Degree 1 | 0.180 | 0.155 | 0.171 | 0.166 | 0.168 |
| Degree 2 | 0.062 | 0.058 | 0.071 | 0.067 | 0.0645 |
| Degree 3 | 0.041 | 0.038 | 0.052 | 0.047 | 0.0445 |
| Degree 4 | 0.044 | 0.043 | 0.061 | 0.058 | 0.0515 |
A clean U: degree 1 underfits, degree 3 is the sweet spot, degree 4 begins to overfit. Pick degree 3, then refit on all 12 points for the final model — and only then touch the test set, once.
Don't average the chosen parameter values
CV gives you a chosen hyperparameter (degree 3), not a final model — the four fold-fits have different coefficients. Refit the chosen-degree model on the entire training pool. Averaging the fold coefficients throws away of your data and is simply wrong.
05 · Visual explanation
The pictures that make it click
The validation protocol
The discipline drawn out: the test set sits in its vault until the very end, and the loop inside the validation phase is where all the CV work happens.
k-fold CV in motion
For : each row is one iteration, the amber tile is that iteration’s validation fold, grey tiles are training. Every fold is amber exactly once.
PCA geometry
The cloud is elongated along an axis that has nothing to do with the original coordinates. PCA finds that axis (PC1), the orthogonal one (PC2), and lets you project onto PC1 — discarding PC2 with minimal loss because the data barely varies there. (Provided “what matters” is variance — the caveat from §3.) Both components are drawn from the centroid , which is why PCA is run on centred data.
06 · Hands-on
Try it yourself
Four labs, each making one idea click by letting you push it around. Push the controls, watch the numbers, then read the takeaway.
The bias–variance dartboard
Each Resample draws a fresh training set, refits the chosen model, and plots its prediction at the test point x = 0.6 as one dart. The gold centre line is the truth. Build the constellation, then read how bias (cloud offset) and variance (cloud spread) trade off.
Find the bottom of the U-curve
Polynomial regression on a noisy sine. Slide the degree and watch the fit (left), the train and test error across all degrees (right), and the regime verdict. Add training points to see how more data shifts the sweet spot.
Walk through k-fold cross-validation
Choose k and step through the folds. Each step turns one fold amber (held out for scoring), refits the polynomial on the grey folds, and records its validation MSE. After all k steps, the averaged CV score is your estimate of test error.
Single tree vs bagging vs boosting
Three predictors on the same noisy task: a single shallow stump, a bag of B stumps on bootstrap samples, and a boosted sequence of B rounds. Grow B and watch bagging smooth the noise while boosting builds detail.
07 · Exam intel
What the exam actually tests
Model selection is short on novel formulas and long on conceptual fluency. Five question shapes recur.
Derive the bias–variance decomposition
Start from , add and subtract , expand the square, and argue all cross-terms vanish ( mean-zero and independent; mean-zero by definition). End with . Bonus: name the irreducible term (noise) and the two you control.
Compare the validation strategies
| Method | Bias of estimate | Variance | Cost |
|---|---|---|---|
| Hold-out | moderate (small train) | high (one split) | 1 fit |
| -fold () | small | low | fits |
| Leave-one-out | almost zero | high | fits |
“Use LOO because it’s unbiased” loses marks unless you also flag its high variance and -fit cost.
State No Free Lunch and its consequence
Averaged over all targets, every learner has accuracy . One-sentence proof: for any beaten by the learner by , a mirror (agreeing on train, disagreeing on test) beats it by ; the pair cancels. Consequence: no universal best model — selection is a matching problem between inductive bias and problem structure.
Bagging vs boosting — when does each help?
Bagging reduces variance — use with high-variance/low-bias bases (deep trees, nets); useless on already-stable biased learners; robust to noisy labels. Boosting reduces bias — use with weak, high-bias bases (stumps); sensitive to label noise (errors gain weight); sequential, so not parallelisable. Random forests = bagging trees with feature subsampling; gradient boosting = boosting generalised to any differentiable loss.
Memorise five identities and you have the chapter
- Bias–variance: .
- -fold CV: .
- AIC ; BIC (penalises harder).
- PCA: eigenvectors of ; variance of component is .
- AdaBoost confidence: .
08 · Common mistakes
Where students get this wrong
Tuning on the test set
The most common (and career-ending) ML mistake. “I’ll just try a few and keep the best test accuracy” turns the test set into a validation set; the final number is optimistic by an unknown amount. Physically separate the test set from the tuning loop — once tuned on, it is burned.
Random k-fold on time-series data
Random folds assume exchangeable samples. Time series aren’t — tomorrow depends on today. Random permutation lets the model “see the future” during training and wildly over-estimates generalisation. Use forward-chaining CV: fold trains on and validates on . Same caveat for spatially autocorrelated data.
Reporting plain R² as a selection metric
Plain increases monotonically as you add features — by construction a training-set quantity. Use adjusted , , AIC, BIC, or out-of-sample error. Forgetting “adjusted” is the classic slip when comparing nested linear models.
'PCA is a feature-selection method'
It isn’t. PCA replaces features with linear combinations of all of them — each component is a weighted sum across every input. You don’t drop features, you mix them. Lasso, forward stepwise, and best-subset are what return an actual subset.
Doing PCA (or scaling) before the split
Principal components — and feature means/standard deviations — must be learned on the training data only, then applied to the test set. Fitting them on the whole dataset lets test samples influence the very axes they’re projected onto: a subtle but real leak.
'Adding more features can only help'
False. More features enlarge the hypothesis space — lower bias, higher variance — and if they carry no signal you’ve bought variance for nothing. Adding random noise columns reliably degrades an unregularised model. That is the curse of dimensionality in one sentence.
Confusing bagging with boosting
Both vote, and that’s where the similarity ends. Bagging fits in parallel, models independent, targets variance, tolerates noise. Boosting fits in sequence, each model depends on the previous one’s errors, targets bias, is fragile to noise. Mixing them up is the fastest way to lose marks here.
Assuming AIC and BIC always agree
They are almost never equal and often disagree on borderline models — and consistently, BIC prefers the simpler model because its penalty grows with sample size. If asked to compute both, expect disagreement and explain which you’d trust (predict → AIC, infer → BIC).
09 · Self-check
Can you answer these?
Four questions in the style the chapter likes to be tested. Click an option for instant feedback.
You fit a degree-9 polynomial on 10 points and get training MSE = 0. What do you also know?
Your bias² is 0.10, variance is 0.30, and noise variance is 0.05. Which intervention is most promising?
You used 10-fold CV to pick λ for ridge. Once λ* is chosen, what is the correct next step?
Your base learner is a decision stump (depth-1 tree): high bias, very low variance. Which ensemble helps most?
10 · Recap
One-screen summary
Chapter 04 — load-bearing ideas
- No Free Lunch. Averaged over all problems, every learner ties. Model selection matches the model’s inductive bias to the problem’s structure — not a search for a universal winner.
- Bias–variance decomposition. ; three non-negative terms, the first two trading off with complexity, the third the irreducible floor.
- The U-curve. Training error falls monotonically; test error dips then climbs. Selection finds the bottom of the U — and you must estimate it without peeking at the test set.
- Train / validation / test. Train fits parameters, validation tunes hyperparameters, test reports once. -fold CV replaces a single split with rotating ones, averaging out split noise.
- Analytical criteria. , AIC (), BIC (), adjusted . BIC penalises harder; AIC for prediction, BIC for identification.
- Curse of dimensionality. Volume explodes in ; sparsity, distance concentration, and variance explosion degrade performance unless scales. Signal-free features make it worse.
- Three capacity knobs. Feature selection (filter / wrapper / embedded), regularisation (ridge / lasso), dimensionality reduction (PCA) — all slide along the U-curve.
- Bagging = variance killer. Bootstrap, fit independent models, average; best with high-variance bases. Variance scales like for independent fits.
- Boosting = bias killer. Sequential weak learners on re-weighted data. AdaBoost: , update , vote . Best with high-bias bases; fragile to label noise.
Looking ahead → Chapter 05
We’ve measured generalisation empirically. Next we ask whether it can be guaranteed in theory — PAC learning, hypothesis-space complexity, and the VC dimension that bounds how much data a model class needs.