License YOLO
Back to Ultralytics Glossary

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.

Medical Pills preview 1
Medical Pills preview 2
Medical Pills preview 3
Medical Pills preview 4
115
Medical Pills
ultralytics
PublicDetect

Photos of pharmaceutical pills, a proof-of-concept set for pill detection in pharmaceutical automation. Built to demonstrate computer vision for quality control, packaging, sorting, and inventory tracking. Created by Ultralytics (Jocher and Rizwan, 2024); docs.ultralytics.com/datasets/detect/medical-pills.

41 class16.1 MBOct 23, 2026
pill

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.

Explore solutions

Computer vision in sports

Computer vision in sports

Discover how Ultralytics YOLO powers sports vision with player and ball tracking, performance analytics, coaching insights, and athlete rehabilitation.
Learn more
Computer vision for aerial imagery

Computer vision for aerial imagery

Turn drone and aerial imagery into real-time insights for agriculture, aquaculture, conservation, and geospatial analysis with Ultralytics YOLO.
Learn more
Computer vision in aerospace

Computer vision in aerospace

Apply computer vision in aerospace with Ultralytics YOLO for aircraft inspection, runway FOD detection, airport ground operations, and composite defect detection.
Learn more
Computer vision in security

Computer vision in security

Protect every site with Ultralytics YOLO models. Vision AI powers perimeter monitoring, threat detection, license-plate recognition, and workplace safety.
Learn more
Computer vision in robotics

Computer vision in robotics

Power smarter machines with Ultralytics YOLO models. Vision AI in robotics drives autonomous navigation, perception, object tracking, and real-time control.
Learn more
Computer vision in logistics

Computer vision in logistics

Streamline logistics with Ultralytics YOLO models. Vision AI enables package inspection, sorting, vehicle tracking, and real-time warehouse safety monitoring.
Learn more
Computer vision in retail

Computer vision in retail

Reimagine retail with Ultralytics YOLO models. Vision AI powers inventory tracking, shelf monitoring, queue management, and smarter customer insights.
Learn more
Computer vision in healthcare

Computer vision in healthcare

Build healthcare solutions with Ultralytics YOLO models. Vision AI in healthcare powers faster medical imaging, smarter diagnostics, and patient monitoring.
Learn more
Computer vision in manufacturing

Computer vision in manufacturing

Optimize manufacturing with Ultralytics YOLO models. Vision AI drives quality control, defect detection, PPE compliance, and assembly line automation.
Learn more
Computer vision in automotive

Computer vision in automotive

Apply computer vision in automotive with Ultralytics YOLO models. Vision AI elevates road safety, driver assistance, and vehicle automation for smarter roads.
Learn more
Computer vision in agriculture

Computer vision in agriculture

Bring vision AI to smart agriculture with Ultralytics YOLO models. Power crop monitoring, livestock tracking, and precision farming for higher, smarter yields.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning