Sub topic 5
Stratified train/test splits and cross-validation
This chapter assumes you know how to call train_test_split and cross_val_score, and that you have used scikit-learn estimators and pipelines. It covers how to split imbalanced data so the rare class appears in every subset, and how to cross-validate without noisy scores.
Why a plain random split is risky
A random split draws rows without looking at their labels. With balanced classes, each subset ends up with roughly the right mix. With a rare class, chance matters much more.
Suppose 400 rows contain 20 positives (5%). A random 25% test set holds 100 rows, so you expect 5 positives. The actual count follows a hypergeometric distribution, so 2 or 9 is entirely plausible. With 2 positives, recall can only take the values 0, 0.5 and 1. A single extra hit moves it by 50 points. With 0 positives, recall and precision are undefined.
The same problem hits cross-validation. If one fold has twice the positives of another, the per-fold scores differ because of the sampling, not because of the model. The standard deviation across folds then hides any real difference between two candidate models.
Stratification fixes this. A stratified splitter groups the rows by class label and divides each group separately. Every subset gets close to the same class proportions as the full data.
Stratified train/test split
Pass the label array to the stratify argument of train_test_split:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=4000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
print("overall positive rate:", y.mean())
print("train positive rate: ", y_train.mean())
print("test positive rate: ", y_test.mean())The three rates agree to within one row's worth of rounding. Without stratify=y, they would drift apart by a random amount.
Two points are worth keeping in mind:
- The test set stays imbalanced on purpose. Stratification preserves the real class ratio. That ratio is the one the model will meet in production, so metrics computed on it are honest. Never rebalance the test set.
- Fix the seed.
random_statemakes the split reproducible. Without it, results change between runs and comparisons between models become meaningless.
Seeing the difference across folds
The following script counts the positives in each test fold for an ordinary shuffled KFold and for StratifiedKFold:
from sklearn.datasets import make_classification
from sklearn.model_selection import KFold, StratifiedKFold
X, y = make_classification(
n_samples=400,
n_features=10,
n_informative=4,
weights=[0.95, 0.05],
flip_y=0,
random_state=0,
)
print("total positives:", int(y.sum()))
def positives_per_fold(splitter):
return [int(y[test].sum()) for _, test in splitter.split(X, y)]
print("KFold: ", positives_per_fold(KFold(5, shuffle=True, random_state=1)))
print("StratifiedKFold:", positives_per_fold(StratifiedKFold(5, shuffle=True, random_state=1)))With 20 positives and 5 folds, StratifiedKFold gives 4 positives per fold. KFold gives counts that scatter around 4. Try several seeds to see how large the scatter can get.
Stratified cross-validation
When you pass an integer cv=5 to cross_val_score or cross_validate and the estimator is a classifier with a binary or multiclass target, scikit-learn already uses StratifiedKFold without shuffling. Being explicit is still better, for two reasons. You control shuffling and the seed. The code also documents the intent.
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import RepeatedStratifiedKFold, cross_validate
model = LogisticRegression(class_weight="balanced", max_iter=1000)
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=3, random_state=42)
results = cross_validate(
model,
X_train,
y_train,
cv=cv,
scoring={
"average_precision": "average_precision",
"recall": "recall",
"precision": "precision",
},
)
for name in ["average_precision", "recall", "precision"]:
values = results["test_" + name]
print(f"{name}: {values.mean():.3f} +/- {values.std():.3f}")This example continues from the stratified split above. It cross-validates on the training portion only, and the test set stays untouched until the final evaluation.
RepeatedStratifiedKFold runs the stratified 5-fold procedure three times with different shuffles, giving 15 scores. With few positives, a single 5-fold run is noisy, and repeating it narrows the uncertainty on the mean. The 15 scores are not independent, because they reuse the same rows, so the standard deviation understates the real uncertainty. Use it to compare models rather than as a confidence interval.
Note the choice of metrics. Average precision, recall and precision describe the rare class. Plain accuracy would stay near 0.95 for any model, as the previous chapters showed.
Choosing the number of folds
Each fold's test portion holds about n_positives / n_splits positives. Fewer folds mean more positives per test fold but less training data per model. More folds mean the opposite.
| Positives in the training data | Sensible setup | Reason |
|---|---|---|
| Fewer than 30 | 3 folds, many repeats | Each test fold still has 10 or so positives |
| 30 to 200 | 5 folds, 3 to 10 repeats | A balance of bias and variance |
| Several hundred or more | 5 or 10 folds, 1 to 3 repeats | Fold sizes are no longer a bottleneck |
The minimum is a hard limit. If the rarest class has fewer members than n_splits, scikit-learn warns that the least populated class has too few members. If every class has fewer members than n_splits, it raises a ValueError. train_test_split with stratify raises a ValueError when a class has only one member. In both cases you need more data or a smaller n_splits. Do not respond by dropping stratification.
When rows are not independent: grouped data
Stratification assumes each row is an independent example. Often it is not. A hospital dataset may hold several visits per patient. A fraud dataset may hold many transactions per card. If rows from the same group land on both sides of a split, the model can memorise the group and the validation score is inflated.
StratifiedGroupKFold keeps every group entirely within one fold and tries to preserve class proportions at the same time:
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import StratifiedGroupKFold
X, y = make_classification(
n_samples=2000,
n_features=10,
n_informative=4,
weights=[0.9, 0.1],
flip_y=0,
random_state=0,
)
rng = np.random.default_rng(0)
groups = rng.integers(0, 200, size=len(y)) # 200 entities, about 10 rows each
cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=0)
for fold, (train_idx, test_idx) in enumerate(cv.split(X, y, groups)):
shared = set(groups[train_idx]) & set(groups[test_idx])
print(
f"fold {fold}: test positive rate = {y[test_idx].mean():.3f}, "
f"groups shared between train and test = {len(shared)}"
)The shared-group count is zero in every fold. The positive rate per fold is only approximately equal to the overall rate. Keeping groups whole makes an exact match impossible, and the fewer and larger the groups, the larger the deviation.
Common errors
- Stratifying only once, then reshuffling. If you split stratified, then call
cross_val_scorewith a plainKFoldon the same data, the cross-validation folds are no longer stratified. Check which splitter is in use. - Stratifying on the wrong array. Pass the label vector. Passing a feature column stratifies on the wrong thing and raises no error.
- Time-ordered data. For forecasting problems, a shuffled split lets the model train on the future. Use
TimeSeriesSplitinstead. It does not stratify, so check the positive count per fold yourself. - Using the test set for decisions. Choosing a model, a resampling method or a threshold based on test performance makes the test score optimistic. Make those choices with cross-validation on the training data.
- Resampling before splitting. Oversampling the whole dataset and then splitting puts copies or near-copies of the same row on both sides. The pipelines chapter covers this in detail. Stratified splitting is the first half of the safeguard, and applying resampling inside each training fold is the second.
Summary of the working model
- Hold out a stratified test set once, and do not look at it until the end.
- Run stratified (and repeated, if positives are few) cross-validation on the training portion for all model and strategy decisions.
- Add groups to the splitter when rows are related.
- Report metrics that focus on the rare class, along with the fold-to-fold spread.
Exercise
You have 12,000 rows with 40 positives. A colleague runs 10-fold cross-validation with StratifiedKFold and reports an average recall of 0.80 with a standard deviation of 0.25. Name two problems with this setup and suggest a change for each.
Show answer
First, each test fold has only about 4 positives, so each recall value can only be 0, 0.25, 0.5, 0.75 or 1, which explains the large spread. Use fewer folds (for example 4 or 5) so each test fold has 8 to 10 positives. Second, a single run of the splitter gives a noisy estimate, so use RepeatedStratifiedKFold with several repeats and average over all the scores. If the rows come from repeated entities such as patients, also switch to StratifiedGroupKFold so related rows stay together.