Cross-validation and grid search
| Problem | Estimate how well a model will predict new data, and choose hyperparameters, using only the data at hand |
| Devised by | Seymour Geisser (1975) and Mervyn Stone (1974), cross-validation; Peter Lachenbruch and M. Ray Mickey (1968), leave-one-out; Ron Kohavi (1995), stratified folds; Leo Breiman et al. (1984), the one-standard-error rule; Gavin Cawley and Nicola Talbot (2010), selection bias |
| Accuracy | Nearly unbiased for a model trained on of the data, with a variance that is hard to estimate |
| Cost | fits per candidate setting; a grid over settings costs fits |
| Read first | Background: bias and variance, Foundations: models, data, preprocessing and metrics |
| API | k_fold, stratified_k_fold, cross_validate_regressor, cross_validate_classifier, parameter_grid, grid_search, mean_score |
Overview
Every model in these chapters has a knob: a penalty, a depth, a number of neighbours, a kernel width, a learning rate. The training error always favours the most flexible setting, so it cannot choose. A single held-out test set can, but it wastes data and gives a noisy answer. k-fold cross-validation splits the data into parts, trains on of them and tests on the remaining one, rotates so that every point is tested exactly once, and averages. Grid search repeats this for every combination of candidate settings and keeps the best. Both are simple. The subtleties lie in what the estimate means, how variable it is, and how much the act of choosing biases it.
Where it is used
A model that fits the training data well may predict new data badly, and cross-validation is how we find out.
- Choosing hyperparameters. The regularisation of a ridge regression, the depth of a tree and the number of neighbours of a classifier are chosen by cross-validation.
- Honest reporting. Estimating the error a deployed model will have, for medical diagnostics, fraud detection or predictive maintenance.
- Comparing methods. Deciding between candidate algorithms on equal terms.
History
Holding data out to test a prediction rule is old. Peter Lachenbruch and M. Ray Mickey (1968) proposed leaving out one observation at a time to estimate discriminant error rates. Mervyn Stone (1974) and Seymour Geisser (1975) set out cross-validation as a general method for choosing and assessing predictors. Leo Breiman, Jerome Friedman, Richard Olshen and Charles Stone (1984) used ten-fold cross-validation and the one-standard-error rule to prune trees. Ron Kohavi (1995) recommended stratified ten-fold cross-validation from a large empirical study. Yoshua Bengio and Yves Grandvalet (2004) showed that no unbiased estimator of its variance exists, and Gavin Cawley and Nicola Talbot (2010) documented the bias of reporting the best cross-validated score.
The idea
k-fold cross-validation
Partition the indices into folds of nearly equal size, after shuffling. For each , fit the model on the other folds and score it on . The cross-validation estimate is the average score. Each point is predicted by a model that did not see it, so the estimate measures generalisation, but of a model trained on of the data. Leave-one-out () uses nearly all the data for each fit but needs fits.
Bias and variance of the estimate
The two words here refer to the error estimate, not to the model; for the model’s own bias and variance see the background section of the machine learning chapter.
For a 7-nearest-neighbour classifier on 200 independent data sets of 60 points, compared with the true error of the model fitted to all 60 points (measured on 5000 fresh points):
Table 13.5. Cross-validation estimates of the error against the number of folds.
| folds (7-NN, 60 points, 200 data sets) | mean estimate | standard deviation | RMS difference from the true error |
|---|---|---|---|
| 2 | 0.1351 | 0.0560 | 0.0866 |
| 5 | 0.1001 | 0.0355 | 0.0469 |
| 10 | 0.0935 | 0.0360 | 0.0424 |
| 60 (leave-one-out) | 0.0919 | 0.0390 | 0.0441 |
| true error of the model fitted to all 60 points | 0.0684 | 0.0073 |
Every estimate is pessimistic, because each fold’s model saw fewer points than the final one. Two folds, training on only 30 points, are the most pessimistic and the most variable. Five and ten folds are close to each other. Leave-one-out has the smallest bias but no smaller error overall: its training sets overlap almost completely, so their errors are correlated and do not average out. Even the best estimate is off by about 0.04, more than half the error being estimated. With small data sets, cross-validation is a rough guide.
Stratification
With imbalanced classes, random folds can miss the minority class entirely, making those folds’ scores meaningless. Stratified folds deal each class out in turn, so every fold has the overall class proportions:
Table 13.6. Minority-class points per fold with and without stratification.
| 10 folds of 100 points, 10 in the minority class | minority points in each test fold | folds with none |
|---|---|---|
| k-fold, shuffled | [0, 1, 0, 2, 0, 3, 1, 1, 0, 2] | 4 |
| stratified k-fold | [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] | 0 |
Choosing a hyperparameter
Ridge regression of a degree-12 polynomial on 40 noisy points, with 10-fold cross-validation over 25 values of the penalty:
Figure 13.6. Cross-validation of ridge regression.
| choice of α | α | CV estimate | true test error |
|---|---|---|---|
| minimum CV error | 1.33e-3 | 0.0504 | 0.1267 |
| one-standard-error rule | 2.37e-1 | 0.0581 | 0.1456 |
| best possible (oracle) | 0.1240 |
The cross-validation curve has the right shape, high for both too little and too much penalty, and its minimum lands close to the best possible choice. The one-standard-error rule (Breiman et al.) picks the simplest model, here the largest penalty, whose estimate is within one standard error of the minimum, on the grounds that the curve is too noisy to distinguish them. Here it chose a more heavily penalised model with a worse true error: the rule trades some accuracy for simplicity and stability. The cross-validation estimates are also well below the true test error, and even below the noise variance of 0.09, which no model can beat on new data. A single estimate from 40 points can be far off, as the previous table showed.
Grid search
Grid search evaluates every combination of candidate values, such as and for an RBF support vector machine, by cross-validation, and keeps the best. Its cost multiplies with every axis, so grids are usually coarse and logarithmic. Random search over the same ranges (James Bergstra and Yoshua Bengio, 2012) finds good settings with fewer evaluations when only a few hyperparameters matter.
The winner’s curse
The best of many noisy estimates is optimistically biased: some candidate will look good by luck. On data whose labels are pure coin flips, so that no model can beat 50%, a search over for -nearest neighbours gives:
Table 13.7. Selection bias of reporting the best cross-validated score on random labels.
| random labels, 60 points, 50 repetitions | mean | standard deviation |
|---|---|---|
| best cross-validated accuracy over k = 1, …, 40 | 0.619 | 0.047 |
| accuracy of the chosen k on new data | 0.499 | 0.015 |
The winning cross-validated accuracy averages 62%, but the chosen models score exactly chance on new data. The score used to choose a model is therefore not an estimate of its performance. Report performance on a test set that played no part in the choice, or use nested cross-validation, in which an inner loop chooses the hyperparameters within each outer training fold.
Algorithm
k-fold splitting of samples.
- List the indices , and shuffle them if a seed is given.
- Fold consists of positions to of the list, for . The fold sizes differ by at most one.
- Split uses fold as the test set and all the other folds as the training set.
Stratified splitting.
- Group the indices by class, and shuffle within each class.
- Deal the indices out to the folds one at a time, in rotation, like cards: the first index to fold 0, the next to fold 1, and so on, going straight on from one class to the next without restarting at fold 0. Every fold then has each class in nearly its overall proportion, and the folds have nearly equal sizes.
Cross-validation of a model on a set of splits. For each split:
- build a fresh, untrained model;
- fit it on the training rows;
- predict the test rows and compute the score.
Return the scores; their mean is the cross-validation estimate, and their standard deviation divided by a rough standard error.
Grid search over a list of candidate settings.
- For each candidate, compute its score, usually the mean cross-validation score.
- Skip any candidate whose evaluation fails or returns NaN.
- Return the candidate with the best score, and the scores of all of them.
The cost is (number of candidates) × (number of folds) model fits.
Implementation
pub fn stratified_k_fold(labels: &[usize], folds: usize, seed: u64) -> Result<Vec<Split>, ErrorsJSL> {
if folds < 2 || folds > labels.len() {
return Err(ErrorsJSL::InvalidInputRange("Need 2 <= folds <= samples."));
}
let classes = labels.iter().max().map_or(0, |m| m + 1);
let mut rng = MlRng::new(seed);
let mut assignment = vec![0usize; labels.len()];
let mut next = 0;
for c in 0..classes {
let mut members: Vec<usize> = (0..labels.len()).filter(|&i| labels[i] == c).collect();
rng.shuffle(&mut members);
for i in members {
assignment[i] = next % folds;
next += 1;
}
}
Ok((0..folds).map(|f| ((0..labels.len()).filter(|&i| assignment[i] != f).collect(), (0..labels.len()).filter(|&i| assignment[i] == f).collect())).collect())
}
pub fn grid_search<P: Clone, E: Fn(&P) -> Result<f64, ErrorsJSL>>(candidates: &[P], evaluate: E, greater_is_better: bool) -> Result<GridSearchResult<P>, ErrorsJSL> {
let scores: Vec<(P, f64)> = candidates.iter().filter_map(|c| evaluate(c).ok().filter(|s| !s.is_nan()).map(|s| (c.clone(), s))).collect();
let better = |a: f64, b: f64| if greater_is_better { a > b } else { a < b };
let (best, best_score) = scores.iter().fold(None, |acc: Option<(P, f64)>, (p, s)| match acc {
Some((_, b)) if !better(*s, b) => acc,
_ => Some((p.clone(), *s)),
}).ok_or(ErrorsJSL::RuntimeError("No candidate could be evaluated."))?;
Ok(GridSearchResult { best, best_score, scores })
}
- The cross-validation functions take a closure that builds a fresh model, so no state leaks between folds.
- Scores are any function of (truth, prediction). For errors such as the MSE, pass
greater_is_better = falsetogrid_search. - Preprocessing (scaling, feature selection) must be done inside each fold, on the training rows only, or information from the test fold leaks into the fit.
In practice
//! Cross-validation and grid search: tuning an RBF support vector machine.
use lib_jsl_machine_learning::datasets::make_moons;
use lib_jsl_machine_learning::kernels::Kernel;
use lib_jsl_machine_learning::metrics::accuracy;
use lib_jsl_machine_learning::model_selection::{cross_validate_classifier, grid_search, mean_score, parameter_grid, stratified_k_fold};
use lib_jsl_machine_learning::supervised::classification::SupportVectorMachine;
fn main() {
let (x, labels) = make_moons(150, 0.25, 4);
let folds = stratified_k_fold(&labels, 5, 1).unwrap();
let grid = parameter_grid(&[vec![0.1, 1.0, 10.0, 100.0], vec![0.1, 1.0, 10.0, 100.0]]);
let search = grid_search(
&grid,
|p| Ok(mean_score(&cross_validate_classifier(|| SupportVectorMachine::new(Kernel::Rbf { gamma: p[1] }, p[0]), x.view(), &labels, &folds, accuracy)?)),
true,
)
.unwrap();
for (p, score) in &search.scores {
println!("C = {:>5}, γ = {:>5}: cross-validated accuracy {score:.3}", p[0], p[1]);
}
println!("best: C = {}, γ = {} with {:.3}", search.best[0], search.best[1], search.best_score);
}
C = 0.1, γ = 0.1: cross-validated accuracy 0.820
C = 0.1, γ = 1: cross-validated accuracy 0.903
C = 0.1, γ = 10: cross-validated accuracy 0.940
C = 0.1, γ = 100: cross-validated accuracy 0.880
C = 1, γ = 0.1: cross-validated accuracy 0.850
C = 1, γ = 1: cross-validated accuracy 0.947
C = 1, γ = 10: cross-validated accuracy 0.950
C = 1, γ = 100: cross-validated accuracy 0.927
C = 10, γ = 0.1: cross-validated accuracy 0.887
C = 10, γ = 1: cross-validated accuracy 0.940
C = 10, γ = 10: cross-validated accuracy 0.957
C = 10, γ = 100: cross-validated accuracy 0.900
C = 100, γ = 0.1: cross-validated accuracy 0.927
C = 100, γ = 1: cross-validated accuracy 0.940
C = 100, γ = 10: cross-validated accuracy 0.930
C = 100, γ = 100: cross-validated accuracy 0.897
best: C = 10, γ = 10 with 0.957
Several settings are within 0.02 of the best, less than two standard errors of an accuracy measured on 300 points (about 0.013). The 0.957 is the winner’s score and slightly optimistic.
Strengths
- Uses all the data for both fitting and evaluation; works with any model and score.
- Stratification and the one-standard-error rule make it more reliable at little cost.
Weaknesses
- fits per setting, multiplied by the size of the grid.
- High variance on small data; no unbiased variance estimate; the best score is optimistic.
- Assumes independent rows: time series and grouped data need folds that respect the order or the groups.
Exercises
- Show that the training sets of two leave-one-out folds share of their points.
- For ordinary least squares, show that the leave-one-out residual is , where is the leverage, so leave-one-out needs only one fit.
- Explain why choosing features on the whole data set before cross-validating gives optimistic estimates. Construct an example with pure noise.
- Implement nested cross-validation and apply it to the random-label experiment above.
- Implement random search and compare it with grid search on the SVM example for the same number of evaluations.
Hints and answers
- The training set of fold is all points but , that of fold is all points but ; they share all points except and , which is of the .
- Deleting point changes the fit by (Sherman-Morrison), so the prediction error at is with .
- Selecting the features that correlate best with the labels on all the data uses the validation labels in the selection, so the validation score is biased upward. With 5000 pure-noise features and 50 samples, the best 10 features correlate with the labels by chance and give cross-validated accuracy well above 50%.
- In nested cross-validation the inner loop selects features or hyperparameters using only the outer training fold; on random labels the outer score should then be about 50%.
- Random search samples hyperparameters from distributions; for the same budget it covers each individual hyperparameter more densely than a grid, which helps when only a few of them matter.
Further reading
- M. Stone, “Cross-validatory choice and assessment of statistical predictions”, Journal of the Royal Statistical Society B 36 (1974) 111–147.
- R. Kohavi, “A study of cross-validation and bootstrap for accuracy estimation and model selection”, Proceedings of IJCAI (1995) 1137–1143.
- G. C. Cawley and N. L. C. Talbot, “On over-fitting in model selection and subsequent selection bias in performance evaluation”, Journal of Machine Learning Research 11 (2010) 2079–2107.
- Y. Bengio and Y. Grandvalet, “No unbiased estimator of the variance of k-fold cross-validation”, Journal of Machine Learning Research 5 (2004) 1089–1105.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, section 7.10.