What learning is · lesson 9 of 13
Parts in this lesson
Across_val_score(model, X, y, cv=5)five scores from five folds
BGridSearchCV(model, {'n_neighbors': [...]}, cv=5)trying each setting with cross-validation
CStratifiedKFold(5)folds that keep the class mix

Validation and cross-validation

Last updated

Choosing k, or any other setting, means comparing models on data they didn’t train on. But that data can’t be the test set, or the test set stops being a fair final exam. The answer is a third set, the validation set, and its better version, cross-validation, which lets every example take a turn. This lesson builds both, tunes k with GridSearchCV, and shows what happens if you tune on the test set instead.

By the end of this lesson you can

  • Explain the different jobs of the training, validation and test sets
  • Score a model with k-fold cross-validation, and read the mean and spread of its scores
  • Tune a hyperparameter with GridSearchCV, and keep the classes balanced with stratified folds
  • Explain why tuning on the test set gives a score that’s too good

Train, validation, test

Lesson 2.6 left a problem. To choose k, you need scores on data the model didn't train on; but if you use the test set for that, the test set helps choose the model, and its score is no longer a fair estimate. So split three ways:

  • the training set trains each candidate model;
  • the validation set compares the candidates and picks the best;
  • the test set is used once, at the very end, to score the one model you picked.
Three sets150 flowers, split once, before anything else
90trainingtrains each candidate30validationchooses one30testscores it, oncelocked until the end

The model never trains on the validation or test sets. Validation is used many times, to choose; the test set is used once, to report.

This lesson uses the iris flowers that come with scikit-learn: 150 flowers of three species, four measurements each, all in centimetres, so they don't need scaling. Split twice to get three sets:

iris.ipynb

90 to train, 30 to validate, 30 to test. Then each k is trained on the 90 and scored on the 30. The trouble shows straight away: k=1 and k=5 both score 1.0. Thirty flowers is so few that each one is worth 3.3 percentage points, and the validation set can't tell the candidates apart. With small data, a single validation set is a noisy judge.

k-fold cross-validation

Cross-validation makes better use of the data. Cut the training data into k equal blocks, called folds (this k is unrelated to k-NN's). Then, k times over, hold out one fold for validation and train on the rest. Every example is used for validation exactly once, and you get k scores instead of one:

Fold rotationround 1 of 5
fold 1validate0.967fold 2trainfold 3trainfold 4trainfold 5traintestuntouchedRound 1: train on folds 2, 3, 4, 5; score on fold 1.

Scores so far: 0.967. Their mean: 0.967.

cross_val_score does all five rounds in one call:

iris.ipynb

Five scores, from 0.933 to 1.0, with a mean of 0.973 and a spread (standard deviation) of 0.025. Report both: the mean is the estimate, and the spread says how much to trust it. Two models whose means differ by less than their spreads may not really differ at all. Five or ten folds are usual; more folds mean more training runs.

Grid search

To tune a setting, cross-validate every candidate value and keep the best. GridSearchCV does this for a list (a "grid") of values, then retrains the winner on all the training data:

search.ipynb

It tried 7 values of k, each with 5-fold cross-validation (35 training runs), and picked k=15 with a mean validation score of 0.967. Only then is the test set used, once: 1.0. That's a fine score, but 30 flowers is a small test, so the honest summary is "about 97%, from cross-validation; 30 of 30 on the test set".

The pattern to remember: split off the test set first; do all your choosing with cross-validation on the rest; score on the test set once, at the end.

Stratified folds

The iris file is sorted: 50 flowers of species 0, then 50 of species 1, then 50 of species 2. Cut it into three folds in order, without shuffling, and something goes badly wrong:

folds.ipynb

Plain KFold(3) scores 0 on every fold. Each fold is one whole species, so every time, the model trains on the other two species and is tested on a species it has never seen. StratifiedKFold builds each fold with the same class mix as the whole, and scores 0.98.

For classification, cross_val_score and GridSearchCV already use stratified folds when you pass cv=5, which is why step 2 worked. The danger is when you build folds yourself, or when data is sorted by something else that matters (by date, by hospital, by person). Always ask what each fold contains.

Wrong way: tuning on the test set

What's the harm in picking k by the test score, just this once? Here's a problem with noisy labels and plenty of data, so we can see what happens later "in real use". Train on 150 examples, try 50 values of k on a 50-example test set, keep the winner, then score it on 19,000 new examples:

testtune.ipynb

The best k scored 0.90 on the test set. In real use it scores 0.732. Nothing was wrong with k=13; the 0.90 was luck. With 50 tries, one of them is bound to land on a run of easy test examples, and choosing the best of 50 picks exactly that luck. The test score was a fair estimate of one model, but it's not a fair estimate of the best of 50.

That's why the test set is used once. If you must try many things, cross-validate on the training data, and accept that even the cross-validation score of the winner is a little optimistic, for the same reason. Kaggle competitions show this every time: the public leaderboard, which people tune against, flatters them; the private one, held back to the end, doesn't.

Check what you learned

Which set should be used to choose between k=5 and k=15?
Predict, then check with the fold figure: with 5-fold cross-validation on 200 examples, how many examples are in each validation fold, and how many times is each example used for validation?
You try 100 settings, scoring each on the test set, and report the best test score. Why is it likely too high?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning