Stratified Sampling
Stratified sampling controls how groups are represented in machine learning datasets, from train-test splits to evaluation of rare classes.
Stratified sampling divides a dataset into nonoverlapping groups called strata and draws examples from each group. In machine learning, strata can be class labels or capture conditions such as lighting. Sampling within strata lets you control how much of each group appears in a subset instead of leaving that mix to a single draw from the full dataset.
In survey statistics, the same method samples from predefined population groups to estimate population characteristics.
How Stratified Random Sampling Works#
First, define the sampling unit, such as an image, and assign each unit to exactly one stratum. Decide how many units to draw from each stratum. Stratified random sampling selects those units at random within each stratum, and the combined result is a stratified random sample. Simple random sampling draws from the entire dataset, so group counts can vary. In cluster sampling, the design instead selects some clusters and observes all or some units within them.
Proportional allocation gives each stratum roughly the same share of the sample as it has in the source dataset. Multiply the total sample size by the stratum's share, then round to whole counts that sum to the requested total. Disproportionate allocation changes those shares deliberately. Including more examples from a rare group in a dedicated evaluation set gives you more observations for measuring that group. To estimate overall classification accuracy, combine the stratum accuracies using the known shares of the target population as weights. In his 1934 paper, Jerzy Neyman formalized an allocation that assigns more of a fixed sample to larger, more variable strata when per-unit sampling costs are equal.
Stratified Train-Test Splits in Python#
In single-label image classification, each image has one ground-truth label, so classes form natural strata. In a chest X-ray classification study, Shenouda and colleagues used stratified sampling to maintain a 15.5% share of COVID-positive patients across the training, validation, and test splits of a 9,860-patient dataset.
With scikit-learn's bundled handwritten digits, passing class labels to train_test_split keeps class proportions close to those of the full dataset. For cross-validation, StratifiedKFold applies the same principle across folds.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
images, labels = load_digits(return_X_y=True)
# Use digit labels to preserve class proportions in the holdout.
_, _, _, test_labels = train_test_split(images, labels, test_size=0.2, stratify=labels, random_state=42)
full_pct = 100 * np.bincount(labels) / len(labels)
test_pct = 100 * np.bincount(test_labels) / len(test_labels)
for digit, (full, test) in enumerate(zip(full_pct, test_pct)):
print(f"Digit {digit}: full {full:.1f}%, test {test:.1f}%")The 360-image holdout contains all ten digits, each close to its share in the full dataset. Stratification preserves the existing class mix here. Rebalancing changes that mix, for example by oversampling rare classes in the training data after splitting.
When a classification dataset contains one folder per class and no train folder, Ultralytics YOLO uses its classification split utility to shuffle images within each class and create an approximately 80/20 training and validation split. Whole-image rounding determines the exact counts.
Stratification With Overlapping Labels and Shared Sources#
An object detection image can contain several classes, so class labels alone do not form disjoint strata. Multilabel iterative stratification assigns whole images to splits while aiming to preserve each label's frequency. Image counts and annotation counts reveal different gaps: many boxes for one class can come from very few images.
Shared sources create a separate constraint. Near-identical frames across splits can cause data leakage and inflate validation scores. A frame-overlap audit of the dataset below found training near-twins for 17 of 23 validation images. The audit compared 32 × 18 grayscale thumbnails and counted pairs with a mean absolute pixel difference below 5 on a 0–255 scale.
When evaluation targets unseen clips, each clip stays in one split. For single-label cross-validation with shared sources, StratifiedGroupKFold keeps groups intact while approximating class proportions.
flowchart TD
A{"Do examples share a source?"}
A -->|Yes| B["Keep source groups intact"]
A -->|No| C{"Can labels overlap?"}
C -->|Yes| D["Stratify across multiple labels"]
C -->|No| E["Stratify by class"]If every example of a rare class comes from one clip, a group-disjoint split can include that class in training or in held-out evaluation, but never in both.














