Cross-validation and model comparison

k-fold, LOOCV, choosing hyperparameters

7 lessons · 13 past questions · 42 marks in the papers collected here

Open the interactive lessons →Cross-validation and model comparison past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Orientation: what you will learn and why
  2. Big picture: concept map, comparison table and the recipe
  3. Start here: a line through points
  4. Reading training and validation errors; choosing a hyperparameter
  5. How k-fold cross-validation works: counting models and sizes
  6. Leave-one-out cross-validation for a line
  7. Model comparison: zero training error, geometry and true/false facts

1. Orientation: what you will learn and why

A model that fits its own training data perfectly may still fail on new data. To choose settings (like $\lambda$, $k$ or tree depth) honestly we must test on data the model did not train on. Cross-validation does this by repeatedly holding out part of the data. This topic also collects the "which model can do what" questions that appear in many papers.

What you will be able to do

Why this topic matters for Quiz 2

Counted only from the PYQs in this project (not a prediction):

What the PYQs askPYQsMarks
Choosing hyperparameters from error tables26
k-fold cross-validation: counts23
LOOCV for a line312
Zero training error26
Model comparison: true/false facts and geometry415

In total 13 PYQs worth 42 marks across 6 papers (5 MCQ, 4 MSQ, 4 numeric).

How this topic connects

It uses the line fit from the Linear regression topic, ridge from the Ridge topic, and k-NN and decision trees from their topics. The k-NN topic already showed LOOCV with a vote; here the model is a line.

Tags: [SRC] from your files, [DERIVED] answer I worked out because the bank gives no key, [ADDED] my own example, [FLAG] disagreement between my calculation and a key.
How to use this page

Read each section, do the quick checks, then attempt each PYQ before opening its solution.

What is new in this upgrade [ADDED]

The route through this topic
three kinds of dataread errors and tunek-fold and leave-one-outcompare models

2. Big picture: concept map, comparison table and the recipe

[ADDED] Read this page first. It shows why we validate, how folds work and which facts the exam asks.

The concept map

Candidate settingslambda, k, depth, ...Split the datatrain | validationFit + scorevalidation errorPick lowestvalidation errork-foldk models, train on n(k-1)/k, validate on n/kLeave-one-out (k = n)n models, train on n-1, validate on 1The test set is never used for choosing: it is kept for one final honest score.Training error alone always favours the most flexible model, so it cannot choose the setting.
Try each candidate setting, score it on data it was not trained on, pick the lowest validation error. k-fold and leave-one-out differ only in how the data is split.

Train, validation, test: three jobs [ADDED]

SetUsed toUsed for choosing?Used once?
Trainingfit the weights / build the treenomany times
Validationcompare settingsyesmany times
Testreport the final scorenoonce

k-fold against leave-one-out [ADDED]

k-fold ($k<n$)Leave-one-out ($k=n$)
Models trained$k$$n$
Training size$n\frac{k-1}{k}$$n-1$
Validation size$n/k$$1$
Costsmallerlargest (n fits)
Estimatea little pessimistic (less training data)nearly unbiased, can vary more

Counting, with examples [ADDED]

$n$$k$Models (one setting)Training sizeValidation size
100558020
100044750250
505050491
600101054060

With $5$ candidate values of a hyperparameter and $k=4$, a full search trains $5\times4=20$ models. Read whether the question says "one value" or "all values".

Mnemonics and recognition cues [ADDED]

Analogy and its limit [ADDED]

AnalogyGood forWhere it breaks
Practice exams: study from some, test yourself on the one you held backwhy the held-out part must stay unseenevery fold is eventually used for training, so cross-validation scores are not a final test; keep a separate test set

Recall questions

$n=100$, $k=5$: models and training size?

$5$ models, $80$ points each.

Leave-one-out on $n=50$: how many models?

$50$, each trained on $49$ points.

Tips and tricks
  • Decide first which set the question is about: training, validation or test.
  • Pick a hyperparameter by validation error, never by training error.

3. Start here: a line through points

Picture it

A ruler laid through two nails: two points fix the line.

Piece 1. Fitting $y=w_0+w_1x$

Formula: simple linear regression

$$w_1=\frac{S_{xy}}{S_{xx}},\qquad w_0=\bar y-w_1\bar x,\qquad S_{xx}=\sum(x_i-\bar x)^2,\ S_{xy}=\sum(x_i-\bar x)(y_i-\bar y)$$ $\bar x$ and $\bar y$ are the means of the $x$ and $y$ values; $w_1$ is the slope and $w_0$ the intercept of the least-squares line.

Worked example: Simple: two points

Problem. Points $(1,2)$ and $(0,1)$. Find $w_0,w_1$.

What is asked. The line.

Idea / formula used. Two points define a line exactly.

Slope $=(2-1)/(1-0)=1$.
Intercept: at $x=0$, $y=1$, so $w_0=1$.
So $y=1+1\cdot x$ and $\|w\|^2=1^2+1^2=2$.
Answer: $w=(1,1)$
Common mistake: using $\sum xy/\sum x^2$ without the intercept.
Worked example: Exam level: three points

Problem. Points $(3,8),(0,3),(6,13)$. Find the least-squares line.

What is asked. $w_0,w_1$.

Idea / formula used. Means, then $S_{xx}$ and $S_{xy}$.

$\bar x=(3+0+6)/3=3$, $\bar y=(8+3+13)/3=8$.
$S_{xx}=(0)^2+(-3)^2+(3)^2=18$.
$S_{xy}=(0)(0)+(-3)(-5)+(3)(5)=30$.
$w_1=30/18=1.6667$, $w_0=8-1.6667\cdot3=3$.
Answer: $y=3+1.667x$
Common mistake: forgetting to subtract the means.

Piece 2. Three kinds of data

SetUsed forUsed to choose settings?
Trainingfit the weightsno
Validationcompare settings (hyperparameters)yes
Testfinal honest scorenever
Tips and tricks
  • Through two points the line has slope $(y_2-y_1)/(x_2-x_1)$. Check it by putting one point back.
  • Square each residual before adding; signs must not cancel.
Memory line

Two points fix a line; residual is predicted minus actual.

Fitting a line to two points
take two pointsslope = rise over runput one point back for the interceptresidual = predicted minus actual

4. Reading training and validation errors; choosing a hyperparameter

Intuition

Everyday analogy

A student who memorises last year's paper scores full marks on it (training) but poorly on a new paper (validation). The honest score is the new paper's, so that is what we use to choose between students (settings).

PatternTraining errorValidation errorDiagnosis
gap is bigvery lowmuch higheroverfitting (too flexible)
both highhighhighunderfitting (too rigid)
both low and closelowlowgood fit
Formula: Selection rule

Choose the setting with the lowest validation error. Training error alone is misleading because it keeps falling as the model becomes more flexible.

Worked examples

Worked example: Exam level: pick a training setting

Problem. (learning rate, iterations): A $(0.01,2000)$ train $90$, validation $118$; B $(0.05,900)$ train $88$, val $95$; C $(0.2,600)$ train $70$, val $140$; D $(0.5,200)$ train $130$, val $138$.

What is asked. The best setting and why.

Idea / formula used. Choose by validation error; read the gap to name the problem.

Validation errors: $118,95,140,138$. B is lowest.
C has the lowest training error but a gap of $70$: it overfits.
D is high on both: it has not fitted well.
Answer: setting B
Common mistake: choosing C for its training error.
Worked example: Exam level: choosing ridge $\lambda$

Problem. $\lambda=0.01$: train $0.8$, val $5.6$; $0.5$: $1.4,\,2.9$; $2$: $2.2,\,2.4$; $20$: $4.9,\,5.0$; $200$: $9.8,\,10.1$.

What is asked. The best $\lambda$.

Idea / formula used. Lowest validation error.

Validation errors: $5.6,2.9,2.4,5.0,10.1$; the lowest is at $\lambda=2$.
$\lambda=0.01$ has a large gap (overfits); $\lambda=200$ has both errors large (underfits).
Validation error falls and then rises: that U shape is what you look for.
Answer: $\lambda=2$
Common mistake: picking the smallest training error, which always favours the smallest $\lambda$.
Trap: training error is not the criterion

Never pick a setting just because its training error is lowest. The validation error decides.

The Aug 2025 table as a picture [ADDED]

140160180200150145140170160150190180setting 1setting 2setting 3setting 4solid blue: training dashed red: validation green dot: chosen (lowest validation)
Real numbers from the Aug 2025 question. Setting 3 has the lowest training error (140) but the worst validation error (190); setting 2 has the lowest validation error (150).

Diagnosis table [ADDED]

SignReadingWhat to try
train $\ll$ validationoverfittingmore regularisation, simpler model, fewer iterations
both highunderfittingless regularisation, more flexible model
both low, closegood fitkeep
validation rises while training fallsoverfitting has begunstop earlier / pick the earlier setting
Setting A: train 5, validation 30. Setting B: train 12, validation 14. Which?

B (lowest validation).

Can training error pick the best $\lambda$?

No, it keeps falling as flexibility grows.

Tips and tricks
  • Choose the value with the smallest validation error, even if its training error is larger.
  • Low training error with high validation error signals overfitting; both high signals underfitting.
Memory line

Train to fit, validate to choose, test to report.

5. How k-fold cross-validation works: counting models and sizes

Intuition

Everyday analogy

Split a class into $k$ equal study groups. Let each group take its turn as the "exam group" while the other $k-1$ groups are used to study. Everyone gets examined exactly once.

Definition: k-fold cross-validation

Split the $n$ points into $k$ equal parts (folds). For each fold $j=1,\dots,k$: train on the other $k-1$ folds, evaluate on fold $j$. Average the $k$ validation errors.

Formula: Counts

$$\text{models trained (for one setting)}=k,\qquad \text{training size}=n\cdot\frac{k-1}{k},\qquad \text{validation size}=\frac nk$$ $n$ is the number of data points and $k$ the number of folds. Leave-one-out is the special case $k=n$: $n$ models, each trained on $n-1$ points.

If you test several values of a hyperparameter (say $5$ values of $\lambda$), the total number of models is $5\times k$. The question wording says whether it asks for "one value of $\lambda$" or for all.

Worked example: Simple: counts

Problem. $n=1000$, $k=4$ folds, one value of $\lambda$. How many models are trained and how big is each training set?

What is asked. Both numbers.

Idea / formula used. One model per fold.

$k=4$ folds, so $4$ models.
Each fold has $1000/4=250$ points and is held out once.
Training set $=1000-250=750$ points.
Answer: $4$ models, $750$ training points each.
Common mistake: answering $250$ (that is the validation size) or $1000$.
Worked example: Tricky: leave-one-out counts

Problem. $n=50$ points, leave-one-out. Models and training size?

What is asked. Both numbers.

Idea / formula used. $k=n$.

$k=n=50$, so $50$ models.
Each trains on $50-1=49$ points.
Answer: $50$ models of $49$ points
Common mistake: saying $1$ model.

Five folds, drawn [ADDED]

data split into k = 5 equal folds (columns)round 1validatetraintraintraintrainround 2trainvalidatetraintraintrainround 3traintrainvalidatetraintrainround 4traintraintrainvalidatetrainround 5traintraintraintrainvalidateEach fold validates once; the 5 validation errors are averaged. 5 models, each trained on 4/5 of the data.
Each column is one fold. In round r the r-th fold is held out for validation and the other four are used for training.

Counting slips [ADDED]

SlipCorrect
training size $=n/k$$n(k-1)/k$ (that is the validation size plus the rest)
models $=n$ for $k$-fold$k$ models
forgetting the number of settingstotal $=\text{settings}\times k$
$n=600$, $k=10$: validation size?

$60$.

Which $k$ gives leave-one-out?

$k=n$.

Interactive explorer

Each row is one training run. Yellow points are held out for validation in that run, blue points train the model. Set $k=n$ to see leave-one-out.

Tips and tricks
  • Models trained = number of folds times number of candidate values. Add one only if the question also retrains on all data.
  • With $n$ points and $k$ equal folds, each model trains on $n(k-1)/k$ points.
Memory line

Models trained: folds times candidate values.

6. Leave-one-out cross-validation for a line

Picture it

Each pupil takes a turn as the examiner's surprise question while the others are the study material.

Procedure

  1. Take the left-out point; remove it.
  2. Fit the line $y=w_0+w_1x$ on the remaining points.
  3. Predict the left-out point: $\hat y=w_0+w_1x_{out}$.
  4. Compare with the true $y_{out}$ (squared error $(\hat y-y_{out})^2$).
  5. Repeat for each point and average the errors.

Worked examples

Worked example: One fold in full, then your turn

Problem. $D=\{(1,1),(3,5),(2,0)\}$, model $y=w_0+w_1x$. Leave out $(2,0)$.

What is asked. $\|w\|_2^2$ and the squared error on the left-out point.

Idea / formula used. Fit the line on the other points, then test it once.

Fit on $(1,1)$ and $(3,5)$: slope $w_1=(5-1)/(3-1)=2$.
Intercept: $w_0=1-2\cdot1=-1$.
$\|w\|_2^2=(-1)^2+2^2=5$.
Prediction at $x=2$ is $3$; true value $0$; squared error $9$.
Your turn: leave out $(3,5)$ instead, then reveal the next line.
Fit on $(1,1),(2,0)$: $w=(2,-1)$; prediction at $3$ is $-1$; squared error $36$.
Answer: $\|w\|_2^2=5$, error $9$ (second fold: $36$)
Common mistake: fitting on all three points before testing.
Worked example: Exam level: full LOOCV on four points

Problem. $(3,8),(0,3),(5,12),(6,13)$. Run LOOCV.

What is asked. Fitted line and prediction for each left-out point.

Idea / formula used. Refit four times.

Leave out $(3,8)$: fit on the other three gives $w_0=3.065$, $w_1=1.710$; prediction $8.194$ against true 8.
Leave out $(0,3)$: fit on the other three gives $w_0=3.000$, $w_1=1.714$; prediction $3.000$ against true 3.
Leave out $(5,12)$: fit on the other three gives $w_0=3.000$, $w_1=1.667$; prediction $11.333$ against true 12.
Leave out $(6,13)$: fit on the other three gives $w_0=2.895$, $w_1=1.789$; prediction $13.632$ against true 13.
Squared errors: 0.037, 0.000, 0.444, 0.399; their mean (the LOOCV mean squared error) is $0.220$.
Answer: The LOOCV MSE is about $0.220$.
Common mistake: using the same fitted line for all four predictions.
Trap: which point is left out

When a question says "the 3rd sample is the validation point", number from $1$ in the table order: here sample 3 is $(5,12)$.

The four-point LOOCV, drawn [ADDED]

01234567051015(3, 8)(0, 3)(5, 12)(6, 13)Each line is fitted with one point left out (same colour as that point). Predictions: 8.19, 3.00, 11.33, 13.63
Each line leaves out one point (same colour). The lines barely move, because the points are nearly collinear; the predictions 8.19, 3.00, 11.33, 13.63 are close to the true values $8,3,12,13$.
Left outPredictionTrueSquared error
(3, 8)8.19480.037
(0, 3)3.00030.000
(5, 12)11.333120.444
(6, 13)13.632130.399

Mean of the four squared errors: 0.220. A large error flags a point that the rest of the data cannot predict (here $(5,12)$).

In LOOCV, is the left-out point used to fit its own line?

No, never.

Tips and tricks
  • With three points, each leave-one-out line passes through the other two, so no fitting formula is needed.
  • Average the squared errors over all left-out points unless the question asks for the sum.
Memory line

Leave one out, fit the rest, square the miss, average.

7. Model comparison: zero training error, geometry and true/false facts

Picture it

A suit cut to every crease of one person fits nobody else.

Which models can reach zero training error?

Zero training error means every training point is predicted correctly (or exactly, for regression).

ModelZero training error guaranteed?Why
Look-up rule $h(x_i)=y_i$Yesit repeats the label
Decision tree (grown fully, distinct points)Yeskeep splitting until leaves are pure
$1$-NN (each point its own neighbour)Yesnearest point is itself
$k$-NN with $k=5$Noa point can be outvoted
Naive BayesNoits assumptions can force mistakes
Linear model $w^Tx+b$Noa straight line cannot fit every pattern, even if $n>d+1$
Predict the mean $\frac1n\sum y_j$ or $0$Noignores the input

Geometry of the decision or fit

ModelBoundary shape
Decision treeaxis-aligned (splits $x_j\le t$)
Ridge and Lasso regressionlinear (a hyperplane)
$1$-NNnon-linear, piecewise
Gaussian Naive Bayes (different variances per class)non-linear, curved (quadratic)

True / false facts that keep appearing

StatementTrue?
Decision trees are a supervised method for classificationTrue
k-NN is lazy (no explicit model built at training)True
In k-NN $k$ is the number of featuresFalse ($k$ counts neighbours)
k-NN is parametric and needs fitted distributionsFalse
Depth of a tree is a hyperparameter, typically chosen by cross-validationTrue
A question $f_k\le\theta$ always splits the data into two non-empty setsFalse (if $\theta$ is outside the data range one side is empty)
A "better" question has greater information gainTrue (that is how "better" is defined)
Trees overfit if the maximum depth is too lowFalse (they underfit)
Trees underfit if the maximum depth is too lowTrue
The training set is not needed to predict with k-NNFalse (it is needed)
Trap: overfit vs underfit with depth

Too deep $\Rightarrow$ overfit. Too shallow $\Rightarrow$ underfit. A "too low depth overfits" option is always false.

Why each model can or cannot reach zero training error [ADDED]

ModelDistinct points, any labelsReason
fully grown treeyeskeep splitting to pure leaves
$1$-NN (own neighbour)yesnearest point is itself
$k$-NN, $k\ge2$nooutvoted by neighbours
linear classifiernoXOR-type labels cannot be split by a line
naive Bayesnoindependence can force mistakes
Why can a linear classifier fail even with distinct points?

Labels in an XOR pattern are not separable by a single line.

Worked example: zero training error or not

Four points $x=1,2,4,8$ with labels $0,1,0,1$. 1-NN: every point is its own nearest neighbour, so training error is $0$. 3-NN (each point counts itself): $x=2$ has neighbours $2,1,4$ with labels $1,0,0$, so it is predicted $0$ and is wrong; the other three are right, so training error is $1/4$. One threshold $x\le\theta$ cannot reproduce the pattern $0,1,0,1$, so it makes at least one training mistake.

Tips and tricks
  • Zero training error says nothing by itself about new data.
  • Test each true or false line with the extreme case of a very flexible model.
Memory line

Perfect training fit proves nothing about new data.

Judging two models
fit both on training datameasure on unseen dataignore a perfect training scoreprefer the lower unseen error

Practise this topic →

Weeks covering this topic

Other MLT topics