Skip to content
AI.info

Evaluation

Cross-Validation, Nested Resampling, and Variance

Use cross-validation and resampling to estimate variability, compare pipelines, and avoid optimistic selection when data are limited.

By the end you can

Five scores are not five independent worlds

Cross-validation reuses observations across training folds. The resulting scores reveal sensitivity to partitioning, but they are correlated because models and datasets overlap. The method is valuable when a single holdout would waste scarce data or produce a fragile estimate. It does not manufacture new independent evidence from one dataset.

Ask it to, and it answers anyway. In 2006 Varma and Simon generated at least 1,000 simulated "null" datasets — 40 samples, 20 per class, 6,000 features, and no real difference between the classes at all. There was nothing in that data to learn. They tuned a shrunken-centroid classifier by 10-fold cross-validation and an SVM by leave-one-out cross-validation, then read off the cross-validation error of the tuned model. The tuned shrunken centroid reported a mean error of 37.8%. The tuned SVM reported 41.7%. The true error, measured on 20,000 independently generated test samples, was 50.0% — mean biases of -12.2 and -8.3 percentage points on pure noise.

The tail of that distribution is what a single project would actually see. Their abstract reports it: “Even though there is no real difference between the two classes for the "null" datasets, the CV error estimate for the Shrunken Centroid with the optimal parameters was less than 30% on 18.5% of simulated training data-sets. For SVM with optimal parameters the estimated error rate was less than 30% on 38% of "null" data-sets.” That 38% belongs to the abstract alone. The paper's own Table 1, in the column “Percentage of times training error<30%”, gives 22.2% for the SVM row. The shrunken-centroid figure does match: 18.5%. The remedy is in the same paper — “A nested CV procedure provides an almost unbiased estimate of the true error”.

Cross-validation does not estimate the error of the model you fitted. It estimates the average error of models fitted to other training sets you never saw. Bates and colleagues proved that in 2024 for the linear model fit by ordinary least squares, and showed empirically that the same phenomenon holds for most popular error estimates, including data splitting, bootstrapping and Mallow's Cp. The five scores are not five worlds. They are not even five looks at your model.

Figure

Two classifiers tuned on data with no signal at all, and how often the resulting cross-validation error still looked like a result.

Resampling measures dependence on the observed sample; it cannot replace a new population.

Steps

What happens inside a valid fold

Everything the pipeline learns must stay inside the training portion.

FigureProcess · 5 steps
  1. 1. Create the split

    Partition units using stratification, groups, time, or another valid rule.

  2. 2. Fit the pipeline

    Learn imputation, scaling, features, and model parameters on the training fold.

  3. 3. Predict the holdout

    Apply the frozen fold-specific pipeline to unseen cases.

  4. 4. Store predictions

    Preserve row identifiers, scores, labels, and fold membership.

  5. 5. Aggregate carefully

    Summarize fold metrics and inspect variation, slices, and failure cases.

Comparison

Choose folds that respect the evidence structure

Different iterators protect different assumptions. The choice of iterator can move the headline number further than the choice of model.

Split a wearable-sensor dataset by record and the error reads 2%. Split the same data by subject and it reads 27%. The dataset is public: 30 subjects, 10,299 records, 561 features each. In 2017 Saeb and colleagues split it both ways. Record-wise, the cross-validation error was already 2% with only two subjects and barely moved as subjects were added. Subject-wise, with no subject appearing on both sides of a fold, the error started at 27% with two subjects and settled at about 7-9% as subjects and folds grew. Same data, same algorithms, an order of magnitude between the reported errors: “Using both a publicly available dataset and a simulation, we found that record-wise CV often massively overestimates the prediction accuracy of the algorithms.” Their systematic review found the record-wise method in almost half of the retrieved wearable and smartphone clinical-prediction studies.

The effect reproduces. In 2021 Tougui and colleagues ran the comparison independently on Parkinson's-disease smartphone audio. One SVM pipeline scored 73.54%, 73.75% and 73.53% accuracy under stratified k-fold, leave-one-out and repeated stratified k-fold cross-validation. Under the group-wise versions of the same three procedures it scored 62.26%, 62.68% and 63.13%. Their conclusion: “The record-wise division and the record-wise cross-validation techniques overestimated the performance of the classifiers and underestimated the classification error.”

Blocking generalises beyond time to any dependence that travels with position. A random forest was trained to predict central-African aboveground forest biomass from 9 MODIS and 27 environmental variables, on inventory data covering more than 190,000 plots and about 11.8 million measured trees. Classical random 10-fold cross-validation reported R2 = 0.53 and RMSPE 56.5 Mg/ha. A spatial 44-fold cross-validation built on clusters of 150 km gave R2 = 0.14 and RMSPE 77.5 Mg/ha — barely better than a no-predictor null model at 82 Mg/ha. Ploton and co-authors published that in Nature Communications in 2020. The model did not change between those two numbers. The fold design did. Their abstract puts it plainly: “A standard nonspatial validation method suggests that the model predicts more than half of the forest biomass variation, while spatial validation methods accounting for SAC reveal quasi-null predictive power.” Stock found the same direction independently in a marine remote-sensing case study in 2025: “Depending on the model and error measure, 10-fold cross-validation underestimated prediction errors by 5% (RMSE of MBR) to 54% (APD of RFXY).”

FigureComparison · 4 columns

Stratified folds

Preserve approximate class proportions across folds.

  • Useful for classification
  • Does not prevent entity leakage
  • Can stabilize rare-class counts
  • Still requires valid units

Grouped folds

Keep all observations from one group together.

  • Protects entity independence
  • May create uneven prevalence
  • Tests unseen groups
  • Needs enough groups

Blocked time folds

Train on earlier periods and validate on later periods.

  • Respects chronology
  • Can reveal drift
  • Fewer exchangeable folds
  • Requires time-aware features

Repeated folds

Repeat valid partitions to study split sensitivity.

  • Adds resampling views
  • Increases compute
  • Scores remain dependent
  • Does not broaden the population

Visual

Why nested cross-validation exists

Hyperparameter search consumes validation evidence.

FigureLayers · 3 layers
  1. 01

    Outer test fold

    Estimates the full selection procedure on cases not used to choose configuration.

  2. 02

    Inner validation folds

    Compare hyperparameters, features, thresholds, or pipelines within outer training data.

  3. 03

    Inner training folds

    Fit candidate pipelines without seeing their validation portions.

Example

Non-nested selection can flatter the winner

Choose the hyperparameters once on the whole design set, then report the cross-validation error, and the number comes back too good. In 2010 Cawley and Talbot measured how much. They estimated the error of kernel ridge regression with a Gaussian RBF kernel by 10-fold cross-validation on thirteen benchmark datasets, under two protocols. In the external protocol the hyperparameters were chosen once on the whole design set. In the internal protocol the selection was repeated inside every fold. Their verdict: “The external protocol clearly exhibits a consistently optimistic bias with respect to the more rigorous internal cross-validation protocol, over all thirteen benchmarks.”

  • Thirteen for thirteen: choosing hyperparameters once on the whole design set never once produced a pessimistic estimate. The bias was statistically significant on eleven of the thirteen benchmarks — all but splice and twonorm.
  • Breast cancer, the widest gap: 26.280% under the external protocol against 27.470% under the internal one. A bias of 1.190 points, larger than the gap between competing algorithms on that benchmark.
  • Thyroid and titanic: 3.743% against 4.279%, and 22.167% against 22.487%. Biases of 0.536 and 0.320 points — small in absolute size, and still pointing the same way.
  • Noise selection: the winning score carries true performance plus the favourable random variation that made it win. Choosing features or an operating point outside the inner loop feeds more of that variation into the candidate.
  • Nested estimate: repeating the selection inside every fold prices the whole search rather than its eventual winner. That is the column to publish.

Analogy

Auditions judged by the same panel that writes the role

Auditions are watched by a panel that then rewrites the role to suit the most impressive performer and announces that it has independently verified the choice. Every step of that is defensible except the word independently.

Model selection is numerical, so the panel can be split in a way a theatre company cannot manage. An inner loop chooses. An outer loop reports. The evidence that shaped the choice never doubles as the proof that the choice was right.

Evaluate the selection procedure, not only its eventual winner.

Key idea

Fold standard deviation is not a universal confidence interval

Folds share data, so their scores are correlated. Reporting mean plus or minus one fold standard deviation can be descriptive, but it is not automatically a calibrated confidence interval for future performance.

There is no honest general formula for the variance of K-fold cross-validation, and that is a theorem rather than a shortage of effort. Bengio and Grandvalet proved it in 2004. Their Theorem 6 shows that “there exists no universal (valid under all distributions) unbiased estimator of the variance of K-fold cross-validation”, the obstacle being “the error correlations due to the overlap between training and test sets”. This is not a rounding error to be absorbed: “Our experimental section shows that in very simple cases, the bias incurred by ignoring the dependencies between test errors will be of the order of the variance itself.” Estimators that ignore the correlation can “grossly underestimate variance”.

An interval built to miss one time in ten missed 31 times in a hundred. Bates and colleagues showed that in a sparse l1-penalised logistic regression: n = 90 observations, p = 1,000 features, a Bayes misclassification rate of 20%, 1,000 replicates. Naive cross-validation intervals built for 10% miscoverage actually missed 31% of the time, and had to be widened by a factor of about 1.6 to reach the nominal level. Their abstract names the cause: “Because each data point is used for both training and testing, there are correlations among the measured accuracies for each fold, and so the usual estimate of variance is too small.” An interval advertised to miss one time in ten, and missing 31% of the time, is worse than no interval, because it is believed.

For uncertainty, use a method aligned with the analysis unit and target claim, such as cluster bootstrap, repeated external splits, or a model-based interval.

Variation across folds is evidence about split sensitivity, not a magic probability statement.

Use cross-validation as a diagnostic portfolio

Preserve out-of-fold predictions so you can inspect thresholds, calibration, subgroup behavior, and error concentration without averaging away structure.

When the final model is trained on all development data, its independent test result remains the cleanest release estimate, and cross-validation supports that decision without abolishing the need for protected evidence.

In regulated work that is not a preference but a published expectation. Ten Good Machine Learning Practice guiding principles for medical device development were published on 27 October 2021 by the US Food and Drug Administration, Health Canada and the UK Medicines and Healthcare products Regulatory Agency together. Principle 4 is “Training data sets are independent of test sets”, and it reads: “Training and test datasets are selected and maintained to be appropriately independent of one another. All potential sources of dependence, including patient, data acquisition and site factors are considered and addressed to assure independence.” Principle 8 requires performance evidence generated independently of the training data. The list in principle 4 — patient, data acquisition, site — is the grouped-and-blocked fold argument written out by three regulators. Independence has to be engineered into the split, one source of dependence at a time, and then evidenced on data the development loop never touched.

The most useful artifact is often the set of out-of-fold predictions, not the mean score alone.

Key takeaways