Sub topic 5
Stratified k-fold for classification
This chapter assumes you know plain k-fold cross-validation, scikit-learn's fit/predict API, and metrics such as accuracy. It covers why plain k-fold can mislead on classification data and how stratification fixes it.
The problem with plain k-fold
Plain KFold cuts the data into folds without looking at the labels. With balanced classes and shuffled rows, each fold ends up with roughly the right class mix. With imbalanced classes, a fold can get far too few minority samples, or none. A fold with no positives makes recall and F1 undefined for that fold. Even when the metric is defined, the fold scores become noisy because the class mix differs between folds.
Without shuffling, the problem is worse when the file is sorted by label or by collection date.
What stratification does
Stratified k-fold splits each class separately, so every fold keeps approximately the class proportions of the full dataset. If 10% of the samples are positive, each test fold is about 10% positive, and so is each training set.
Seeing the difference
The next example uses 100 labels sorted so that all 10 positives come last. It counts the positives in each test fold.
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
y = np.array([0] * 90 + [1] * 10)
X = np.arange(100).reshape(-1, 1)
for name, splitter in [("KFold", KFold(n_splits=5)),
("StratifiedKFold", StratifiedKFold(n_splits=5))]:
counts = [int(y[test].sum()) for _, test in splitter.split(X, y)]
print(name, counts)The output is:
KFold [0, 0, 0, 0, 10]
StratifiedKFold [2, 2, 2, 2, 2]Plain KFold puts every positive in the last fold. The first four folds cannot measure recall, and the model never sees a positive while training on the last fold's complement. Stratified folds each hold two positives.
Using it in practice
Pass the splitter to cross_val_score through cv. Set shuffle=True and a random_state so the result is reproducible and does not depend on row order.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=500, weights=[0.9, 0.1], random_state=0)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
scores = cross_val_score(model, X, y, cv=cv, scoring="f1")
print(scores.round(3))
print(f"mean={scores.mean():.3f} std={scores.std():.3f}")Common errors
- Too few samples in a class. Each class needs at least
n_splitssamples. If the smallest class has fewer, scikit-learn warns that the stratification is approximate. If every class has fewer, it raises aValueError. Lowern_splitsor collect more minority data. - Expecting equal fold sizes. Folds can differ by a sample or two, because each class is divided on its own.
- Using it for regression.
StratifiedKFoldneeds discrete labels. Binning a continuous target is possible but is a manual step. - Treating it as a cure for dependence. Stratification only balances labels. If several rows come from the same patient or device, use a group-aware splitter. Stratification does not stop related samples from landing in both training and test sets.
- Reading accuracy on imbalanced data. Balanced folds make the estimate stable, but accuracy can still hide a model that ignores the minority class. Choose
f1,recall,balanced_accuracy, orroc_auc.
Exercise
A dataset has 200 samples, with 4 in the positive class. You call StratifiedKFold(n_splits=5) on it. What happens, and what are two ways to respond?
Show answer
The smallest class has 4 samples, fewer than the 5 splits, so scikit-learn warns that the least populated class has fewer members than nsplits, and one test fold will contain no positives. The fold-level recall or F1 for that fold is then undefined or zero. You can lower nsplits to 4 or fewer, so each fold gets at least one positive, or collect more positive samples. Repeated stratified k-fold with a small n_splits is another option.