Stratified k-fold cross-validation

Also known as: stratified cross-validation

On this page 7

Stratified k-fold cross-validation is a resampling procedure that divides a labeled dataset into k folds of roughly equal size while keeping the class proportions of every fold close to those of the full dataset. In model evaluation, it is the standard way to estimate how a classifier will generalize when classes are unevenly represented, because each training and validation split reflects the same label distribution.

The method is a refinement of ordinary k-fold cross-validation. The model is trained k times, each time on k minus one folds, and scored on the remaining fold; the k scores are then averaged. Stratification does not change this loop. It only changes how rows are assigned to folds, which reduces the variance of the estimate and prevents folds that contain few or no examples of a rare class.

How stratified folds are built

Stratified fold assignment works class by class. The rows of each class are shuffled, if shuffling is enabled, and then dealt out across the k folds in turn, so every fold receives about one k-th of each class. The folds are then combined into training and validation splits exactly as in plain k-fold.

The table below traces the assignment for a binary dataset of 1,000 rows with a 10% positive rate and k set to 5.

FoldRowsPositive rowsNegative rows
Fold 120020180
Fold 220020180
Fold 320020180
Fold 420020180
Fold 520020180
Fold composition with five stratified folds

With random, unstratified splitting, the number of positives per fold would fluctuate, typically by several rows in either direction. On small or highly imbalanced datasets that fluctuation can leave a fold with almost no minority examples, making recall, precision and the F1 score for that fold unreliable or undefined.

Choosing k and other settings

The value of k controls a bias and variance trade-off in the performance estimate. Larger k trains on more data per round, which lowers pessimistic bias, but it increases computation and makes the fold scores more correlated with one another.

SettingCommon valuesWhat it affects
Number of folds (k)5 or 10Training size per round, run time, estimate variance
ShufflingEnabled with a fixed seedRemoves ordering effects; seed makes runs reproducible
Repetitions1 to 10 repeatsAveraging repeats lowers variance of the final score
Minimum class countAt least k rows per classBelow this, some folds lack a class entirely
Scoring metricF1, balanced accuracy, AUCShould match the cost of errors in the task
Effect of the main settings

A practical rule is that every class needs at least k members; common libraries warn or fail when a class is smaller than the number of folds. For very rare classes, reducing k or using repeated stratified k-fold with a smaller k gives more stable results than forcing ten folds.

Comparison with other validation schemes

Stratified k-fold is one member of a family of resampling methods, and the correct choice depends on the structure of the data rather than on habit. The comparison below covers its closest relatives.

SchemeHow splits are formedBest suited for
Plain k-foldRandom contiguous or shuffled blocksRegression and balanced classification
Stratified k-foldFolds preserve class proportionsImbalanced or small classification datasets
Group k-foldAll rows of one group stay in one foldRepeated measurements of patients, users or devices
Stratified group k-foldKeeps groups intact and balances classes approximatelyGrouped data with imbalanced labels
Leave-one-outEach single row is a validation foldVery small datasets; high variance
Time series splitTraining always precedes validation in timeForecasting and any temporally ordered data
Holdout splitOne fixed train and test partitionVery large datasets or quick checks
Stratified k-fold and related schemes

Stratification is not a substitute for grouping or temporal ordering. If the same customer appears in both training and validation folds, the estimate is optimistic regardless of how balanced the classes are, because the model partly recognizes individuals rather than learning general patterns.

Using it correctly in a modeling workflow

The most important rule is that every data-dependent step must happen inside the folds. Scaling, feature selection, target encoding and oversampling such as SMOTE must be fitted on the training part of each split only, typically by wrapping them in a pipeline that the cross-validation loop refits each round.

  • Keep a separate final test set untouched for the last, unbiased evaluation.
  • Use nested cross-validation when hyperparameters are tuned, so the tuning does not inflate the score.
  • Report the mean and standard deviation of fold scores, not only the mean.
  • For regression, stratify on binned target values when the target distribution is skewed.
  • For multilabel problems, use iterative stratification, which balances many labels at once.

The fold scores also carry diagnostic value. A wide spread between folds suggests that the dataset is small, that a few unusual rows dominate some folds, or that the model is unstable, all of which deserve investigation before deployment.

Common mistakes and their consequences

Most problems with stratified cross-validation come from data leakage or from applying it to data whose structure it ignores. The table lists the typical errors.

MistakeConsequenceRemedy
Oversampling before splittingSynthetic copies leak into validation foldsResample inside each training fold
Ignoring groupsOverly optimistic scoresUse stratified group k-fold
Shuffling time seriesFuture information trains the modelUse a time-ordered split
Using accuracy on rare classesHigh score from predicting the majorityUse F1, recall or balanced accuracy
Tuning and reporting on the same foldsInflated final estimateApply nested cross-validation
Frequent errors and remedies

In simple terms

To test a model fairly, data is split into several equal parts. The model learns from most parts and is tested on the one left out. This repeats until every part has been the test once.

Stratified means each part gets a fair share of every category. Imagine dealing a deck of cards so that each player gets the same mix of suits. If one category is rare, every test still includes some of it. That makes the final score more trustworthy.

A practical example

A hospital analytics team builds a model to flag patients at risk of readmission within 30 days. Its dataset has 4,000 discharge records, of which only 8% are readmissions, about 320 cases. With plain five-fold splitting, one fold in a trial run contained just 49 positives and another 78, and recall swung between 0.52 and 0.71.

The team switches to stratified five-fold cross-validation, repeated three times with different seeds, and keeps each patient’s records in a single fold. Every fold now holds about 64 readmissions. Recall settles at 0.63 with a standard deviation of 0.03, a figure the clinical committee can rely on when deciding whether the model is ready for a pilot.