License YOLO
Guides

Train, validation and test splits for computer vision: ratios, class balance and leakage

Start at 70/15/15, split by camera or clip, check every class in every split, and score val and test separately with Ultralytics YOLO and Platform.

Sergiu Waxmann14 min read

Listen to this article

Start at 70/15/15, split by camera or clip, check every class in every split, and score val and test separately with Ultralytics YOLO and Platform.

How should you split a computer vision dataset into train, validation and test sets? Start from about 70/15/15, split whole groups of related images (clips, cameras, days or sites) rather than single frames, make sure every class shows up in every split, and look at the test set only once. The exact ratio matters far less than keeping near-identical images on one side of the line.

This guide covers what each split is for, why a random shuffle can leave a rare class with no validation images, how near-duplicate frames leak between splits, why an unlabeled validation set breaks your metrics, and how to read validation scores against test scores. It ends with the steps to do all of it in Ultralytics YOLO and Ultralytics Platform.

Each split has one job, and only one#

A dataset split is a promise about who gets to see which images. Training data is the only split the optimizer learns weights from. Validation data guides your decisions: which epoch to keep, which model size, which settings. Test data reports one final number after every decision is made.

SplitTypical shareWho learns from itWhen you look at it
Train70%The model fits its weights hereEvery epoch
Val15%You: epochs, model size, thresholds, settingsAfter every experiment
Test15%NobodyOnce, for the final go/no-go

The 70/15/15 starting point comes from our Academy lesson on splitting a dataset correctly, and our guides put the usual range at 70-80% train with 10-20% each for val and test: the steps of a CV project suggests 10-15% each, and the preprocessing guide uses 70/20/10. Count the shares in objects as well as images, because one crowded image can hold more labels than ten sparse ones.

Ultralytics YOLO training uses the val split continuously. For detection, by default, it scores val after every epoch, saves the epoch with the highest validation mAP50-95 as best.pt, and stops early after patience epochs without improvement, 100 by default, as the validation data glossary entry explains. That is exactly why val cannot double as your final score: you have already used it to choose.

Frames 124 and 125 of the same clip are nearly identical. If one lands in train and the other in val, validation grades the model on a picture it has effectively already seen. That is data leakage, and it makes validation mAP look excellent while the model fails at the next camera.

A fixed traffic camera view of an intersection with cars, a truck and pedestrians boxed by an object detector Illustrative. One fixed camera produces thousands of frames that share the same background, lighting and often the same vehicles, so a per-frame random split puts near-twins on both sides.

On the medical-pills dataset, whose images are frames from a video, the Splits that Tell the Truth lesson compares a 32 x 18 grayscale fingerprint of each validation image with every training image and counts a near-twin when the mean difference is below 5 on the 0-255 scale: 17 of the 23 validation images have one. In the split lesson's practice set, a random per-image 70/15 split put all 13 validation camera-days into training as well.

Public benchmarks are not immune. A study of large geospatial datasets found that 93.45% of the official AICrowd Mapping Challenge validation images were also present in its training split.

Split by the unit that will be new at deployment#

The fix is a group split: pick the unit your model must generalize across and assign whole units to one split.

flowchart LR
    A{New cameras or sites?} -->|yes| B[Split by camera or site]
    A -->|no| C{Video or burst captures?}
    C -->|yes| D[Split by clip or day]
    C -->|no| E[Random per image]

Random per-image splits are safe only when every image is an independent capture, such as product photos taken weeks apart. When in doubt, choose the most general unit you can afford, because it gives the most honest number. For a fixed warehouse camera that must keep working on new days, the Academy lesson splits by camera-day, keys every filename with it (cam2_2026-05-01_000124.jpg), then verifies with a short script that no key appears in two splits.

Check for near-duplicates, not just exact copies#

Hashing files catches byte-identical copies, such as a folder uploaded twice. It misses consecutive frames, burst photos and re-encoded copies that differ by a few pixels. For those, compare small fingerprints as above, or use embeddings: in Ultralytics Platform, the Clustering view of a dataset can be colored by split, and a tight island that mixes train and val points is a candidate near-duplicate leak, as the Curate, Dedup, and Split lesson shows. Open those images, or check their camera and session metadata, before deciding they are the same scene.

Random splits skew rare classes#

Shuffling all images together keeps the overall ratio, not each class's ratio. A class with 40 examples can easily land 2 of them in val, or none. Platform's Split Redistribution docs now state this directly: redistribution shuffles all images together, so a rare class can end up with few or no validation images.

A top-down warehouse floor with many pallets boxed in cyan and a single forklift boxed in pink Illustrative. Many pallets to one forklift: in imbalanced data like this, a random shuffle decides how many forklifts val gets.

Two things go wrong when a class is thin in a split:

  • Missing in train: your data gives the model no positive examples to learn the class from. A pretrained model may still score something, but you can't improve what you never train on, so add labeled groups that contain it.
  • Too few in val: its AP is noise. With 7 pallets in val, one missed pallet is 1 of 7, about 14 percentage points of pallet recall, so a single object can swing the class's score, as the Curate, Dedup, and Split lesson warns.

Stratify classification, balance detection by group#

For image classification, each image has one label, so you can stratify: split every class folder at the same ratio. Ultralytics ships split_classify_dataset for this. It splits each class folder 80/20 by default into a new {source}_split directory, with a fixed seed so re-running never mixes train and val images, and it runs automatically when you train on a classification folder with no train/ directory.

Object detection images hold several classes at once, so single-label stratification, including scikit-learn's StratifiedGroupKFold in its cross-validation module, does not balance every object class directly. Balance at the group level instead: after a group split, compare per-class counts across splits and swap whole groups until every class sits within about ±20% of its expected share, as the split lesson recommends. When a class is missing from a split, add or move whole groups that contain it, never single frames, which would reintroduce the leak. With few groups, some targets are impossible until you collect more cameras or days.

The Charts tab of the LOCO warehouse dataset on Ultralytics Platform showing split distribution and top classes The Charts tab of the LOCO warehouse dataset on Ultralytics Platform plots the split distribution and the top classes across the dataset.

The Charts tab shows the overall picture. For per-class box counts in each split of a detection dataset, download the dataset's NDJSON export from the dataset header and count them, adapted from the Academy lesson:

import json
from collections import Counter, defaultdict

counts = defaultdict(Counter)  # split -> class name -> box instances
with open("dataset.ndjson") as f:  # NDJSON export from the dataset header or Versions tab
    names = json.loads(f.readline())["class_names"]
    for line in f:
        record = json.loads(line)
        for box in (record.get("annotations") or {}).get("boxes", []):  # detection boxes
            counts[record["split"]][names[str(box[0])]] += 1

for name in sorted(names.values()):  # every defined class, zeros included
    print(f"{name:<14}" + "".join(f"{s} {counts[s][name]:>4}  " for s in ("train", "val", "test")))

An unlabeled validation set can't score anything#

Validation compares predictions against ground truth, so it only works on labeled images. An image with no label file counts as a background image, which is useful when it truly contains nothing. If an entire validation split has no labels, Ultralytics prints the warning no labels found in detect set, cannot compute metrics without labels, and mAP comes out as 0, according to the detection validator source.

A partly labeled val set is quieter and worse. A correct detection on an object nobody labeled counts as a false positive, so precision drops for no real reason, and best.pt is chosen by a val mAP50-95 that is wrong.

On Platform, unlabeled images reach val in a few predictable ways:

  • No val split on upload. For a detection, segmentation, pose or OBB dataset, if an upload with no split selected leaves val empty, Platform moves about 20% of the train images, at least one, into val; classification datasets follow their folder structure and depth datasets have their own rules. With All selected, images in train/, val/ or test/ folders keep their split; selecting Train, Val or Test first sends the whole upload there.
  • Video frames. Frames extracted from a video arrive unlabeled in the split the gallery filter has selected, and with All selected they follow the upload rule above, which can move some into an empty val, so select Train before dropping a video.

Filter the gallery to Val and audit it before you train: every object labeled, and any background images there on purpose. Locally, the scan line at the start of validation (23 images, 0 backgrounds, 0 corrupt) tells you at a glance how many val images have no labels.

One more trap hides in per-class results. In the validation mode docs, metrics.box.maps holds per-class mAP50-95, but classes absent from the val set hold the overall mAP instead. Read metrics.box.ap_class_index to see which classes were actually evaluated.

Read val as your tuning score and test as your honest one#

By default, model.val() scores the val split. To score the held-out test set, define test: in the dataset YAML and pass split="test", as the model testing guide shows. Both report the same metrics: precision, recall, mAP50 and mAP50-95, explained in our YOLO performance metrics guide. So the mAP50-95 printed during training is a validation number, and the test number is the one you report.

Here is how to read the pair:

  • Test slightly below val is normal. You picked the epoch and settings that maximized val, so val is a little optimistic.
  • Test far below val calls for a check, in this order: the same imgsz and settings for both runs, the same classes covered in both splits, consistent labels, and test images that match deployment conditions. If those hold, look for leakage between train and val, or for many rounds of tuning against val.
  • Numbers that swing between runs usually mean a split too small to trust. In the Validate and Diagnose lesson, the pill model's precision on 23 validation images moved from 0.93 to 0.80 and back within a single training run.

The most expensive mistake is comparing ten model variants on the test set. Once test has influenced a decision, it is a second validation set and its number is optimistic, a form of overfitting to your own choices. For datasets under about 500 images per class, K-fold cross-validation trains k models on rotating folds for a steadier estimate, at k times the compute. Build the folds from groups too, and keep the test set outside all of them.

How to split a dataset in Ultralytics YOLO and Platform#

In Python#

For independent images, autosplit assigns each image to train, val or test at random with the weights you give and writes autosplit_train.txt, autosplit_val.txt and autosplit_test.txt next to the images folder. Because each image is drawn independently, the shares come out close to the weights rather than exact. With annotated_only=True it keeps only images that have a label .txt file, which drops background images without one, so leave it off if your negatives have no label files. Use a group split, as above, for video or multi-camera data.

# forklift.yaml
path: /data/forklift
train: autosplit_train.txt
val: autosplit_val.txt
test: autosplit_test.txt
names:
  0: forklift
  1: person
  2: pallet
from ultralytics import YOLO
from ultralytics.data.split import autosplit

# 70/15/15 for independent captures; writes autosplit_*.txt beside the images folder
autosplit(path="/data/forklift/images", weights=(0.7, 0.15, 0.15))

model = YOLO("yolo26n.pt")
model.train(data="forklift.yaml", epochs=100, imgsz=640)

best = YOLO(model.trainer.best)  # best.pt from this run
val = best.val(data="forklift.yaml")  # tuning score
test = best.val(data="forklift.yaml", split="test")  # report once
print(f"val mAP50-95 {val.box.map:.3f}  test mAP50-95 {test.box.map:.3f}")

Before training, check that all three autosplit_*.txt files exist and list images: a small dataset can leave a split with no file at all. If one is empty, add images or assign groups by hand rather than rerunning on the same inputs, then run the per-class audit on the result.

For a classification dataset sorted into class folders, split_classify_dataset("path/to/dataset", 0.8) gives you a stratified 80/20 train/val split in one call; the classify task docs cover training on it.

In Ultralytics Platform#

  1. Upload grouped splits when your images are related. With All selected, images inside train/, val/ or test/ folders keep that split, so prepare group splits offline and upload the folders.
  2. Redistribute independent images. In the dataset's Images tab, click the thin colored split bar below All / Train / Val / Test, type or drag the percentages (for example 70/15/15), check the live image count preview, and click Apply. Auto sets 80/20 train/val with 0% test.
  3. Move specific images. Select them in Table view, right-click, and choose Move to split, for example to keep one camera whole.
  4. Check the result. Open the Charts tab for the split distribution, run the per-class audit above, and color the Clustering view by split.
  5. Train on a frozen version. When you start cloud training, the training dialog's Save Dataset Version option snapshots the dataset, reusing a matching version when nothing changed. Versions are available for Platform-hosted datasets, not connected cloud or On Premise datasets.

The Ultralytics Academy split lesson showing Platform's Redistribute Splits dialog with an 80/20/0 split and an Auto button Platform's Redistribute Splits dialog, shown in the Ultralytics Academy split lesson: drag, type or Auto, with a live preview of images per split.

Redistribution reassigns images randomly and does not know your groups. It also deletes all but one copy of an image that appears in more than one split, along with those copies' annotations, so final counts can be lower than the preview. For an imbalanced classification dataset, the docs recommend splitting each class locally with split_classify_dataset and uploading the train/ and val/ folders. Our post on smart dataset management in Ultralytics Platform covers the rest of the dataset workflow.

Who should revisit their split#

Anyone training on video, fixed cameras, bursts or several sites should audit their split before the next training run: a group split and a near-duplicate check are the cheapest accuracy fix available, because they make the number you already have honest. Teams with rare classes should check per-class counts per split before trusting any per-class AP. And anyone reporting a model to a customer or a review board should hold a test set that nobody tuned on, scored once with split="test".

Once the split is fixed, keep it. Every metric you publish is tied to it, and re-shuffling later makes old and new runs incomparable. Store the split unit, the seed and the file lists with the dataset, or freeze them as a Platform dataset version. Then train Ultralytics YOLO26 on it and compare runs on equal terms.

Frequently asked questions

  • Start from 70/15/15 and adjust for dataset size; Ultralytics guides put the usual range at 70-80% train with 10-20% each for val and test. Larger datasets can spare smaller shares for val and test. Count objects as well as images, and make sure every class appears in every split.

  • During detection training, Ultralytics YOLO computes mAP50-95 on the val split after every epoch and, by default, keeps the best epoch as best.pt. model.val() also scores val by default. To score the test set, define test: in your dataset YAML and run model.val(split="test").

  • The validation set guides decisions such as which epoch, model size or threshold to use, so you look at it after every experiment. The test set reports one final number after all decisions are made. Once you tune on the test set, it becomes a second validation set and its score is optimistic.

  • Split by the unit that will be new at deployment, such as camera, clip, day or site, so related frames stay in one split. Then check for exact duplicates with file hashes and for near-duplicates with image fingerprints or embedding clusters colored by split. Fix leaks by moving whole groups, never single frames.

  • Yes. autosplit defaults to a 90/10/0 split, and Platform's Auto button sets 80/20 train/val with 0% test. Without a test set, though, your only score is the validation number you tuned on, so keep a test share above 0% whenever you need a final number nobody optimized for.

Written by

Sergiu Waxmann
Sergiu Waxmann

Lead Software Engineer · Ultralytics

Sergiu Waxmann is the Lead Web Developer at Ultralytics, where he focuses on building intuitive and dynamic web experiences. A software engineer specializing in modern web development frameworks, he holds a Bachelor's degree in Computer Software Engineering from Saxion University of Applied Sciences.

Comments

Ask a question, share your results, or help someone else.

Similar articles

Document layout analysis datasets for historical pages, and why old prints are hard

Document layout analysis datasets for historical pages, and why old prints are hard

Six historical document layout analysis datasets on Ultralytics Platform, from The History of England to a 15th-century music manuscript, compared.
Learn more
How to choose an edge AI device for computer vision, with measured Ultralytics YOLO26 results

How to choose an edge AI device for computer vision, with measured Ultralytics YOLO26 results

Measured YOLO26 results on Jetson, DGX Spark, Raspberry Pi 5 with Hailo-8 or DEEPX, RK3588, Snapdragon, iPhone, Apple M4 and STM32, each with its setup.
Learn more
Ultralytics Platform export options for YOLO26n: TensorRT for a Jetson Orin Nano Super at 4.57 ms and NCNN for a Raspberry Pi 5 CPU at 67.03 ms, from separate published benchmarks

Jetson Orin Nano Super vs Raspberry Pi 5 for YOLO26 object detection

YOLO26n inference: 4.57 ms on a Jetson Orin Nano Super (TensorRT FP16) vs 67.03 ms on a Pi 5 CPU, in separate tests. Choose by model, FPS and cameras.
Learn more
Ultralytics cover for the Azure Custom Vision migration checklist: the Ultralytics Platform New Dataset dialog with a panel mapping Custom Vision detection projects, tagging, training iterations and prediction endpoint to Platform datasets, annotation editor, cloud training and dedicated endpoints

Azure Custom Vision is retiring: a migration checklist for your vision models

Azure Custom Vision retires on September 25, 2028. Plan your migration, export your labeled data and retrain on Ultralytics Platform.
Learn more
Ultralytics Platform export list with the NCNN row highlighted above MNN, the format recommended for running YOLO26 on a Raspberry Pi 5 CPU

Raspberry Pi object detection: YOLO26 on a Pi 5 CPU, no accelerator

YOLO26n runs at 67.03 ms per image with NCNN on a Raspberry Pi 5 CPU, and Arm's open-source runtime measures 36.60 ms in its own test. Here's how to run both.
Learn more
Ultralytics licensing page showing the free AGPL-3.0 card and the paid Ultralytics Enterprise License card

Is Ultralytics YOLO free for commercial use? AGPL-3.0 vs the Enterprise License

Ultralytics YOLO is free under AGPL-3.0 if you open-source your whole project. Compare licensing for internal tools, SaaS and devices.
Learn more
Ultralytics security page cards for ISO/IEC 27001:2022 and SOC 2 Type I, with Ultralytics Platform workspace roles in front, on a gold gradient cover titled Regulated industries

Computer vision for regulated industries: an Ultralytics security review checklist

A security review checklist for computer vision in regulated industries: SOC 2 and ISO 27001 scope, on-premise and air-gapped options, privacy and SLAs.
Learn more
The Ultralytics Platform SAM smart annotation editor segmenting boxes on a warehouse conveyor, with a Batch Annotation estimated cost of $0.05 for 49 images

Budgeting for Image Annotation: Seats, AI and Exports

Compare image annotation software costs, free-plan limits and AI allowances. Estimate software and project costs with a worked three-person team example.
Learn more
Aerial view of a busy intersection with cars boxed by Ultralytics YOLO26s using 640-pixel tiles, dashed lines marking the tile seams

Small object detection with image tiling in Ultralytics YOLO, from Python to Rust

See when image tiling helps YOLO detect small objects, compare its costs, and run built-in tiled inference in Python or Rust without SAHI.
Learn more
A confusion matrix from model evaluation in Ultralytics Platform, beside compare workflows: no-code, developer control and edge export

Best platforms for training custom image classifiers

Image classifier training platforms compared: no-code AutoML, developer platforms and edge tools, and how to choose by control, deployment and cost.
Learn more
A rendered street scene with a bus, cars and people carrying pixel-perfect segmentation labels, beside three methods: simulation, generation and augmentation

Best synthetic data tools for computer vision training

Synthetic data tools for computer vision compared by method: 3D simulation, generative models and augmentation, and how to test them with Ultralytics YOLO.
Learn more
Missing PPE detection: train Ultralytics YOLO on Construction-PPE

Missing PPE detection: train Ultralytics YOLO on Construction-PPE

See how Construction-PPE labels missing helmets, vests and gloves, then train Ultralytics YOLO to detect missing PPE on your own site cameras.
Learn more
Drone detection dataset guide: train Ultralytics YOLO on tiny UAVs

Drone detection dataset guide: train Ultralytics YOLO on tiny UAVs

Compare DUT Anti-UAV, Drone-vs-Bird and thermal drone detection datasets, then train Ultralytics YOLO26 to find tiny drones and cut false alarms.
Learn more
A YOLO26 depth estimation prediction in Ultralytics Platform showing a dense depth map of a street scene with a bus, with timings and depth range

Best Depth Estimation Models: How to Choose

Compare monocular depth models such as Depth Anything, Depth Pro, Metric3D, UniDepth and Ultralytics YOLO26 for metric depth, edge devices and robotics.
Learn more
Two leaves classified as healthy and rust by an image classification model, with confidence scores

Best Image Classification Models: How to Choose

Compare the leading image classification models, from ConvNeXt V2 and DINOv3 to EfficientNetV2, ViT and Ultralytics YOLO26-cls, and learn how to choose.
Learn more
YOLO26 semantic segmentation of a street scene with a bus and people in Ultralytics Platform, each class shown in its own color

Semantic vs Instance Segmentation: How to Choose the Right Task

Semantic segmentation labels every pixel by class; instance segmentation separates each object. Learn which one your computer vision project needs, and why.
Learn more
An engineer with a tablet beside industrial machinery, beside the costs beyond compute: data and labeling, cameras and hardware, integration and operations

What Enterprise Computer Vision Costs: A TCO Framework

A total-cost framework for enterprise computer vision covering data, annotation, cameras, edge hardware, training, inference, integration and retraining.
Learn more
Ultralytics Platform deployment monitoring showing total requests, active deployments and a ready YOLO26 segmentation endpoint

Computer Vision Inference at Scale: Seven Platforms Compared

Seven computer vision inference platforms compared: Azure ML, KServe, NVIDIA Triton, Roboflow, SageMaker AI, Ultralytics and Vertex AI, on latency and scale.
Learn more
Ultralytics Platform SAM smart annotation outlining a leopard, beside two different jobs: propose labels and select useful frames

How to Label Less: Auto-Labeling and Active-Learning Tools Compared

Ten auto-labeling and active-learning tools compared: CVAT, Encord, Label Studio, Labelbox, Lightly, Roboflow, SuperAnnotate, Ultralytics, V7 and FiftyOne.
Learn more
Elevated security-camera view of a city intersection with cars, a bus and pedestrians detected by Ultralytics YOLO26, beside three routes: analytics layer, VMS upgrade and self-hosted models

How to Add AI Analytics to Existing Security Cameras

Three routes to adding AI analytics to existing security cameras: analytics layers, VMS upgrades, or self-hosted models, and the constraints that decide.
Learn more
Metal castings on a conveyor with cracks and damaged parts detected, a magnified crack, and what to test: accuracy on your images, edge deployment and licensing

Choosing a Computer Vision Vendor: An Enterprise Procurement Guide

A procurement view of eight computer vision vendors: AWS, Azure, Cognex, Encord, Landing AI, NVIDIA, Roboflow and Ultralytics, with licensing checks.
Learn more
An edge computing board with a processor, beside where inference runs: managed endpoint, own hardware or hybrid

Managed Cloud vs Self-Hosted Computer Vision Deployment

Compare managed cloud and self-hosted computer vision deployment on cost, latency, data boundaries, scaling and exit risk, with three deployment patterns.
Learn more
A parcel on a modern conveyor detected by Ultralytics YOLOE, beside production readiness steps: validate, integrate, assign owners and monitor

Scaling Computer Vision from Pilot to Production

Six stage gates for taking computer vision from pilot to production, covering coverage matrices, workflow validation, model operations and site readiness.
Learn more
Bottles on a high-speed bottling line under an inspection camera, each detected by Ultralytics YOLO26

Computer Vision Platforms for Manufacturing: YOLO, Cognex and Keyence Compared

Compare computer vision platforms for manufacturing: Cognex, Edge Impulse, Keyence, Landing AI and Ultralytics YOLO, on inspection and MES fit.
Learn more
An Ultralytics Platform dataset gallery of labeled wildlife images, beside the question service or software: managed labeling or annotation software

Scale AI Alternatives for Data Labeling

Alternatives to Scale AI for vision data labeling: iMerit, SuperAnnotate and Ultralytics Platform, compared on cost, control, ramp time and data handling.
Learn more
Overhead view of people passing ticket gates in a bright concourse, detected by Ultralytics YOLO26, beside the four people-counting measurements: entries, occupancy, dwell time and queues

How People Counting and Occupancy Analytics Actually Work

How people counting and occupancy analytics work: comparing WiFi, ToF, thermal and camera-based vision methods, the products available, and how to build it.
Learn more
An industrial robot lifting a tyre from a stack in a warehouse, with the tyre detected by Ultralytics YOLOE

Vision-Guided Robotics for Assembly and Pick-and-Place

How vision-guided pick-and-place works across sensing, perception, calibration, grasp planning, motion and recovery, with a 2D versus 3D decision guide.
Learn more
Cherries segmented with precise polygon labels, beside who owns label quality: guidelines, review and a gold-standard set

Annotation Outsourcing vs In-House: The Real Trade-offs

Compare outsourced and in-house computer vision annotation on cost per usable label, ramp time, quality, security and the hybrid model most teams reach.
Learn more
PyTorch vs TensorFlow for computer vision projects

Choosing between PyTorch vs TensorFlow for computer vision projects

Compare PyTorch vs TensorFlow for computer vision across ease of use, flexibility, deployment, and scalability, and see how each fits Ultralytics YOLO.
Learn more
Supervised vs unsupervised learning in computer vision

Exploring supervised vs unsupervised learning in computer vision

Learn the differences between supervised and unsupervised learning in computer vision and how to choose the right approach for your data and project goals.
Learn more

Let's build the future of AI together!

Begin your journey with the future of machine learning