Learning outcomes

After this lesson, you will be able to:

Key question If two models achieve almost the same score on one split, does that mean they are equally reliable? What changes when they are evaluated on several different partitions?

1. Why cross-validation is useful

A single train/test split depends on which observations happen to enter each part. An unusually easy test set can inflate the score; a difficult one can lower it. Cross-validation repeats training and evaluation across several partitions so we can inspect sensitivity to sample composition.

A holdout estimates performance on one particular reserved sample. Cross-validation adds evidence about variation across plausible splits. It is useful when data is limited and when comparing models, but it does not create new independent observations or guarantee performance on future data.

All folds come from the same sample, and their training subsets overlap. Fold scores are therefore dependent. Their spread is a diagnostic of split sensitivity, not automatically a confidence interval or proof of statistical significance.

Cross-validationAn evaluation procedure that trains and validates a model across several partitions of one original sample.

2. The mechanics of k-fold

In k-fold cross-validation, the sample is divided into k non-overlapping parts called folds. At each iteration, one fold is used for validation and the remaining k−1 folds are used for training. The model is fitted again and the process repeats k times.

With k = 5, each validation step uses about 20% of observations and training uses about 80%. Every observation appears in validation exactly once. These are five fits of the same procedure, not five independent datasets.

A smaller k costs less computation but leaves less data in each training set. A larger k requires more fits and can increase sensitivity to individual observations. Choose k based on sample size, training cost, event rarity and computational budget.

Five iterations of k-fold cross-validationEach fold becomes validation once; the other four folds are used for training.Step 1Step 2Step 3Step 4Step 5Green — validation · blue — training
Each fold becomes validation once; the other four folds are used for training.

3. Mean score and variation

Let sᵢ be the metric on fold i. The mean across folds adds the scores and divides by k. It summarizes typical performance under the selected protocol, but it does not replace inspection of individual scores and confusion matrices.

For example, model A obtains Accuracy 0.91, 0.90, 0.92, 0.89 and 0.91. Model B obtains 0.95, 0.86, 0.92, 0.88 and 0.92. Their means are close, but B varies more from fold to fold. Investigate which groups and cases explain the variation.

Standard deviation describes observed variation. Do not automatically treat SD/√k as an exact standard error: training subsets overlap, so fold scores are dependent. Stronger inference needs an appropriate statistical design, repeated partitions or an independent external evaluation.

Mean metric across foldss̄ = (1 / k) Σᵢ₌₁ᵏ sᵢk is the number of folds; sᵢ is the metric on fold i. Add all fold scores and divide by their count. The mean summarizes typical performance under the selected protocol.
Mean score and variationSimilar mean scores can hide different fold-to-fold variation.Example fold scoresCircles — model A · squares — model B
Read the mean together with the standard deviation and investigate the source of variation.

4. Choosing a splitting strategy

Ordinary random k-fold is suitable when observations are independent and shuffling matches the deployment scenario. For imbalanced classification, stratified k-fold attempts to preserve approximate class proportions in every fold. This connects directly to the class-imbalance topic in lesson 1.5.5.

If multiple rows belong to the same person, device, company or source document, use a group-aware split. Keep all observations from one group together. Otherwise, the model may learn group-specific patterns in train and encounter the same group in validation, inflating the score.

For forecasting, random shuffling is usually inappropriate. A time-series split trains on the past and validates on a later period. Expanding or sliding windows should reproduce what information would actually be available at prediction time.

Splitting strategies for different data structuresThe splitting strategy must match independence, class proportions, groups and time.Random splitshuffleStratifiedclass ratioGroup-awarewhole groupsTime-awarepast → futureChoose the scheme from the data structure and deployment scenario.
The splitting strategy must match independence, class proportions, groups and time.

5. Preventing leakage inside each fold

Any transformation that estimates parameters from data must be fitted only on the current training fold. This includes imputation, scaling, feature selection, frequency encoding and resampling. Fit on train, then apply the fitted transformation to validation without fitting again.

The correct cycle is: create train and validation folds; fit preprocessing on train; transform both parts; fit the model on transformed train; calculate the metric on transformed validation. In Python, a Pipeline makes this sequence explicit. For SMOTE, use a pipeline that resamples only during the training step.

Scaling or selecting features on the full sample allows validation information to influence learned parameters. Applying SMOTE before splitting can place nearby original and synthetic points in different folds. This is leakage and produces an optimistic estimate. Validation and test should retain the natural class distribution.

6. Hyperparameter tuning and nested CV

If dozens of configurations are compared on the same validation folds and the best score is reported as an objective estimate, selection bias occurs: the winner was selected because it performed well on those data. The more configurations are tried, the greater the risk of adapting to validation noise.

Nested cross-validation separates two processes. The inner loop selects hyperparameters within the outer training portion. The outer loop evaluates the entire selection procedure on a fold that was not used for inner tuning. It evaluates the model-building and selection process, not just one fixed configuration.

Nested CV costs more computation. In many projects, a train/validation split for tuning and an independent test set for one final evaluation are sufficient. Nested CV is useful when data is limited and the selection bias from comparing many configurations needs to be assessed.

7. Interpreting stability and its limits

Compare models on identical folds, record the random seed and preserve the split strategy. Along with the mean, inspect standard deviation, individual scores, absolute error counts and important segments. For rare events, continue to examine prevalence, Precision, Recall and PR metrics.

A small spread does not guarantee reliability for new organizations, devices, time periods or rare segments if they are absent from the sample. All folds can be similar while missing important sources of distribution shift.

Cross-validation does not replace an independent test set when the protocol includes one. After deployment, monitor new data and performance as labels become available. Stability on historical folds is not a guarantee against data drift.

Standard deviation of fold scoresSD = √[Σᵢ₌₁ᵏ (sᵢ − s̄)² / (k − 1)]sᵢ is an individual fold score; s̄ is the mean; k is the number of folds. SD describes observed variation. Because folds are dependent, it is not automatically a confidence interval for future performance.

8. A practical research protocol

First define the independent unit of observation and the real deployment scenario. Choose stratified splitting to preserve class proportions, group-aware splitting for repeated observations from subjects, or time-aware splitting for future prediction. Fix the primary metric and model-selection rule before running the experiment.

Put all learned transformations and the estimator into one pipeline. Tune only within the training portion; use nested CV when needed. Save each fold's metric and report the mean, standard deviation, split strategy, random seed, sample size and experimental limitations.

In the report, record the selected scheme, the rationale for the grouping unit and time boundary, the preprocessing sequence, the metric, each fold score and the role of an independent test set. State the limits of the estimate and the conditions under which the conclusions may no longer apply.

Practical exercise

You have 12,000 maintenance records, with 6–20 records per device. The goal is to predict a failure in the next month. Define grouping by device, the time boundary, fold construction, preprocessing, metric and the role of a final test set. Explain why ordinary random k-fold may produce an overly optimistic estimate.

Expected outcome: a written evaluation protocol that justifies grouping and time boundaries, prevents leakage, selects a metric and reserves an independent final check.

Takeaway: Cross-validation reveals how much a result depends on the split, but it does not turn one sample into many independent experiments. Match the scheme to the data: stratified for class proportions, group-aware for related observations and time-aware for future prediction. Fit learned preprocessing inside each training fold, separate tuning from evaluation and preserve an independent test set for the final check. Lesson 1.5.7 introduces regression metrics MAE, MSE, RMSE and R².

Sources and further reading

  1. Kohavi, R. (1995). A Study of Cross-Validation and Bootstrap for Accuracy Estimation and Model Selection. IJCAI. A classic study of cross-validation schemes and model selection.
  2. Varma, S. & Simon, R. (2006). Bias in error estimation when using cross-validation for model selection. BMC Bioinformatics, 7, 91. Why model selection and performance estimation should be separated; motivation for nested CV.
  3. scikit-learn documentation: Cross-validation: evaluating estimator performance. Practical guide to k-fold, stratification, groups and time series.

Key terms

Cross-validation

An evaluation procedure that trains and validates a model across multiple partitions of one original sample.

Fold

One partition of the sample that is used as the validation part in turn.

Stratified k-fold

A splitting strategy that preserves approximately the same class proportions in every fold.

Group-aware split

A scheme that keeps related observations from one group in the same data partition.

Nested cross-validation

A two-level procedure: the inner loop tunes the model and the outer loop evaluates the complete selection process.

Self-check

Choose one answer for each question. An explanation appears after you check your answer.

Question 1

What happens in one k-fold iteration?

Question 2

Why calculate a metric across several folds?

Question 3

Which scheme suits independent observations in an imbalanced classification task?

Question 4

What should you do when many rows belong to the same device?

Question 5

Why fit preprocessing inside each training fold?

Question 6

What is nested cross-validation used for?

Question 7

How should standard deviation across k folds be interpreted?