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 , 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.
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:
90 to train, 30 to validate, 30 to test. Then each is trained on the 90 and scored on the 30. The trouble shows straight away: and 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 equal blocks, called folds (this is unrelated to -NN's). Then, times over, hold out one fold for validation and train on the rest. Every example is used for validation exactly once, and you get scores instead of one:
Scores so far: 0.967. Their mean: 0.967.
cross_val_score does all five rounds in one call:
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:
It tried 7 values of , each with 5-fold cross-validation (35 training runs), and picked 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:
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 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 on a 50-example test set, keep the winner, then score it on 19,000 new examples:
The best scored 0.90 on the test set. In real use it scores 0.732. Nothing was wrong with ; 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
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.
- scikit-learn: Cross-validation: evaluating estimator performance: k-fold, stratified k-fold and cross_val_score
- scikit-learn: Tuning the hyper-parameters of an estimator: GridSearchCV
- Goodfellow, Bengio and Courville, Deep Learning, chapter 5: Machine Learning Basics: hyperparameters and validation sets, and cross-validation (5.3)
- Fisher, The use of multiple measurements in taxonomic problems, Annals of Eugenics 7(2), 1936: where the iris flower measurements were published