Reading history

Cross-Validation Strategies in Python: StratifiedKFold, GroupKFold and More

5 min read 5 views

Learn cross-validation strategies in Python: StratifiedKFold for class balance, GroupKFold to stop group leakage, and repeated cross-validation for steady scores.

Cross-validation only gives an honest score if each test fold looks like the new data your model will really meet. Plain KFold is not always enough. This lesson covers the splitters that fix the most common problems: rare classes, repeated measurements from the same person, and noisy scores.

In this lesson you will learn

  • Why sorted data breaks plain KFold
  • Keeping class balance with StratifiedKFold
  • Avoiding group leakage with GroupKFold
  • Getting steadier scores with repeated cross-validation
  • Which splitter fits which kind of data

You should know overfitting and cross-validation and train-test split.

Keeping Classes Balanced

Data files are often sorted, for example by date or by label. Here 20 emails are stored with the 4 spam emails at the end.

import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold

# 20 emails, sorted so the 4 spam ones come last
y = np.array([0] * 16 + [1] * 4)
X = np.zeros((20, 1))

for name, cv in [("KFold", KFold(n_splits=4)),
                 ("KFold shuffled", KFold(n_splits=4, shuffle=True, random_state=0)),
                 ("StratifiedKFold", StratifiedKFold(n_splits=4, shuffle=True, random_state=0))]:
    counts = [int(y[test].sum()) for _, test in cv.split(X, y)]
    print(f"{name:16} spam in each test fold: {counts}")

Output

KFold            spam in each test fold: [0, 0, 0, 4]
KFold shuffled   spam in each test fold: [2, 1, 1, 0]
StratifiedKFold  spam in each test fold: [1, 1, 1, 1]
  • Plain KFold cuts the rows in order. The first three test folds contain no spam at all, and the last contains all of it. In that last fold the model trains on zero spam emails, so it cannot learn what spam looks like.
  • Shuffling helps, but by chance one fold still gets no spam and another gets two.
  • StratifiedKFold puts exactly one spam email in each fold, matching the 20% spam rate of the full data.

For classification, scikit-learn’s cross_val_score already uses stratified folds when you pass a number like cv=5. You need StratifiedKFold yourself when you want shuffling, a fixed random seed, or the same folds across several models.

Group Leakage: The Hidden Trap

Sometimes several rows come from the same source: many heart readings from one patient, many photos of one person, many orders from one customer. If rows from the same patient land in both the training and test folds, the model can recognise the patient instead of learning the disease. The score looks great, then the model fails on new patients.

import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GroupKFold, KFold, cross_val_score

# 40 patients, 25 heart readings each. Each patient has a personal "signature"
# in the readings, and a diagnosis that only one reading partly reveals.
rng = np.random.default_rng(7)
patients, per = 40, 25
groups = np.repeat(np.arange(patients), per)
signature = rng.normal(0, 1, (patients, 6))
diagnosis = rng.integers(0, 2, patients)
X = signature[groups] + rng.normal(0, 0.3, (patients * per, 6))
X[:, 0] += 1.5 * diagnosis[groups]                 # the real signal
y = diagnosis[groups]

model = RandomForestClassifier(n_estimators=200, random_state=0)
rows = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0))
print(f"KFold (shuffled rows)   accuracy {rows.mean():.3f}")
by_patient = cross_val_score(model, X, y, cv=GroupKFold(5), groups=groups)
print(f"GroupKFold (by patient) accuracy {by_patient.mean():.3f}")

Output

KFold (shuffled rows)   accuracy 0.945
GroupKFold (by patient) accuracy 0.704
  • Each patient’s readings share a personal pattern (signature), and only one reading carries a real link to the diagnosis.
  • Shuffled KFold scores 94.5%. The forest learned to match each test reading to the same patient’s training readings and copy that patient’s label. That is memorising, not diagnosing.
  • GroupKFold keeps all readings from a patient in the same fold, so every test patient is new to the model. The honest score is 70.4%.
  • The gap of 24 percentage points is pure leakage. Reporting 94.5% would badly mislead anyone using the model on new patients.

Ask yourself: “When this model is used for real, will it see new patients, customers or devices?” If yes, split by that group.

Steadier Scores With Repeated Cross-Validation

With small datasets, the score can change noticeably depending on how the rows happen to fall into folds. RepeatedStratifiedKFold runs stratified cross-validation several times with different shuffles and averages all the results:

from sklearn.model_selection import RepeatedStratifiedKFold

cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=10, random_state=0)
scores = cross_val_score(model, X, y, cv=cv)     # 50 scores
print(scores.mean(), scores.std())

This costs more training time, but the average is more stable, and the standard deviation tells you how much the score could vary.

Choosing a Splitter

Your dataSplitter
Regression, rows independentKFold(shuffle=True)
Classification, rows independentStratifiedKFold(shuffle=True)
Several rows per person, device or customerGroupKFold or StratifiedGroupKFold
Rows ordered in timeTimeSeriesSplit (see time series forecasting)
Small dataset, noisy scoresRepeatedStratifiedKFold
Very small datasetLeaveOneOut, used with care, as it is slow and its scores vary a lot

Common Mistakes

  1. Shuffling rows when groups exist. Shuffling makes group leakage worse, not better.
  2. Shuffling time series. The model then trains on the future to predict the past.
  3. Tuning and reporting on the same folds. The best score from a grid search is optimistic. Keep a final test set, or use nested cross-validation.
  4. Forgetting the groups argument. GroupKFold needs it in cross_val_score(..., groups=groups).

Practice Exercises

Exercise 1. In cv2.py, check that no patient appears in both the training and test parts of any GroupKFold split.

Show answer
for train_idx, test_idx in GroupKFold(5).split(X, y, groups):
    shared = set(groups[train_idx]) & set(groups[test_idx])
    print(len(shared))          # 0 every time

Exercise 2. Each patient has a single diagnosis, but the two diagnoses might be unevenly spread across folds. Which splitter keeps groups together and also balances the classes?

Show answer

StratifiedGroupKFold. It keeps each group in one fold and tries to give every fold a similar class balance.

Frequently Asked Questions

How many folds should I use?

Five or ten is standard. More folds give each model more training data but take longer, and the fold scores become more correlated. With very little data, use repeated cross-validation instead of many folds.

Does group leakage only happen in medical data?

No. It happens with customers who place many orders, users with many sessions, photos of the same object, sensors sending many readings, and sentences from the same document.

Summary

  • Test folds should look like the real new data.
  • StratifiedKFold keeps class shares equal across folds.
  • GroupKFold stops the same person or device appearing in train and test.
  • Repeated cross-validation gives steadier estimates on small data.

Next: Quantile Regression and Prediction Intervals.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *