Cross-Validation and Hyperparameter Tuning
Estimate performance reliably with k-fold cross-validation, tune hyperparameters with grid and random search, and keep the test set truly untouched.
Welcome back!
Step 1 of 13Learn
One split can lie
You split 1,000 examples into 800 for training and 200 for validation and get 86% accuracy. A classmate uses a different random split of the same data and gets 81%. Who's right?
Both. With 200 validation examples, the score depends noticeably on which examples happened to land in the validation set. One split gives a noisy estimate, and if you then choose between models based on small differences, you may be choosing based on luck.
k-fold cross-validation reduces this noise:
- Shuffle the data and divide it into k equal folds, commonly k = 5 or 10.
- For each fold in turn: train on the other k − 1 folds and validate on this one.
- Average the k validation scores. Their spread (standard deviation) shows how stable the estimate is.
With 1,000 examples and k = 5, each round trains on 800 and validates on 200, and every example is used for validation exactly once. You get five scores, say 0.84, 0.86, 0.81, 0.85 and 0.84, with a mean of 0.84, a much more trustworthy estimate than any single split.
Variants handle special cases:
- Stratified k-fold keeps the class proportions the same in each fold, which matters for imbalanced classes.
- Group k-fold keeps all rows from the same person, patient or store in one fold, preventing leakage.
- Time series split always trains on earlier data and validates on later data.
The cost: k times the training time. For large datasets or slow models, a single well-sized validation set is often enough; for small and medium datasets, cross-validation is the standard.
Step 2 of 13Practice · Work it out
In 5-fold cross-validation, a model scores 0.80, 0.84, 0.78, 0.86 and 0.82 on the five folds. What is its mean cross-validation score?
Step 3 of 13Chart
Five folds, five scores
The spread between folds shows how much a single split could have misled you.
Step 4 of 13Learn
Hyperparameters and how to search them
Parameters are learned from data during training: weights, biases, tree split thresholds. Hyperparameters are set before training and control how learning happens:
- Learning rate and number of epochs
- Regularization strength λ
- Maximum depth and minimum leaf size of a tree
- Number of trees in a forest, learning rate and rounds in boosting
- k in k-nearest neighbors
- Number of layers and neurons in a network
Choosing them is called tuning, and it is done by comparing validation (or cross-validation) scores.
Grid search tries every combination from lists of values. For depth ∈ {3, 5, 7, 9} and minimum leaf size ∈ {1, 5, 20}, that's 4 × 3 = 12 combinations, each evaluated with cross-validation. Simple and thorough, but the number of combinations explodes as you add hyperparameters: five hyperparameters with five values each means 3,125 combinations.
Random search samples a fixed number of random combinations from ranges you specify. Research and experience show it often finds good settings with far fewer trials than grid search, because usually only a few hyperparameters really matter, and random sampling tries many more distinct values of each.
Bayesian optimization and similar methods use results so far to choose promising combinations next, which helps when each training run is expensive.
Practical tips: search learning rates and regularization strengths on a log scale (0.001, 0.01, 0.1, 1); start with a coarse search, then refine around the best region; and fix the random seed to make comparisons repeatable.
Step 5 of 13Compare
Grid search vs. random search
| Aspect | Grid search | Random search |
|---|---|---|
| How | Every combination of listed values | Random combinations from ranges |
| Cost | Multiplies: 4 × 3 × 5 = 60 fits | You choose the budget |
| Strength | Thorough on few hyperparameters | Explores more values of the ones that matter |
| Best for | 2 or 3 hyperparameters | Many hyperparameters |
Step 6 of 13Practice · Work it out
A grid search tries learning rates {0.01, 0.05, 0.1}, tree depths {3, 5, 7, 9} and numbers of trees {100, 300}, evaluating every combination with 5-fold cross-validation. How many models are trained in total?
Step 7 of 13Learn
Keeping the test set honest
Every time you look at a score and make a decision based on it, information leaks from that data into your model choices. Try enough variations against the same data and you will eventually find one that scores well by chance. This is sometimes called overfitting to the validation set.
That's why the standard protocol uses three roles:
- Training data to fit parameters.
- Validation data (or cross-validation on the training portion) to choose hyperparameters, features and models.
- Test data, used once, at the very end, to estimate how the final model will perform on new data.
If you look at test scores during development and go back to adjust the model, the test set has become a second validation set, and its score is now optimistic. There is no way to "un-see" it; the honest fix is to collect fresh test data.
Nested cross-validation is the rigorous version for small datasets: an inner cross-validation loop tunes hyperparameters, and an outer loop estimates the performance of the whole tuning procedure.
Some other habits that keep evaluation honest:
- Put all preprocessing inside the cross-validation loop, using pipelines, so scalers and imputers are fit only on each training fold.
- Report uncertainty, for example the mean and standard deviation across folds, not just a single best number.
- Compare against a baseline evaluated the same way.
- Keep a record of everything you tried. If you tested 200 variants, the best one's score is likely somewhat inflated.
Step 8 of 13Practice · Diagram
Who sees which data
Which part should you use to pick the regularization strength λ?
Tap the shape that answers the question, then press Check.
- All labeled data
- Training portion (80%)
Everything you are allowed to look at while developing.
- Test set (20%)
Locked away and used once, at the very end.
- Training folds
Fit the parameters.
- Validation folds
Choose hyperparameters, features and models.
Step 9 of 13Practice · Put in order
Put the steps of a clean model selection process in order.
Drag the items, or use the arrow buttons, to put them in order.
- Tune hyperparameters with cross-validation on the training data
- Split off a test set and set it aside
- Retrain the chosen configuration on all the training data
- Build a preprocessing and model pipeline
- Evaluate once on the test set and report the result
Step 10 of 13Practice · Code challenge
Write accuracy(actual, predicted) that returns the share of positions where the two arrays hold the same label, as a number between 0 and 1. You might use it to score each fold in cross-validation.
accuracy([1, 0, 1, 1], [1, 1, 1, 0])accuracy([0, 0], [0, 0])accuracy([1, 0, 1, 0, 1], [0, 0, 1, 0, 1])accuracy(["cat", "dog", "cat", "bird"], ["cat", "cat", "cat", "bird"])
Step 11 of 13Note
Step 12 of 13Practice · True or false
After evaluating your final model on the test set, it is fine to tweak the model and re-test on the same test set as many times as you like, since you are not training on it.
Step 13 of 13Practice · Choose one
You have 400 labeled examples, and 10% belong to the positive class. Which validation strategy is most appropriate for comparing models?
Lesson complete!