Sub topic 6
Stratified splits for imbalanced classes
This chapter assumes you can run basic Python and scikit-learn, know what features and labels are, and have already used train_test_split. It covers why a plain random split can distort class proportions, and how stratification fixes that.
The problem with purely random splits
A random split picks rows by chance. With balanced classes, the proportions in each part stay close to the original. With imbalanced classes, chance matters more. Suppose 5% of 200 rows are positive, which is 10 rows. A random 20% test set holds 40 rows and should contain about 2 positives. It could easily contain 0, 1 or 5.
That variation causes two errors:
- A test set with no positives. Recall and precision for the rare class become undefined or meaningless.
- Proportions that differ between parts. The training set and test set describe different problems, so the score is noisy and harder to compare between runs.
What stratification does
A stratified split divides the data by class first. It then samples the same fraction from each class. Each part keeps the class proportions of the whole dataset, up to rounding.
Using stratify in scikit-learn
Pass the label array to the stratify argument. The breast cancer dataset has about 63% benign and 37% malignant samples. It is mildly imbalanced, which is enough to show the effect.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
print("all :", np.bincount(y) / len(y))
print("train:", np.bincount(y_train) / len(y_train))
print("test :", np.bincount(y_test) / len(y_test))All three lines print nearly identical proportions. Remove stratify=y and rerun with a few different random_state values. The test proportions will drift from run to run.
A heavily imbalanced example
The effect grows as the minority class shrinks. This example builds a synthetic dataset with 2% positives and compares many random splits against stratified ones.
import numpy as np
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
y = np.array([1] * 20 + [0] * 980)
X = rng.normal(size=(len(y), 3))
plain, strat = [], []
for seed in range(200):
_, _, _, yt = train_test_split(X, y, test_size=0.1, random_state=seed)
plain.append(yt.sum())
_, _, _, yt = train_test_split(
X, y, test_size=0.1, stratify=y, random_state=seed
)
strat.append(yt.sum())
print("positives in test, plain : min", min(plain), "max", max(plain))
print("positives in test, stratified: min", min(strat), "max", max(strat))The test set has 100 rows, so the expected count is 2 positives. Plain splitting gives a spread of counts, sometimes 0. Stratified splitting returns 2 every time.
Common errors
- Stratifying on the wrong thing. Pass the labels, not the features. Stratifying on
yis the usual choice. - A class with too few members. If a class has fewer rows than the number of parts it must be spread across, scikit-learn raises a
ValueError. With two parts, each class needs at least 2 rows. Merge or drop the tiny class, or collect more data. - Stratifying every split. If you create a validation set with a second
train_test_splitcall, passstratifythere too, using the labels of the data being split. - Assuming it fixes imbalance. Stratification only keeps proportions consistent. It does not give the model more minority examples. Evaluate with metrics such as recall, precision or F1, since accuracy can look high while the model ignores the rare class.
- Stratifying when rows are dependent. If several rows come from the same patient or user, stratification can still put them on both sides of the split. Chapters on grouped data cover that case.
Summary
Stratify on the label whenever classes are imbalanced or the dataset is small. It costs one argument and makes test scores more stable and meaningful.
Exercise
A dataset has 1,000 rows and 30 positives. You run train_test_split(X, y, test_size=0.2, random_state=1) and get a test set with 0 positives. What change prevents this, and roughly how many positives should the test set then contain?
Show answer
Add stratify=y. The test set has 200 rows, so it should contain about 6 positives (30 × 0.2), matching the 3% rate in the full data.