Cross-Validation

Using k-fold, stratified, group and time-series cross-validation to get stable performance estimates and compare models fairly.

Intermediate · about 4 hours · difficulty 2/5

Learn first: Evaluation Metrics

A single validation split gives a noisy estimate. Cross-validation trains and evaluates on several different splits and averages the scores, giving both a better estimate and a sense of its variance.

Variants

  • KFold: split into k folds, each serves once as validation. k = 5 or 10 is typical.
  • StratifiedKFold: preserves class balance; default for classification.
  • GroupKFold / StratifiedGroupKFold: keeps related rows together.
  • TimeSeriesSplit: expanding windows that always validate on later data.
  • Repeated CV: repeats with different shuffles for small datasets.

Using it well

  • cross_val_score and cross_validate in scikit-learn; always pass a pipeline so preprocessing is refit in each fold.
  • Look at the standard deviation across folds, not only the mean. A 0.2% improvement inside a 1% spread is noise.
  • Nested CV gives an unbiased estimate when you also tune hyperparameters (inner loop tunes, outer loop evaluates).
  • Keep a final holdout test set anyway for one last check.

Good enough to move on when you can pick the right CV splitter for a problem's structure and report mean and spread of the metric.

Key concepts

  • k-fold and stratified k-fold
  • Group k-fold
  • Time series split
  • Reading fold variance
  • Nested cross-validation

Mini project

Compare three models on the UCI Wine Quality dataset using repeated stratified 5-fold CV, and plot score distributions per model as box plots to judge whether differences are real.

Check yourself

Why must scaling and imputation happen inside each CV fold rather than once before cross-validation?

Free resources