Sub topic 15
Stratified and iterative-stratified validation
This chapter covers how to split data so that rare classes and rare labels appear in every fold. It assumes you know k-fold cross-validation, the multiclass and multilabel target shapes from earlier chapters, and per-class and per-label metrics. The code needs scikit-learn, NumPy and the iterative-stratification package (pip install iterative-stratification).
Why plain splitting fails on imbalanced targets
A random split treats every row the same. With a balanced target that is fine. With a rare class or label, a random split can leave a fold with very few positives, or none.
The effects are concrete:
- A test fold with zero examples of a class makes that class's recall undefined. scikit-learn reports 0.0 and warns, unless you set
zero_division. - A test fold with two examples gives a noisy per-class F1. Macro averages then swing between folds for reasons unrelated to the model.
- A training fold with no positives for a label leaves the model nothing to learn for that label.
Stratification means splitting so that each fold keeps roughly the class proportions of the full dataset. It reduces this variance. It does not create data. If a class has only 3 examples, a 5-fold split cannot put one in every fold.
Stratified k-fold for multiclass
For a multiclass target, StratifiedKFold does the job. It spreads each class's examples evenly across the folds.
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
rng = np.random.default_rng(0)
X = rng.normal(size=(300, 4))
y = rng.choice([0, 1, 2], size=300, p=[0.8, 0.15, 0.05])
def show_test_counts(splitter, name):
print(name)
for i, (_, test_idx) in enumerate(splitter.split(X, y)):
print(" fold", i, "test class counts:", np.bincount(y[test_idx], minlength=3))
show_test_counts(KFold(n_splits=5, shuffle=True, random_state=0), "KFold")
show_test_counts(StratifiedKFold(n_splits=5, shuffle=True, random_state=0), "StratifiedKFold")StratifiedKFold gives test counts for class 2 that differ by at most one across folds. Plain KFold gives counts that vary much more.
The same idea applies to a single hold-out split: pass stratify=y to train_test_split.
Two details matter in practice:
StratifiedKFoldtakesyas a 1-D vector of class labels. The call issplit(X, y), and it fails or misbehaves if you omity.- If a class has fewer members than
n_splits, scikit-learn warns that the least populated class is smaller than the number of splits. Treat that warning as a sign to reducen_splitsor merge classes.
Why StratifiedKFold does not work for multilabel
With a multilabel target, y is a matrix of 0s and 1s. StratifiedKFold rejects it, because it does not know how to stratify on several columns at once. There are three ways to get a stratified multilabel split.
- Stratify on one label. Pick the rarest or most important label and stratify on that column. The other labels get no guarantee.
- Stratify on the label powerset. Turn each row's label combination into one class, such as
"1,0,1,0,0", and runStratifiedKFoldon those. This fails when there are many label combinations. Most combinations occur once or twice, which triggers the least-populated-class warning, and the split no longer balances the individual labels. - Iterative stratification. Balance each label's positives across folds directly. This is the usual choice.
How iterative stratification works
Iterative stratification (Sechidis et al., 2011) is a greedy algorithm. It starts from the observation that rare labels are the hardest to place, so it handles them first.
- Count the positives for each label, and decide how many positives each fold should receive per label.
- Find the label with the fewest remaining positives, and take the examples that have it.
- Assign those examples one by one to the fold that still needs the most positives of that label. Break ties using the fold that needs the most positives overall, then at random.
- Update the remaining desired counts and repeat with the next rarest label, until every example is assigned.
The result is that rare labels are spread almost evenly. Common labels are balanced approximately, because they have plenty of examples to absorb the rounding.
Iterative stratification in code
The example below builds a multilabel target with two rare labels, then compares the positives per label in each test fold under plain KFold and MultilabelStratifiedKFold.
import numpy as np
from sklearn.model_selection import KFold
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
rng = np.random.default_rng(0)
X = rng.normal(size=(1000, 8))
probs = np.array([0.5, 0.3, 0.1, 0.03, 0.02]) # last two labels are rare
Y = (rng.random((1000, 5)) < probs).astype(int)
print("total positives per label:", Y.sum(axis=0))
def show_label_counts(splitter, name):
print(name)
for i, (_, test_idx) in enumerate(splitter.split(X, Y)):
print(" fold", i, "test positives per label:", Y[test_idx].sum(axis=0))
show_label_counts(KFold(n_splits=5, shuffle=True, random_state=0), "KFold")
show_label_counts(
MultilabelStratifiedKFold(n_splits=5, shuffle=True, random_state=0),
"MultilabelStratifiedKFold",
)The two rare labels have about 30 and 20 positives. Under KFold, the per-fold counts for those labels spread widely. Under MultilabelStratifiedKFold, they differ by about one.
MultilabelStratifiedKFold follows the scikit-learn splitter interface, so you can use it anywhere that accepts cv. For cross_val_score, materialize the splits as a list:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.multiclass import OneVsRestClassifier
cv = MultilabelStratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = OneVsRestClassifier(LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, Y, cv=list(cv.split(X, Y)), scoring="f1_macro")
print(scores.round(3))Here X is random noise, so the scores carry no meaning. The point is the call pattern. OneVsRestClassifier handles a label that has no positives in a training fold by predicting a constant, so the run does not crash.
What each splitter guarantees
| Splitter | Target | Balances | Main limitation |
|---|---|---|---|
| `KFold` | Any | Nothing | Rare classes can vanish from a fold |
| `StratifiedKFold` | Binary, multiclass | Class proportions | No multilabel support |
| `StratifiedGroupKFold` | Binary, multiclass | Class proportions, groups kept whole | Balance is approximate |
| `MultilabelStratifiedKFold` | Multilabel | Per-label positives, approximately | Ignores groups, does not preserve label combinations exactly |
Gotchas and edge cases
- Labels with fewer positives than folds. A label with 3 positives cannot appear in every one of 5 test folds. Reduce
n_splits, or accept that some folds have no examples for it. Report per-label metrics with a note about support (the number of positives). - Groups. If several rows come from the same patient, document or user, a split that separates them leaks information. Use
StratifiedGroupKFoldfor single-label targets. Iterative stratification does not support groups, so for multilabel data with groups you need a different approach, such as stratifying at the group level. - Stratify before any resampling. Oversampling or class weighting belongs inside the training fold only. If you oversample first and split afterward, copies of the same example land in both training and test sets, and the scores are inflated.
- Stratification applies to evaluation, not training balance. Each training fold is as imbalanced as the full dataset. Imbalance handling, covered in an earlier chapter, is a separate step.
- Tuning thresholds. Per-label thresholds should be chosen on validation data, never on the final test set. Use stratified inner folds for that search, so rare labels still have positives to tune against.
- Reproducibility. Set
shuffle=Truewith a fixedrandom_state. Without shuffling, folds follow row order, and data sorted by class or time produces odd splits. - Maintenance of libraries.
iterative-stratificationis small and works with the scikit-learn splitter interface. The olderscikit-multilearnpackage also offersIterativeStratification, but check that it installs against your scikit-learn version before depending on it.
Exercises
Exercise
A multiclass dataset has 200 rows and a class with 4 examples. You use StratifiedKFold with n_splits=5. What happens, and what are two reasonable responses?
Show answer
scikit-learn warns that the least populated class has fewer members than nsplits. One fold has no example of that class, so its per-class recall is undefined for that fold. Reasonable responses are to lower nsplits to 4 or fewer, or to merge the class into a related one. Collecting more examples is another option.
Exercise
Why is stratifying on the label powerset a poor choice for a multilabel dataset with 50 labels and 20,000 rows?
Show answer
With 50 labels there are many distinct label combinations, and most appear only once or a few times. Those tiny classes trigger the least-populated-class warning and cannot be spread across folds. The split also balances combinations instead of individual labels, so a rare single label can still be unevenly distributed. Iterative stratification balances each label directly.