TExcelTAD
Home › Data Preparation Toolkit: Cleaning to Leakage-Free Splits › K-Fold, Stratified K-Fold and Leave-One-Group-Out

K-Fold, Stratified K-Fold and Leave-One-Group-Out

A single hold-out split gives one number, and with a few hundred rows that number depends a lot on which rows happened to land in the test set. Cross-validation repeats the split: every row is used for testing exactly once and for training the rest of the time, and you report the mean and the spread of the scores. The basic cross_val_score call is in ML Cross Validation. This lesson is about choosing the splitter, because cross-validation inherits every rule of the split strategies: stratify rare classes, keep groups together, respect time.

K-fold from scratch

K-fold cross-validation shuffles the row indices once, cuts them into kk nearly equal folds, and runs kk rounds; in round ii, fold ii is the validation set and the other k−1k - 1 folds train the model.

python · try it yourself
import numpy as np

def kfold_indices(n, k, seed=0):
    idx = np.random.default_rng(seed).permutation(n)
    folds = np.array_split(idx, k)
    for i in range(k):
        val = folds[i]
        train = np.concatenate([folds[j] for j in range(k) if j != i])
        yield np.sort(train), np.sort(val)

for i, (tr, va) in enumerate(kfold_indices(10, 3)):
    print(f"round {i}: train={tr.tolist()}  validate={va.tolist()}")
all_val = np.concatenate([va for _, va in kfold_indices(10, 3)])
print("every row validated once:", sorted(all_val.tolist()) == list(range(10)))
round 0: train=[0, 1, 3, 5, 8, 9]  validate=[2, 4, 6, 7]
round 1: train=[0, 1, 2, 4, 6, 7, 8]  validate=[3, 5, 9]
round 2: train=[2, 3, 4, 5, 6, 7, 9]  validate=[0, 1, 8]
every row validated once: True

Common choices are k=5k = 5 or k=10k = 10. Larger kk trains on more data per round (less pessimistic) but costs more fits; leave-one-out (k=nk = n) is the extreme and is rarely worth it.

Stratified k-fold

Plain k-fold can put very different numbers of a rare class into each fold. StratifiedKFold keeps the class ratio in every fold, which makes the per-fold scores comparable. It is scikit-learn's default when you pass an integer cv to cross_val_score with a classifier.

python · try it yourself
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold

y = np.array([1] * 10 + [0] * 90)
X = np.zeros((100, 1))
for name, cv in [("KFold", KFold(5, shuffle=True, random_state=0)),
                 ("StratifiedKFold", StratifiedKFold(5, shuffle=True, random_state=0))]:
    counts = [int(y[va].sum()) for _, va in cv.split(X, y)]
    print(f"{name:<16} positives per validation fold: {counts}")
KFold            positives per validation fold: [3, 2, 4, 0, 1]
StratifiedKFold  positives per validation fold: [2, 2, 2, 2, 2]

With 10 positives in 100 rows, shuffled k-fold puts 3, 2, 4, 0 and 1 into the five validation folds; one fold has no positive at all, so its recall is undefined. Stratified k-fold gives exactly 2 per fold.

Group k-fold and leave-one-group-out

When rows come in groups (patients, customers, hospitals, recording sessions), the splitter must keep each group inside a single fold. GroupKFold spreads the groups over kk folds; StratifiedGroupKFold additionally tries to balance the classes; LeaveOneGroupOut (LOGO) makes one fold per group, which answers a sharper question: how well does the model do on a group it has never seen? That is exactly the question for a model trained on four hospitals and deployed at a fifth.

python · try it yourself
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import KFold, GroupKFold, LeaveOneGroupOut, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(0)
hospitals = ["north", "south", "east", "west", "river", "hill"]
prevalence = [0.2, 0.8, 0.3, 0.7, 0.5, 0.4]            # share of positive cases differs by site
X_parts, y_parts, g_parts = [], [], []
for name, prev in zip(hospitals, prevalence):
    n = 100
    y_h = (rng.random(n) < prev).astype(int)
    offset = rng.normal(0, 2.0, 4)                    # each site's machines read differently
    X_h = rng.normal(0, 1, (n, 4)) + offset
    X_h[:, 0] += 0.6 * y_h                            # the real, weak medical signal
    X_parts.append(X_h); y_parts.append(y_h); g_parts += [name] * n
X, y, groups = np.vstack(X_parts), np.concatenate(y_parts), np.array(g_parts)

model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))
for name, cv in [("KFold (rows shuffled)", KFold(5, shuffle=True, random_state=0)),
                 ("GroupKFold (3 folds)", GroupKFold(3)),
                 ("LeaveOneGroupOut", LeaveOneGroupOut())]:
    s = cross_val_score(model, X, y, cv=cv, groups=None if name.startswith("KFold") else groups)
    print(f"{name:<22} mean {s.mean():.3f}  std {s.std():.3f}")

logo = LeaveOneGroupOut()
scores = cross_val_score(model, X, y, cv=logo, groups=groups)
for (tr, va), s in zip(logo.split(X, y, groups), scores):
    print(f"  held-out hospital {groups[va][0]:<6} accuracy {s:.3f}")
KFold (rows shuffled)  mean 0.690  std 0.035
GroupKFold (3 folds)   mean 0.452  std 0.061
LeaveOneGroupOut       mean 0.442  std 0.150
  held-out hospital east   accuracy 0.640
  held-out hospital hill   accuracy 0.650
  held-out hospital north  accuracy 0.270
  held-out hospital river  accuracy 0.380
  held-out hospital south  accuracy 0.310
  held-out hospital west   accuracy 0.400

Six hospitals, 100 patients each, with different shares of positive cases and different machine offsets; the real medical signal is weak. Shuffled k-fold reports 0.690 with a small spread: rows of every hospital are in every training fold, so the model learns "this offset means hospital south, and most of south's patients are positive". That is a shortcut through the site, not medicine. Keeping hospitals together collapses the score to 0.452 (three group folds) or 0.442 (one hospital out at a time), below the 0.5 of guessing, and the per-hospital results range from 0.270 to 0.650. A model that looked good under the wrong splitter fails at every new site where the prevalence differs from what its neighbours suggest.

Time-series cross-validation

For ordered data, TimeSeriesSplit makes expanding windows: each round trains on everything up to a point and validates on the block right after it. The gap parameter leaves out rows between the two, so that lag features cannot bridge them.

python · try it yourself
import numpy as np
from sklearn.model_selection import TimeSeriesSplit

X = np.arange(20).reshape(-1, 1)
for i, (tr, va) in enumerate(TimeSeriesSplit(n_splits=4, test_size=3, gap=1).split(X)):
    print(f"round {i}: train 0..{tr.max():>2} ({len(tr):>2} rows)  gap {tr.max() + 1}  validate {va.min()}..{va.max()}")
round 0: train 0.. 6 ( 7 rows)  gap 7  validate 8..10
round 1: train 0.. 9 (10 rows)  gap 10  validate 11..13
round 2: train 0..12 (13 rows)  gap 13  validate 14..16
round 3: train 0..15 (16 rows)  gap 16  validate 17..19

Each validation block lies strictly in the future of its training data, with one row skipped. The training window grows, mimicking a model that is retrained as data arrives (max_train_size gives a sliding window instead).

Which splitter?

Data Splitter
independent rows, regression KFold(shuffle=True)
independent rows, classification StratifiedKFold
several rows per entity GroupKFold, StratifiedGroupKFold
few large groups (sites, devices), deployment to new ones LeaveOneGroupOut
ordered in time TimeSeriesSplit (with gap)
model selection and an honest estimate together nested cross-validation

Pitfalls

  • Preprocessing outside the folds: cross-validate a pipeline, so the scaler, imputer, encoder and sampler are refitted in every round (Pipelines).
  • Reporting only the mean: the spread across folds (and across groups) is part of the result; a model that fails at one site is not "on average fine".
  • Shuffling ordered data: KFold(shuffle=True) on a time series leaks the future.
  • Forgetting groups=: GroupKFold without groups raises an error, but KFold ignores them with only a warning, and your score is quietly the leaky one.

Practice

  1. With 5-fold cross-validation on 1,000 rows, how many rows train the model in each round, and how many models are fitted?
Answer

800 rows train and 200 validate in each round; 5 models are fitted (plus usually a final one on all 1,000 rows for deployment).

  1. In the hospital example, which number would you give a hospital that wants to use the model?
Answer

The leave-one-hospital-out results, including the worst site, not the shuffled k-fold mean. They measure performance at a hospital the model has never seen, and the spread warns that a new site can be much worse than average, so the model should be checked locally before use.

Test yourself

In k-fold cross-validation, how often is each row used for validation?

  1. Never
  2. Exactly once
  3. k times
  4. k - 1 times

Which splitter answers 'how well does the model work at a site it has never seen?'

  1. KFold
  2. StratifiedKFold
  3. LeaveOneGroupOut with sites as groups
  4. ShuffleSplit

What does TimeSeriesSplit guarantee?

  1. Equal class ratios in each fold
  2. Validation rows always come after the training rows
  3. Every row is validated once
  4. Groups stay together

Why did shuffled KFold score higher than GroupKFold on the hospital data?

  1. KFold uses more data
  2. Rows from the same hospital, with its machine offsets, were on both sides of the split
  3. GroupKFold is buggy
  4. KFold stratifies