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 readListen to this article

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.
| Split | Typical share | Who learns from it | When you look at it |
|---|---|---|---|
| Train | 70% | The model fits its weights here | Every epoch |
| Val | 15% | You: epochs, model size, thresholds, settings | After every experiment |
| Test | 15% | Nobody | Once, 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.
A random split leaks when your images are related#
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.
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.
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 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
valempty, Platform moves about 20% of the train images, at least one, intoval; classification datasets follow their folder structure and depth datasets have their own rules. With All selected, images intrain/,val/ortest/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
imgszand 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: palletfrom 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#
- Upload grouped splits when your images are related. With All selected, images inside
train/,val/ortest/folders keep that split, so prepare group splits offline and upload the folders. - 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.
- Move specific images. Select them in Table view, right-click, and choose Move to split, for example to keep one camera whole.
- Check the result. Open the Charts tab for the split distribution, run the per-class audit above, and color the Clustering view by split.
- 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.
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, definetest:in your dataset YAML and runmodel.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.
autosplitdefaults 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
Comments
Ask a question, share your results, or help someone else.





























