Lesson 2.7 · 11 min read · about 1 h to master at a very slow pace

Cross-validation

K-fold cross-validation step by step, a worked comparison of two models, why each fold is an independent experiment, and when ordinary random folds are the wrong tool.

Not startedJump to quiz

Why not just one validation split?

A single split has two weaknesses: unless data are plentiful you end up with too few training points or too few validation points, and the result depends on which rows happened to land where. Cross-validation reuses the data through several train/validation partitions.

K-fold cross-validation

F1F2F3F4F5
Round 1
Round 2
Round 3
Round 4
Round 5
Train on these 4 foldsValidate on this fold
5-fold CV: every observation is used for validation exactly once and for training K − 1 = 4 times.
  1. Randomly split the data into roughly equal folds (typically or ).
  2. For each fold : train on the other folds and compute the error on fold .
  3. Average the errors: .
  4. Do this for each candidate model (or each value of a hyperparameter) and pick the best average. Re-train the chosen model on all the training data.

Cost: you fit the model times per candidate. Training on of the data is nearly as good as training on all of it.

Worked example: choosing between two models with 5-fold CV

Validation RMSEF1F2F3F4F5Mean
Model A (simple)2.102.402.202.302.102.22
Model B (flexible)1.503.201.602.901.802.20

B is marginally better on average, but its fold errors range from 1.5 to 3.2: a sign of instability (high variance). A sensible analyst might prefer A. Look at the spread, not just the mean.

Click through the same comparison round by round:

Each fold is an independent experiment

A patient can be in the validation fold in round 1 and in the training folds in round 2. That's fine: each round is a fresh fit from scratch, and nothing learned in round 1 is carried into round 2. Anything that learns from data (scaling, feature selection, oversampling) must be redone inside each round, using that round's training folds only.

CV is not the final test

CV chooses models and hyperparameters using the training data. A separate untouched test set still gives the final honest number. And folds must respect the structure of the data:

  • Time series: random folds train on the future. Use forward-chaining folds instead (2.8).
  • Repeated measurements on a person: keep all of a person's rows in the same fold (group K-fold).

Stuck? Common doubts

Questions real learners asked while studying this lesson. They stay closed so they don't spoil your own thinking: open only the ones you need.

Going deeperWhen moving to the second fold, the previous validation fold becomes training data. Aren't we influencing the outcome?

No. Each fold is an independent training–validation experiment. The model is re-fitted from scratch each round, and feature selection (or any other learned preprocessing) is repeated using only that round's training folds. Being validation data in one round and training data in another is exactly how CV is designed, and it isn't leakage by itself.

What can bias the result is repeatedly changing your whole methodology based on CV scores. Then the CV estimate itself becomes optimistic, which is why a final untouched test set is still valuable.

Going deeperIf feature selection happens inside each fold, why would the selected features differ between folds?

Because each round sees a different training subset, so the "best 20 genes" are ranked on slightly different data. In the wrong approach, genes are selected once using all the data, so every fold uses the same genes. In the correct approach they're selected independently within each fold, so they can differ, though they may also turn out identical.

Cheatsheet

K-fold CV

1) Split into folds. 2) For each fold: train on , validate on it. 3) Average the errors. 4) Pick the best candidate; re-fit on all training data.

CV with preprocessing

Scaling, imputation, feature selection and oversampling happen inside each fold, on that fold's training part only.

See every cheatsheet by category →

Check your understanding

Score 75% or more to master this lesson and earn XP. Answer first, then check.

Q1calculateThe validation errors from 5-fold cross-validation are 4, 6, 5, 7 and 3. What is the CV estimate?
Q2calculateYou compare 3 candidate models with 10-fold cross-validation. How many model fits does that take, not counting the final refit?
Q3diagnoseWhy is ordinary random K-fold CV inappropriate for forecasting next month's demand from monthly data?
Q4interpretModel A has mean CV RMSE 2.22 with fold errors between 2.1 and 2.4. Model B has mean 2.20 with fold errors between 1.5 and 3.2. Which conclusion is most reasonable?
Q5diagnoseA team standardises features using the mean and SD of the whole training set, then runs 5-fold CV on it. Is there a leak?