Sub topic 15
Stratified and Iterative-Stratified Validation
This chapter assumes you know train/test splits, k-fold cross-validation, and the multiclass and multilabel target shapes from earlier chapters. It covers how to split data so that rare classes and rare labels appear in every fold.
Why plain random splits fail
A random split draws rows without looking at the target. With balanced classes this is fine. With a rare class, a fold can end up with very few examples of it, or none. The consequences:
- A class missing from the validation fold makes its recall undefined. scikit-learn warns and reports 0.
- A class missing from the training fold means the model never learns it.
- Fold scores swing widely, so you cannot trust the average.
Multilabel data makes this worse. A label that appears in 1% of rows may be absent from a whole fold, and label combinations are rarer still.
Stratified k-fold for multiclass
Stratification keeps the class proportions of the full dataset in every fold. In scikit-learn, use StratifiedKFold, or pass an integer cv to cross_val_score with a classifier, which stratifies by default.
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
y = np.array([0] * 90 + [1] * 8 + [2] * 2)
X = np.zeros((len(y), 1))
for name, splitter in (
("KFold", KFold(n_splits=2, shuffle=True, random_state=0)),
("StratifiedKFold", StratifiedKFold(n_splits=2, shuffle=True, random_state=0)),
):
print(name)
for _, val_idx in splitter.split(X, y):
print(" validation class counts:", np.bincount(y[val_idx], minlength=3))KFold can put both class-2 rows in one fold. StratifiedKFold puts one in each. Each class needs at least n_splits examples, or scikit-learn warns that the smallest class has too few members.
Why stratified k-fold breaks for multilabel
StratifiedKFold needs one class per row. A multilabel target is a multi-hot matrix, so scikit-learn raises an error for it. A common workaround is to stratify on the label powerset, meaning each distinct combination becomes one class. That fails when many combinations occur only once or twice, which is typical.
Iterative stratification
Iterative stratification, from Sechidis et al. (2011), balances each label individually and works with a multi-hot matrix. The algorithm:
- Compute how many positives of each label every fold should receive.
- Pick the label with the fewest remaining positives, because it is the hardest to place.
- Assign each row carrying that label to the fold that still needs that label most.
- Update the counts and repeat until every row is assigned.
Rare labels are placed first, while there is still freedom to spread them evenly. The iterative-stratification package provides this as MultilabelStratifiedKFold. Install it with pip install iterative-stratification.
import numpy as np
from iterative_stratification.iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from sklearn.datasets import make_multilabel_classification
from sklearn.model_selection import KFold
X, Y = make_multilabel_classification(
n_samples=500, n_features=10, n_classes=5, n_labels=2, random_state=0
)
splitters = {
"KFold": KFold(n_splits=5, shuffle=True, random_state=0),
"MultilabelStratifiedKFold": MultilabelStratifiedKFold(
n_splits=5, shuffle=True, random_state=0
),
}
for name, splitter in splitters.items():
ratios = [Y[val].mean(axis=0) for _, val in splitter.split(X, Y)]
spread = np.max(ratios, axis=0) - np.min(ratios, axis=0)
print(name, "label-frequency spread across folds:", spread.round(3))The printout shows, for each label, the gap between its highest and lowest positive rate across folds. A smaller gap means more even folds.
Common errors
- Stratifying only the final split. Use the stratified splitter inside cross-validation and hyperparameter search too.
- Tuning thresholds on the test fold. Pick per-label thresholds on validation data, then score once on untouched test data.
- Expecting exact balance. Iterative stratification is a heuristic. A label with fewer positives than folds cannot appear in every fold.
- Ignoring groups. If rows share a source, such as several images of one patient, stratification does not prevent leakage. Use a group-aware splitter.
Exercise
A multilabel dataset has a label with only 3 positive rows, and you run 5-fold cross-validation. Can iterative stratification put that label in every validation fold? What should you do about it?
Show answer
No. Three positives can cover at most three folds, so at least two validation folds have no positives for that label and its recall is undefined there. Either use fewer folds, collect more examples of the label, or merge it with a related label. Report that label's metric with caution.