Sub topic 12
Splitting data without leakage
This chapter assumes you can write basic Python with lists and dictionaries, read COCO-style JSON, and know what training and evaluating a supervised model means. It covers how to divide a labelled detection or segmentation dataset into training, validation and test sets so that the evaluation numbers mean something.
Why splits exist
A model is trained on one set of images and judged on another. The judgement is only honest if the second set is something the model has not seen. The usual three sets are:
| Set | Used for | Who looks at it |
|---|---|---|
| Train | Fitting model weights | The optimiser, every epoch |
| Validation | Choosing hyperparameters, stopping training, comparing runs | You, repeatedly |
| Test | One final estimate of real-world performance | You, rarely |
The test set is only useful if decisions are not tuned against it. Each time you pick a model because it scored well on the test set, the test set leaks a little into your choices and the number becomes optimistic. Keep it locked until the end.
What leakage is
Leakage is any path by which information from the evaluation images reaches training. The model then scores well because it has effectively seen the answers, not because it generalises. The score looks good in your report and falls apart in deployment.
In image datasets the worst leaks are not exact duplicates. They are near-duplicates, which random splitting cannot see:
- Frames from the same video. Frames 1,200 and 1,201 of a dashcam clip are almost identical.
- Burst shots or multiple photos of the same scene from one session.
- The same physical object photographed several times, such as one product on a shelf from three angles.
- Crops, rescaled copies or re-compressed copies of one source image.
- Tiles cut from one large image, such as a satellite scene or a pathology slide. Neighbouring tiles share content at their edges.
- Augmented copies made before splitting (flips, colour shifts, mosaics).
A random per-image split puts some of these siblings in train and some in test. The model memorises the scene, then "detects" the same car in the test sibling. Detection and segmentation suffer especially, because background, lighting and camera placement are shared across siblings and the model can latch onto them.
The rule: split by group, not by image
Decide what the unit of independence is, then assign whole units to a split. Call that unit a group. Common choices:
- Video or recording session ID.
- Camera or capture location, if you want the model to generalise to new sites.
- Patient, slide or specimen ID in medical imaging.
- Source large image, for tiled data.
- A cluster of near-duplicates found automatically, when no metadata exists.
The right group depends on the deployment you care about. If the model will run on cameras it has never seen, group by camera. If it will run on new footage from known cameras, group by recording is enough. Pick the group that matches the question "what will be new at deployment?"
Getting group IDs
Metadata is the best source. File names often encode it, for example cam3_2026-05-14_000123.jpg. Parse the camera and date from the name rather than guessing.
When metadata is missing, build groups from the images themselves. A perceptual hash gives similar images similar hashes. The sketch below uses a simple average hash, then merges images whose hashes differ by only a few bits into one group using union-find.
import numpy as np
from PIL import Image
def average_hash(path, size=8):
"""64-bit hash as a tuple of bits: 1 where a pixel is above the mean."""
img = Image.open(path).convert("L").resize((size, size))
px = np.asarray(img, dtype=np.float32)
return tuple((px > px.mean()).flatten().astype(int))
def hamming(a, b):
return sum(x != y for x, y in zip(a, b))
def group_near_duplicates(paths, max_distance=5):
hashes = [average_hash(p) for p in paths]
parent = list(range(len(paths)))
def find(i):
while parent[i] != i:
parent[i] = parent[parent[i]]
i = parent[i]
return i
for i in range(len(paths)):
for j in range(i + 1, len(paths)):
if hamming(hashes[i], hashes[j]) <= max_distance:
parent[find(i)] = find(j)
return {paths[i]: find(i) for i in range(len(paths))}This is quadratic in the number of images, which is fine for a few thousand. For larger sets, use an approximate nearest-neighbour index over image embeddings. Tune max_distance by looking at pairs near the threshold. A low value misses sibling frames, and a high value merges unrelated images into one huge group that then cannot be split evenly.
Splitting by group in code
Scikit-learn's GroupShuffleSplit assigns whole groups. Apply it twice to get three sets.
from sklearn.model_selection import GroupShuffleSplit
def three_way_split(items, groups, val_frac=0.15, test_frac=0.15, seed=0):
"""items, groups: parallel lists. Returns lists of indices."""
idx = list(range(len(items)))
outer = GroupShuffleSplit(n_splits=1, test_size=test_frac, random_state=seed)
trainval_idx, test_idx = next(outer.split(idx, groups=groups))
trainval_groups = [groups[i] for i in trainval_idx]
inner_frac = val_frac / (1 - test_frac)
inner = GroupShuffleSplit(n_splits=1, test_size=inner_frac, random_state=seed)
tr, va = next(inner.split(trainval_idx, groups=trainval_groups))
train_idx = [int(trainval_idx[i]) for i in tr]
val_idx = [int(trainval_idx[i]) for i in va]
return train_idx, val_idx, [int(i) for i in test_idx]Two details matter. The test_size is a fraction of groups, not of images, so if groups differ in size the image counts will only approximate your target. And the second split's fraction must be rescaled, because it applies to what remains after the test set was removed.
Checking for leaks after splitting
Do not trust the split; verify it. Write a check that fails loudly if any group appears in more than one set.
def assert_no_group_overlap(split_to_groups):
"""split_to_groups: dict like {"train": set, "val": set, "test": set}."""
names = list(split_to_groups)
for i, a in enumerate(names):
for b in names[i + 1:]:
shared = split_to_groups[a] & split_to_groups[b]
if shared:
raise AssertionError(
f"{len(shared)} groups appear in both {a} and {b}: "
f"{sorted(shared)[:5]}"
)
assert_no_group_overlap({"train": {1, 2, 3}, "val": {4}, "test": {5, 6}})
print("no overlap")Run it in the same script that writes the split files, so a bad split cannot be saved. Also run a cross-check with an independent method: compute perceptual hashes or embeddings for the test images, find their nearest neighbour in train, and review the closest pairs by eye. If the nearest train image for a test image is nearly identical, you have a leak your group labels missed.
Balancing classes and rare cases
Group splitting gives up some control. With few groups, one split can end up with no examples of a rare class. After splitting, count labelled instances per class in each set:
from collections import Counter
def class_counts(coco, image_ids):
ids = set(image_ids)
return Counter(
a["category_id"] for a in coco["annotations"] if a["image_id"] in ids
)If a rare class is missing from validation or test, you cannot measure it at all. Options, in order of preference:
- Try several seeds and keep the split whose class counts are closest to the target proportions. The group constraint stays intact.
- Use a stratified group splitter, such as
StratifiedGroupKFoldin scikit-learn, which balances class distribution while keeping groups whole. - Collect more data for the rare class from new sources.
Do not move single images between sets by hand to fix the counts. That reintroduces the leak you removed.
Edge cases
- Augmentation. Apply it only to the training set, and only after the split. Augmented copies generated before splitting are the most common accidental leak. Most training frameworks augment on the fly, which avoids the problem.
- Annotation format side effects. A single COCO file holds all images. Write one annotation file per split, with image IDs and annotation IDs kept consistent, and make sure the
categorieslist is identical in all three files so class IDs match. - Tiling. Split the source images first, then cut tiles. If tiles already exist, group by source image ID.
- Pre-labelling models. If a model helped create the labels (see the model-assisted chapter) and was trained on images that are now in your test set, its biases are baked into those test labels. Prefer to keep test images out of the pre-labelling model's training data, and have humans label the test set carefully.
- Time-varying data. If the deployment sees future data, split by time: train on earlier recordings, test on later ones. This catches drift that a shuffled split hides.
- Reusing the validation set. Every tuning round makes the validation score slightly optimistic. This is expected, which is why the test set exists.
- Fixed splits. Save the assignment to disk (a CSV of image path and split) and commit it. Re-running a random split with a new seed or a new image list silently changes which images are in test, which makes results across experiments incomparable.
Writing the split out
import csv
def save_split(path, items, train_idx, val_idx, test_idx):
rows = (
[(items[i], "train") for i in train_idx]
+ [(items[i], "val") for i in val_idx]
+ [(items[i], "test") for i in test_idx]
)
with open(path, "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["file_name", "split"])
writer.writerows(rows)
save_split("splits.csv", ["a.jpg", "b.jpg", "c.jpg"], [0], [1], [2])When new images arrive later, assign them to a split by their group, using the saved file as the source of truth. A new frame from a video already in the test set goes to test.
Link to error analysis
Leakage often shows up as results that look too good. If validation performance is far above what the task's difficulty suggests, or training and test scores are nearly identical on a hard problem, suspect a leak before celebrating. The next step after a clean split is reading the model's errors on the test and validation sets, which can also reveal label mistakes.
Exercise
A dataset has 12,000 frames from 40 dashcam videos. A teammate splits it with a random 80/10/10 per-image split and reports 94% mAP on the test set, much higher than earlier models. What is the likely problem, and how would you fix and check it?
Show answer
Frames from the same video are near-identical, so a per-image random split puts sibling frames in both train and test, and the model has effectively seen the test scenes. Fix it by using the video ID as the group and splitting whole videos with a group splitter such as GroupShuffleSplit. Check it by asserting that no video ID appears in more than one split, and by comparing each test image to its nearest train image with a perceptual hash or embedding to confirm no near-duplicates remain. Expect the score to drop to a more honest value.
Exercise
You group-split your data and find the test set contains no examples of the rare class "bicycle". Name two acceptable fixes and one fix to avoid.
Show answer
Acceptable: try other random seeds and keep a split whose per-class counts are close to the targets, or use StratifiedGroupKFold, which balances classes while keeping groups whole. Collecting more bicycle data from new sources also works. Avoid: moving individual images containing bicycles into the test set by hand, because this can put siblings of training images into test and reintroduces leakage.