Sub topic 5
Stratified train/test splits and cross-validation
This chapter assumes you can run a scikit-learn train/test split and a basic cross-validation loop. It also assumes you know what a binary classifier and a minority class are.
Why a random split can go wrong
A plain random split draws rows without looking at the labels. With a 5% positive rate, each draw is a small gamble. On a large dataset the split usually lands near 5%. On a small one, or when you cut the data into many folds, some parts can end up with far fewer positives than expected, or none at all.
That causes three problems:
- A test set with few positives gives a noisy recall or precision estimate.
- A validation fold with zero positives makes recall undefined, and scikit-learn warns or returns 0.
- Scores vary between folds because the class ratio varies, not because the model does.
Stratification fixes this. A stratified split keeps the class proportions of the full dataset, as closely as the row counts allow, in every part it creates.
Stratifying a train/test split
Pass the labels to the stratify argument of train_test_split. This reuses the synthetic data from the accuracy example.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(
n_samples=10000,
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:", round(y.mean(), 4))
print("train positive rate: ", round(y_train.mean(), 4))
print("test positive rate: ", round(y_test.mean(), 4))All three rates should agree to within a fraction of a percentage point.
Stratified cross-validation
StratifiedKFold applies the same idea to every fold. Each validation fold gets roughly the same share of positives as the training data. The helper below shows the positive rate in each validation fold for both splitters.
from sklearn.model_selection import KFold, StratifiedKFold
def fold_rates(splitter):
return [round(y_train[val].mean(), 4)
for _, val in splitter.split(X_train, y_train)]
print("KFold: ", fold_rates(KFold(n_splits=5, shuffle=True, random_state=0)))
print("StratifiedKFold:", fold_rates(StratifiedKFold(n_splits=5, shuffle=True, random_state=0)))The KFold rates drift from fold to fold. The stratified rates are nearly identical.
Scikit-learn already stratifies for you in one common case. If you pass an integer cv=5 to cross_val_score and the estimator is a classifier, it uses StratifiedKFold without shuffling. Passing the splitter explicitly is still better, because you control shuffle and random_state, and the intent is visible in the code.
Common errors
- Too many folds for the minority class.
StratifiedKFoldneeds at leastn_splitsexamples of every class. Otherwise it warns, or raises an error when the smallest class has fewer members thann_splits. With 12 positives, usen_splits=5, not 20. - Forgetting
stratifyon the final split. Stratifying only inside cross-validation leaves the held-out test set unprotected. - Stratifying a multi-class or grouped problem on the wrong thing. Stratify on the label you care about. If rows from one customer or patient must stay together, use
StratifiedGroupKFoldso groups are not split across folds. - Shuffling time-ordered data. Stratification assumes rows are exchangeable. For time series, use
TimeSeriesSplitand accept that the class ratio will vary. - Believing stratification fixes imbalance. It only makes evaluation fair. The training data is still imbalanced, so you still need the remedies in later chapters.
Choosing a score
Pair stratified folds with a metric that sees the rare class. Accuracy hides it, so use scoring="average_precision" or "f1" in cross_val_score. Report the mean and the spread across folds. A large spread with only a few dozen positives per fold is a warning that your estimate is uncertain.
Exercise
You have 8,000 rows with 40 positives. You plan to run StratifiedKFold(n_splits=10) and score recall on each validation fold. What problem will you face, and what would you change?
Show answer
Each validation fold holds only about 4 positives, so recall on a fold can only take values like 0, 0.25 or 0.5 and varies wildly. Use fewer folds, such as 5 (about 8 positives per fold), or repeat the cross-validation with RepeatedStratifiedKFold and average the scores. Keep the stratified test split as well.