Sub topic 6
Stratified splits for imbalanced classes
This chapter assumes you can run train_test_split and know what a train/test split is for. It also assumes you know the basics of classification metrics such as accuracy, precision and recall. The first half of the chapter explains why a plain random split can fail on skewed labels. The second half covers the edge cases that cause errors in practice.
The problem with plain random splits
A random split picks rows without looking at their labels. With balanced classes this is fine, because any large random sample looks like the whole dataset. With a rare class, chance matters much more.
Suppose 3% of 1,000 rows are positive. A test set of 200 rows should hold about 6 positives. A random draw can easily give 2 or 11. Two things go wrong:
- The test score becomes noisy. Recall computed from 2 positives can only be 0, 0.5 or 1.0.
- The training set and test set can have different class ratios, so the two scores are not measured on comparable data.
A stratified split fixes the second problem and reduces the first. Stratification means the split is done separately inside each class, so every part receives roughly the same fraction of each class as the full dataset.
Seeing the difference
The code below creates a dataset with about 3% positives. It then splits it five times with different seeds, once with plain random sampling and once with stratify=y, and counts the positives in each test set.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=1000, weights=[0.97, 0.03], flip_y=0, random_state=0
)
print("positives overall:", y.sum())
for seed in range(5):
_, _, _, y_plain = train_test_split(
X, y, test_size=0.2, random_state=seed
)
_, _, _, y_strat = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=seed
)
print(seed, "plain:", y_plain.sum(), "stratified:", y_strat.sum())The plain column changes from seed to seed. The stratified column stays at the expected count, about 6 in a test set of 200. Stratification does not make the split deterministic by itself. The random_state argument still decides which rows are chosen. Stratification only fixes how many rows come from each class.
How the stratified split works
train_test_split with stratify=y uses StratifiedShuffleSplit internally. For each class, it computes how many rows should go to the test set, then samples that many from that class. Rounding means the counts are not always exact, but they differ from the ideal by at most one row per class.
The stratify argument takes the array of labels. It does not have to be y itself. Any array with one entry per row works, and the entries define the strata (the groups that are split separately).
flowchart TDDo not use the block above. The diagram follows.
Stratified cross-validation
The same idea applies to cross-validation. StratifiedKFold makes each fold keep the overall class ratio. cross_val_score uses it by default for classifiers when you pass an integer cv. Passing it explicitly lets you set shuffle and random_state.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
StratifiedKFold,
cross_val_score,
train_test_split,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=1000, weights=[0.97, 0.03], flip_y=0, random_state=0
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for fold, (_, val_idx) in enumerate(cv.split(X_train, y_train)):
print("fold", fold, "positives in validation part:", y_train[val_idx].sum())
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000, class_weight="balanced"),
)
scores = cross_val_score(model, X_train, y_train, cv=cv,
scoring="average_precision")
print("CV average precision:", np.round(scores, 3))Each validation part holds about the same number of positives, so the five scores are comparable. The scaler sits inside the pipeline, so it is refit on the training part of each round. The scoring choice matters as well. With 3% positives, a model that always predicts the majority class gets 97% accuracy. Use a metric that reflects the rare class, such as average precision, F1 or recall.
What stratification does not do
Stratification changes how rows are assigned to parts. It does not change the class balance of the data.
- The training set is still imbalanced, with the same ratio as the original. If the model needs help with the rare class, use class weights or resampling, and apply any resampling to the training part only.
- The test set should keep the natural ratio. Oversampling the test set produces scores that do not describe real use.
- Stratification does not protect against leakage. Duplicate or near-duplicate rows can still land on both sides of the split.
- Stratification does not guarantee a good estimate. A test set with 6 positives still gives a very uncertain recall. If positives are that scarce, prefer cross-validation, which tests on every positive once, and report the spread across folds.
Edge cases and errors
A class with too few rows
Stratified splitting needs at least two rows in every class, so one can go to each side. A class with one member raises a ValueError.
import numpy as np
from sklearn.model_selection import train_test_split
X = np.arange(21).reshape(-1, 1)
y = np.array([0] * 20 + [1])
try:
train_test_split(X, y, test_size=0.2, stratify=y, random_state=0)
except ValueError as err:
print("ValueError:", err)Your options are to collect more data for that class, merge it into a related class, or drop it from the evaluation. Do not silently switch to an unstratified split, because that hides the fact that the class cannot be evaluated.
StratifiedKFold has a similar limit. It needs at least n_splits members in each class to place one in every fold. With fewer, scikit-learn raises an error when the smallest class has fewer members than n_splits, and warns when some folds would lack the class. Lower n_splits or merge classes.
Test set smaller than the number of classes
When stratifying, the test set must have at least as many rows as there are classes. With 10 classes, a test set of 8 rows cannot hold one of each. This tends to appear with small datasets and small test_size values.
Continuous targets
Regression targets have no classes, so stratify=y fails or produces one stratum per unique value. Bin the target into quantiles first and stratify on the bins. This keeps the target distribution similar in both parts, which matters when the target is skewed.
import numpy as np
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 3))
y = rng.lognormal(mean=0.0, sigma=1.0, size=500)
edges = np.quantile(y, [0.2, 0.4, 0.6, 0.8])
y_bins = np.digitize(y, edges)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y_bins, random_state=42
)
print("train median:", round(float(np.median(y_train)), 3))
print("test median: ", round(float(np.median(y_test)), 3))The bins are used only to assign rows. The model still trains on the original continuous y.
Several attributes at once
Sometimes the label is not the only thing that must stay balanced. You may also want an equal share of each data source or region in every part. Build a combined key and stratify on it, for example key = y.astype(str) + "_" + source. Every combined stratum needs at least two rows, so the number of strata can grow past what the data supports. If it does, stratify on the label alone and check the other attribute afterwards.
Multi-label targets
stratify expects one label per row. A row with several labels at once has no single class, so scikit-learn cannot stratify it directly. Combining the label set into a single key works only when the combinations are few. Otherwise, use a dedicated iterative stratification library.
Grouped data
If several rows come from the same patient, user or device, stratifying by label does not keep them together, and the same group can appear on both sides. Use StratifiedGroupKFold when you need both group separation and approximate class balance. The balance is only approximate, because whole groups must move together.
Quick reference
| Situation | Approach |
|---|---|
| Imbalanced class labels | `train_test_split(..., stratify=y)` |
| Cross-validation on class labels | `StratifiedKFold(shuffle=True, random_state=...)` |
| Continuous target | Bin into quantiles, stratify on bins |
| Label plus another attribute | Stratify on a combined key |
| Class with one row | Collect data, merge, or drop |
| Groups plus classes | `StratifiedGroupKFold` |
Exercise
A dataset has 500 rows, and 10 are positive. You use traintestsplit with test_size=0.2 and stratify=y. About how many positives land in the test set, and why is a recall score from that test set still unreliable? What would you do instead to estimate recall?
Show answer
About 2 positives land in the test set (20% of 10). Recall from 2 cases can only be 0, 0.5 or 1.0, so one prediction changes it by 50 points. Stratification keeps the ratio right but cannot create more positive cases. Use stratified cross-validation (for example StratifiedKFold with 5 splits) so every positive is tested once, and report the mean and spread of the fold scores. Also consider collecting more positive examples.
Exercise
You call traintestsplit(X, y, test_size=0.2, stratify=y) and get a ValueError saying the least populated class has only 1 member. Give two valid fixes and one fix you should avoid.
Show answer
Valid fixes: collect more examples of that class, or merge it with a related class (or drop it from the evaluation if that suits the task). A fix to avoid: removing stratify=y so the call succeeds, because that hides the problem. The rare class may then end up entirely in training or entirely in the test set, so it cannot be evaluated properly.