Gradient LabStart the lesson

Lessons › Chapter 5: Generalization

Cross-validation

cross-validation cuts the data into equal slices called folds. Here there are 5, shown in different colors.

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Was the test lucky?

Maya worries that one particular test split made the model look better than it is.

Problem

One split can be lucky

With a single train/test split, the score depends on which examples happened to land in the test set. You might get an easy test set by chance, and a score that flatters the model.

Concept

Cut the data into folds

cross-validation cuts the data into equal slices called folds. Here there are 5, shown in different colors.

Build

Take turns being the test set

Train on 4 folds and test on the 5th. Then rotate: a different fold is the test set each round. Every example gets to be in the test set exactly once.

Key idea

Average the rounds

Average the 5 scores: 86%. The spread between rounds (82% to 90%) also tells you how stable the model is. That is far more trustworthy than a single lucky number.

Real life

In real life: checking a model on different months

Banks and insurers test a model on several different slices of customers, such as different months, before trusting it. If it scores well in March but badly in July, they want to know why before using it for real decisions.

Quick check: In 5-fold cross-validation, how many times is the model trained?

Once per fold: each round trains a fresh model with a different fold held out.

Pseudocode

folds = split the data into 5 equal parts
scores = []
for each fold:
    test  = this fold
    train = the other 4 folds
    scores.add(train_and_score(train, test))

final score = average(scores)

Key terms

cross-validation
Testing a model several times, each time holding out a different slice of the data.
fold
One of the equal slices the data is cut into for cross-validation.

Build it: A screening classifier that doesn’t miss cases (35 min, runs in your browser)

See the project