TExcelTAD
Home › Training Mechanics, Evaluation & Model Improvement › Stratified and Group Cross-Validation

Stratified and Group Cross-Validation

Plain k-fold cross-validation assumes the rows are interchangeable: any row could land in any fold, and each row is an independent example of the future. Two common situations break that. When one class is rare, random folds get different numbers of it, and the fold scores swing for no reason. When rows come in groups (several scans of the same patient, many sessions of the same user, frames of the same video), a random split puts the same patient in training and validation, and the model is rewarded for recognising the patient instead of the disease. The fixes are stratified and group splits. Data Preparation shows the splitter API; this lesson measures what goes wrong without them.

Stratified k-fold

Stratification makes each fold keep the class proportions of the whole data set. With ncn_c examples of class cc and kk folds, every fold gets ⌊nc/k⌋\lfloor n_c/k \rfloor or ⌈nc/k⌉\lceil n_c/k \rceil of them.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import make_scorer, recall_score

X, y = make_classification(n_samples=200, n_features=8, n_informative=4, weights=[0.9], flip_y=0, class_sep=1.5, random_state=3)
print("positives:", int(y.sum()), "of", len(y))
model = LogisticRegression(max_iter=1000)
recall = make_scorer(recall_score, zero_division=np.nan)       # recall is undefined without positives
for name, cv in [("KFold", KFold(5, shuffle=True, random_state=1)),
                 ("StratifiedKFold", StratifiedKFold(5, shuffle=True, random_state=0))]:
    pos = [int(y[val].sum()) for _, val in cv.split(X, y)]
    rec = cross_val_score(model, X, y, cv=cv, scoring=recall)
    print(f"{name:16s} positives per fold {pos}  recall per fold {rec.round(2).tolist()}  mean {rec.mean():.3f}")
positives: 19 of 200
KFold            positives per fold [0, 3, 7, 6, 3]  recall per fold [nan, 0.33, 0.57, 0.67, 0.67]  mean nan
StratifiedKFold  positives per fold [3, 4, 4, 4, 4]  recall per fold [1.0, 0.5, 0.75, 0.25, 0.75]  mean 0.650

Only 19 of the 200 rows are positive. Shuffled KFold happens to give one fold no positives at all and another seven: the recall of the first fold is undefined (nan, so the mean is too; scikit-learn's default would silently report 0 instead), and the others are computed from 3 to 7 examples. StratifiedKFold puts 3 or 4 positives in every fold. The per-fold recalls still vary (0.25 to 1.0), because 4 positives is very few; stratification removes the variation caused by the split, not the variation caused by small numbers.

Use StratifiedKFold by default for classification; cross_val_score and GridSearchCV already do when you pass cv=5 with a classifier. For regression, the same idea can be applied to bins of the target (stratify on pd.qcut(y, 5) by hand).

Groups: the same patient on both sides

Suppose 40 patients each contribute 10 recordings. Every patient has their own "signature" (body size, sensor placement, voice), which shows in all ten recordings, and the label (disease or not) belongs to the patient. A model evaluated with random folds sees 8 or 9 of a patient's recordings in training and is asked about the rest: it can recognise the patient and copy their label. A new patient in the clinic has no recordings in the training data at all. Group k-fold keeps all rows of a group in the same fold, so each validation fold contains only unseen patients.

python · try it yourself
import numpy as np
from sklearn.model_selection import KFold, GroupKFold, cross_val_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier

rng = np.random.default_rng(0)
def make_patients(n_patients, start_id):
    sick = rng.random(n_patients) < 0.5                       # label per patient
    signature = rng.normal(0, 2.0, (n_patients, 6))          # strong per-patient offset, unrelated to the label
    X, y, g = [], [], []
    for p in range(n_patients):
        signal = 0.4 * sick[p] * np.r_[1, 1, 0, 0, 0, 0]       # weak real effect of the disease
        X.append(signature[p] + signal + rng.normal(0, 0.5, (10, 6)))
        y += [int(sick[p])] * 10; g += [start_id + p] * 10
    return np.vstack(X), np.array(y), np.array(g)

X, y, groups = make_patients(40, 0)                          # 400 recordings for development
X_new, y_new, _ = make_patients(40, 1000)                    # 40 completely new patients

for name, model in [("1-NN", KNeighborsClassifier(1)), ("random forest", RandomForestClassifier(200, random_state=0))]:
    leaky = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0))
    grouped = cross_val_score(model, X, y, cv=GroupKFold(5), groups=groups)
    new = model.fit(X, y).score(X_new, y_new)
    print(f"{name:13s} KFold {leaky.mean():.3f}   GroupKFold {grouped.mean():.3f}   new patients {new:.3f}")

shared = [len(set(groups[trn]) & set(groups[val])) for trn, val in GroupKFold(5).split(X, y, groups)]
print("patients in both training and validation, per GroupKFold fold:", shared)
1-NN          KFold 0.997   GroupKFold 0.490   new patients 0.537
random forest KFold 0.960   GroupKFold 0.395   new patients 0.542
patients in both training and validation, per GroupKFold fold: [0, 0, 0, 0, 0]

With random folds, 1-nearest-neighbour looks almost perfect (0.997): the closest recording to any validation recording is another recording of the same patient, with the same label. Grouped folds tell the truth, 0.490, close to the 0.537 on 40 brand-new patients and to the 0.5 of guessing. The random forest shows the same pattern (0.960 against 0.395 and 0.542). The disease effect in this simulation is real but weak next to the patient signatures, so neither model learned it; only the grouped estimate reveals that. With just 40 patients, the grouped scores are noisy too (0.395 is below chance by luck), which is an honest picture of how little 40 patients can tell you. The last line checks the splitter: no patient is ever on both sides.

What counts as a group

The group is the unit you will generalise to. Ask: "in production, will the model see new ___?" and put that word in the blank.

Data Group by
medical images, sensor recordings patient (or hospital, if the model must work in new hospitals)
user sessions, purchases, reviews user or customer
video frames, image crops, audio clips cut from a recording the source video or recording
sentences, paragraphs document or author
near-duplicate rows (augmented copies, the same product photographed twice) the original item
sales per store store, if new stores are the target

For grouped and imbalanced data, StratifiedGroupKFold keeps groups intact while trying to balance the classes across folds. LeaveOneGroupOut makes one fold per group, useful when there are few groups (for example 6 hospitals). When groups are also ordered in time, use time-based splits (Backtesting).

Pitfalls

  • Forgetting groups=. GroupKFold without the groups argument raises an error, but KFold with shuffled rows from grouped data runs silently and is optimistic.
  • Splitting augmented copies. Augment after splitting, and only the training part; otherwise variants of one image sit on both sides (Data Leakage).
  • Too few groups. With 10 patients and 5 folds, each fold scores 2 patients; the estimate is very noisy, and that is the truth about how much you know.
  • Stratification is not a cure for imbalance. It only makes folds comparable; the model still needs suitable metrics and possibly reweighting (Class Imbalance).

Practice

  1. A data set has 23 positives and 177 negatives. With StratifiedKFold(5), how many positives does each fold get?
Answer

23/5=4.623/5 = 4.6, so three folds get 5 and two get 4 (3⋅5+2⋅4=233 \cdot 5 + 2 \cdot 4 = 23).

  1. A face-verification data set has 50 photos each of 200 people. You want to know how the system works for people who never enrolled. Which split?
Answer

Group by person (GroupKFold with the person id), so validation people never appear in training. A random split would measure recognition of known faces, a different and easier task.

Test yourself

What does stratified k-fold guarantee?

  1. Each fold has the same class proportions as the whole data set (up to rounding)
  2. No group appears in two folds
  3. Folds respect time order
  4. The model is balanced

Recordings of the same patient appear in both training and validation folds. What is the usual effect?

  1. The score is pessimistic
  2. The score is optimistic: the model can recognise the patient instead of the disease
  3. No effect if the model is linear
  4. Training fails

A model will be used on customers who are not in the training data. What should be the group in GroupKFold?

  1. the transaction
  2. the customer
  3. the day
  4. the class label