Nested cross-validation

On this page 7

Nested cross-validation is a model evaluation procedure that wraps one cross-validation loop inside another: an inner loop selects hyperparameters or models, and an outer loop measures how well that whole selection process performs on data it never touched. In artificial intelligence and machine learning, it is the standard way to obtain an approximately unbiased estimate of generalization error when the same dataset must serve both for tuning and for evaluation.

The method addresses a subtle but common flaw. When a practitioner tunes a model with ordinary cross-validation and then reports the best cross-validation score, that score is optimistically biased, because the configuration was chosen precisely for scoring well on those folds. Nested cross-validation removes this selection bias by keeping every outer test fold outside the tuning process.

How the inner and outer loops work

Nested cross-validation splits the data twice, and each split has a distinct responsibility. The outer loop divides the dataset into K outer folds; for each one, the remaining data becomes an outer training set, and all tuning happens inside it through a separate inner cross-validation.

  1. Split the data into K outer folds, for example five.
  2. Hold out one outer fold as the outer test fold.
  3. On the remaining data, run an inner cross-validation with L folds for every candidate hyperparameter setting.
  4. Select the setting with the best mean inner score and refit it on the full outer training set.
  5. Score that refitted model once on the outer test fold.
  6. Repeat for every outer fold and average the outer scores.

The following table separates the roles of the two loops, which beginners often blur.

ElementInner loopOuter loop
PurposeChoose hyperparameters or modelEstimate generalization error
Data usedOuter training set onlyEntire dataset, fold by fold
Typical folds3 to 55 to 10
OutputOne selected configuration per outer foldMean and spread of test scores
Roles of the inner and outer loops

An important consequence is that different outer folds may select different hyperparameters. This is expected, because the outer loop evaluates the tuning procedure as a whole, not a single fixed model.

Why ordinary cross-validation becomes biased

Ordinary k-fold cross-validation gives a fair estimate only when no decisions depend on its results. Once dozens or hundreds of configurations are compared, the best score partly reflects random luck on those particular folds, a form of overfitting to the validation data.

The size of the bias grows with the number of candidates searched and shrinks with the size of the dataset. On small datasets with wide hyperparameter grids, studies of support vector machines and similar models have shown optimistic gaps of several percentage points of accuracy, enough to reverse conclusions when two methods are compared. On large datasets with a narrow search, the gap is often negligible.

DesignTuning dataReported scoreBias
Single train-test splitTraining partTest split scoreUnbiased but high variance
Ordinary cross-validation with tuningAll foldsBest mean fold scoreOptimistic
Train, validation and test splitValidation setHeld-out test scoreUnbiased, wastes data
Nested cross-validationInner folds onlyMean outer scoreApproximately unbiased
Evaluation designs and their bias

Key parameters and computational cost

The main cost of nested cross-validation is multiplicative compute. With K outer folds, L inner folds and C candidate configurations, the procedure trains roughly K multiplied by (L multiplied by C, plus one) models, so a 5 by 3 design with 50 candidates fits about 755 models.

ConfigurationModels per candidateTypical use
10 outer by 5 innerAbout 50Small tabular datasets, publications
5 outer by 3 innerAbout 15Default for most projects
Repeated 5 by 3About 15 per repeatReducing variance of the estimate
Leave-one-out outerN times inner foldsVery small clinical samples
Common configurations and their trade-offs

Practitioners reduce cost with randomized or Bayesian search in the inner loop, fewer inner folds and parallel execution across outer folds. Stratified k-fold cross-validation is used in both loops for classification so that class proportions stay stable, and grouped splits keep related samples, such as repeated measurements of one patient, inside a single fold.

When to use nested cross-validation

Nested cross-validation is most valuable when data is scarce and decisions are made on the data. For deep learning on millions of examples, a fixed held-out test set is usually sufficient and far cheaper.

SituationRecommended designReason
Fewer than a few thousand samplesNested cross-validationUses all data and avoids selection bias
Comparing algorithms for a paperRepeated nested cross-validationFair and stable comparison
Large dataset, expensive modelTrain, validation and test splitCompute would be prohibitive
Time series dataNested rolling-origin validationPreserves temporal order
Choosing an evaluation design

After nested cross-validation reports its estimate, the final production model is usually trained by running the inner tuning procedure once on the full dataset. The nested score describes the expected performance of that procedure, not of one specific outer-fold model.

Common mistakes and limitations

Most failures of nested cross-validation come from information leaking across loop boundaries. Every data-dependent step, including scaling, imputation, feature selection and resampling, must be fitted inside the inner training folds as part of a pipeline.

  • Preprocessing before splitting: fitting a scaler or feature selector on all data leaks test information.
  • Reporting inner scores: the inner best score is still biased and must not be published.
  • Ignoring groups or time: random splits of correlated samples inflate every estimate.
  • Reading the outer mean as exact: with small samples, the variance across outer folds can be large, so the spread should be reported too.

Understanding it simply

Nested cross-validation is a fair way to grade a model when the same data must be used for practice and for the exam. The inner loop is the practice round. There, the model tries many settings and keeps the best one.

The outer loop is the real exam. It uses questions the model never saw during practice. Because practice and exam never mix, the final grade is honest rather than flattering. Doing this takes more computing time, but the score can be trusted.

Applied in practice

A medical research group has 400 patient records and wants to predict which patients will respond to a treatment. They compare a regularized logistic regression with a gradient boosting model, each with a grid of about 40 hyperparameter settings. Ordinary cross-validation with tuning reports an AUC of 0.86 for gradient boosting.

The group then runs 5 outer by 3 inner nested cross-validation, using stratified, patient-grouped splits and keeping feature scaling inside the pipeline. The nested estimate for gradient boosting falls to an AUC of 0.79, while logistic regression reaches 0.80 with less variance across folds. The team selects the simpler model, reports the nested score with its spread in the publication and avoids an overstated performance claim that reviewers or a later external validation would likely have exposed.