Sub topic 5
Stratified k-fold for classification
This chapter assumes you know plain k-fold cross-validation, scikit-learn's fit/predict API, and basic classification metrics such as accuracy. It covers why ordinary k-fold can mislead on classification data, how stratification fixes that, and where stratification stops helping.
The problem: folds that do not look like the data
Plain KFold splits row indices into k chunks and ignores the labels. With balanced classes and shuffled rows, each fold usually resembles the full dataset anyway. Two situations break this:
- Class imbalance. Suppose 5% of the samples are positive. A random fold of 20 samples can easily contain zero positives, and then recall, precision, and F1 are undefined for that fold.
- Ordered data. If the file is sorted by label, or the rows come in blocks, unshuffled
KFoldproduces folds with very different class mixes. A training fold can then miss a class entirely.
Both cases make the fold scores noisy for a reason that has nothing to do with the model. The spread you report mixes real model variability with accidental differences in class mix.
What stratification does
Stratified k-fold builds the folds so that each one has approximately the same class proportions as the full dataset. If 90% of the samples are class 0 and 10% are class 1, every test fold is about 90% class 0 and 10% class 1. Every training fold has the same property.
The procedure is:
- Group the sample indices by class label.
- Split each class's indices into k nearly equal parts.
- Build fold i by combining part i from every class.
The diagram shows this for two classes.
Seeing the difference
The next script builds a labeled array with 90 negatives followed by 10 positives, with the rows sorted by label. It prints the class counts in each test fold for both splitters.
import numpy as np
from sklearn.model_selection import KFold, StratifiedKFold
y = np.array([0] * 90 + [1] * 10)
X = np.zeros((len(y), 1))
splitters = {
"KFold": KFold(n_splits=5),
"StratifiedKFold": StratifiedKFold(n_splits=5),
}
for name, splitter in splitters.items():
print(name)
for fold, (train_idx, test_idx) in enumerate(splitter.split(X, y)):
counts = np.bincount(y[test_idx], minlength=2)
print(f" fold {fold}: test class counts = {counts}")KFold without shuffling cuts the sorted array into consecutive blocks. Its first four test folds contain only class 0 ([20 0]), and the last fold has [10 10]. A model scored on that last fold sees a very different problem from the other four. StratifiedKFold gives [18 2] in every fold.
Note that split takes y as a required argument. Stratification needs the labels, and if you call split(X) alone you get an error.
Using it in scikit-learn
You often get stratification without asking for it. When you pass an integer to cv in cross_val_score, cross_validate, or GridSearchCV, and the estimator is a classifier and y is binary or multiclass, scikit-learn uses StratifiedKFold without shuffling. For a regressor it uses plain KFold.
Relying on that default has two drawbacks. The splitter does not shuffle, so ordered data stays ordered inside each class. It is also invisible to someone reading your code. Passing the splitter explicitly is clearer and lets you set shuffle=True and random_state.
The next example is imbalanced (about 5% positives). It reports several metrics at once so you can compare them.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_validate
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=1000,
n_features=10,
n_informative=4,
weights=[0.95, 0.05],
flip_y=0,
random_state=0,
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
results = cross_validate(
model, X, y, cv=cv,
scoring=["accuracy", "balanced_accuracy", "f1"],
)
for metric in ["accuracy", "balanced_accuracy", "f1"]:
scores = results[f"test_{metric}"]
print(f"{metric:>18}: mean={scores.mean():.3f} std={scores.std():.3f}")Here a model that always predicts the majority class would score about 0.95 accuracy, so accuracy alone says little. balanced_accuracy (the mean of per-class recall) and f1 show whether the model finds the minority class. Stratification guarantees each fold has about 10 positives, so those per-class metrics are computed on comparable evidence in every fold. The exact numbers you see depend on your scikit-learn version.
Comparing the two splitters
| Property | `KFold` | `StratifiedKFold` |
|---|---|---|
| Uses labels to build folds | No | Yes |
| Class proportions per fold | Vary by chance | Close to the full dataset |
| Works for regression targets | Yes | No (needs discrete labels) |
| Default in `cross_val_score` for classifiers | No | Yes, when `cv` is an integer |
| Fold sizes | Differ by at most one | Can differ by a few samples |
Edge cases
Rare classes
Each class must have enough samples to be spread over the folds. Two cases matter:
- If the least populated class has fewer than
n_splitsmembers, scikit-learn issues a warning. Some test folds will then contain no member of that class. - If every class has fewer than
n_splitsmembers, it raises aValueError.
With 4 positives and n_splits=5, one fold has no positives, so any positive-class metric is undefined there. Reduce n_splits, collect more data, or use repeated cross-validation (a later chapter) to get stable estimates.
Multiclass targets
Stratification works for any number of classes. Each class is divided separately, so a dataset with classes at 70%, 20%, and 10% keeps those proportions in each fold. Very small classes are the usual trouble, for the reason above.
Fold sizes and exact proportions
Stratification is approximate. If a class has 22 samples and n_splits=5, the parts have sizes 5, 5, 4, 4, 4, so the per-fold proportions differ slightly. This is normal. When you average fold scores, a slightly smaller fold is weighted the same as a larger one, which has a negligible effect unless the data set is very small.
Shuffling and reproducibility
With shuffle=False, the samples of each class keep their original order within the class, so folds correspond to blocks of the original file. If the file has time or batch structure, that can matter, and shuffling may or may not be what you want (see the chapters on grouped and time-ordered data). With shuffle=True, set random_state to an integer so your results can be reproduced. Note that random_state has no effect when shuffle=False.
Regression targets
StratifiedKFold rejects continuous targets. If you want folds with similar target distributions for regression, a common workaround is to bin the target (for example with pandas.qcut or KBinsDiscretizer) and stratify on the bin labels, while still training on the original continuous target. This is a heuristic, not a built-in feature.
What stratification does not solve
Stratification balances only the label. It says nothing about other structure in the data. Three limits matter in practice:
- Related samples. If several rows come from the same patient, user, or device, a stratified split can still put one patient's rows in both train and test, which inflates scores. Use group-aware splitting. When you also need class balance,
StratifiedGroupKFoldcombines the two goals, with balance that is approximate. - Time order. A stratified split shuffles across time, so the model trains on the future. Use forward-chaining splits.
- Leakage from preprocessing. Fitting a scaler or feature selector on the full dataset before splitting leaks information regardless of how the folds are built. Put preprocessing inside a pipeline, as in the examples above.
Stratification also does not change the model's training distribution. Each training fold is still imbalanced, so techniques such as class weights or resampling are separate decisions. If you resample, do it only on the training portion of each fold, never before splitting, or duplicated minority samples will appear in both train and test.
Summary of when to choose it
Use StratifiedKFold as your default for classification, especially when classes are imbalanced, the dataset is small, or the metric depends on per-class counts. Use plain KFold for regression, or for classification where classes are balanced and the data are large enough that random folds are already representative. Switch to a group-aware or time-aware splitter when your data have that structure, because those concerns outrank class balance.
Exercise
You have a binary classification dataset with 200 samples, of which 8 are positive. You choose StratifiedKFold with n_splits=10. What problem will you meet, and what are two reasonable ways to handle it?
Show answer
The least populated class has 8 members, fewer than nsplits=10, so scikit-learn warns and at least two test folds contain no positives. Metrics such as recall, precision, and F1 are then undefined or misleading in those folds. Two fixes: lower nsplits (for example to 4, giving about 2 positives per test fold) or use repeated stratified k-fold with a small k so the estimate averages over many different splits. Collecting more minority-class samples also helps.
Exercise
A colleague writes crossvalscore(LogisticRegression(), X, y, cv=5) on a classification problem where the rows of X are sorted by label. They say they are using plain k-fold without stratification and without shuffling, so the folds are blocks of single classes. Is the claim correct? What would you change?
Show answer
Not quite. For a classifier with a binary or multiclass y, an integer cv means StratifiedKFold without shuffling, so each fold still has the right class proportions. The claim would be true for KFold. Still, the unshuffled order within each class is kept, so I would pass an explicit StratifiedKFold(nsplits=5, shuffle=True, randomstate=0) to make the behavior visible and reproducible.