Train/test splits for images without leakage (near-duplicates and contamination)
How to split an image dataset into train, validation and test sets, how big the test set has to be, and how to keep the same patient, scene or near-identical photo from showing up on both sides and inflating the score.
A train/test split divides labeled images into a part the model learns from and a part held back to measure it. The measurement is only fair if the test images are new to the model. With image data that is harder than it sounds, because many images in a dataset are close copies of each other, and a careless split lets the model score well by recognizing them.
The three-way split
Labeled data usually gets divided into three parts:
- Train: the images the model learns from.
- Validation: images held out from training and used to compare experiments, such as different models or different settings. Settings that are chosen by hand before training, such as the learning rate, are called hyperparameters.
- Test: images kept for one final measurement at the end.
Each time you pick a model or a setting because its validation score was higher, a little of the validation set leaks into your choices. After many experiments the validation score is too optimistic. The test set avoids this by being used once. Tune against it and its score stops meaning much.

How big the test set has to be
Say you have 24,000 labeled images and split them 70/15/15:
$$\text{train} = 0.70 \times 24000 = 16800$$
$$\text{val} = 0.15 \times 24000 = 3600$$
$$\text{test} = 0.15 \times 24000 = 3600$$
The size of the test set sets how precise the final number can be. Near 90 percent accuracy, a test set of 3,600 images gives a result that is give or take about 1 percent. The uncertainty shrinks with the square root of the test set size, so a 200-image test set is give or take about 4 percent. A two-point difference between two models would sit inside that range.

Why random splits inflate image scores
Image datasets are full of related images. Frames from one video, burst shots, several photos of one product and the same person photographed many times all look alike. A random split scatters these across train and test.
For example, say 8,000 images come from 2,000 distinct scenes, 4 photos each. A random 80/20 split puts about 3 of each scene's photos in train and 1 in test. Almost every test image then has a near-twin in train. A model that memorizes scenes scores far higher on this test set than it would on new scenes. This happens often in competitions, and the leaderboard rewards the memorizing.

Data leakage and grouped splits
A random split is fine when every image is independent, such as each one showing a different scene. When the same patient, product or scene shows up on both sides of a split, the model can recognize it in test instead of doing the task. This is called leakage.
The fix starts by finding the leaking key. That is the thing that would let the model cheat if it appeared on both sides. It might be a patient, a product, a video or a camera. A grouped split then keeps all images of one group together, entirely in train or entirely in test.

A grouped split on patient scans
Say 12,000 scans come from 3,000 patients, 4 scans each, and you want about 75 percent for training. A random split scatters each patient's 4 scans across train and test. The model can then recognize a patient in test from a scan it saw in training.
A grouped split assigns whole patients instead. About 2,250 patients (9,000 scans) go to train and 750 patients (3,000 scans) go to test. Measured accuracy usually drops by several points. That drop is the leakage the random split was hiding.

GroupShuffleSplit from scikit-learn splits by a group id so that no group ends up on both sides. Here patient_id holds one id per scan:
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
patient_id = np.repeat(np.arange(3000), 4) # 12,000 scans, 4 per patient
# shape (12000,), one id per image
groups = patient_id
gss = GroupShuffleSplit(
n_splits=1, test_size=0.25, random_state=0)
train_idx, test_idx = next(gss.split(
np.zeros(len(groups)), groups=groups))
# set(), no overlap
set(groups[train_idx]) & set(groups[test_idx])gss.split produces pairs of train and test index arrays, and next takes the first pair. Here that gives 9,000 training scans and 3,000 test scans. np.zeros(len(groups)) stands in for the images, since only the group ids decide the split. The empty intersection on the last line is the check to run on any split. The same call works with video_id, camera_id or scene_id as the group. Wrapped as a function:
def grouped_split(groups, test_size, seed):
gss = GroupShuffleSplit(n_splits=1, test_size=test_size, random_state=seed)
train_idx, test_idx = next(gss.split(np.zeros(len(groups)), groups=groups))
return train_idx, test_idxIf the intersection is not empty, some group ended up on both sides and the split has to be redone.
Time-based and location-based splits
When products, seasons or cameras change over time, train on earlier data and test on later data. That measures whether the model holds up as conditions drift.
Splitting by location tests whether the model works in places it has not seen. Backgrounds, buildings, signs and people all differ by place. They can leak across a random split.

Exact and near-duplicates
Exact duplicates are the same file saved twice. Near-duplicates show the same scene with different bytes, such as burst frames, resized copies and reposts. A grouping key cannot catch them, because the only link between the two files is how they look.

Finding near-duplicates with a hash
Comparing file bytes misses a resized copy, since resizing changes the bytes. A perceptual hash turns each image into a short string of bits that barely changes under resizing, recompression or small crops. Two images are near-duplicates when their hashes differ in only a few bits. The number of differing bits is the Hamming distance.
The imagehash library computes one with imagehash.phash, and subtracting two hashes gives the number of bits that differ. The first line below makes a half-size copy of a photo to compare against:
import imagehash
from PIL import Image
Image.open('img_0001.jpg').resize((400, 300)).save('img_0001_resized.jpg')
a = imagehash.phash(Image.open('img_0001.jpg'))
b = imagehash.phash(Image.open('img_0001_resized.jpg'))
a - b # 2 (bits different out of 64)The exact count depends on the photo. Across 60 test images, a half-size copy came out 0 bits away for 51 of them, 2 bits for 7 and 4 bits for 2. A difference of 0 to about 5 bits almost always means the same scene, and above 15 means unrelated images. Hash every image and flag close pairs before splitting. As a function that takes two image paths:
def is_near_duplicate(path_a, path_b, max_bits):
hash_a = imagehash.phash(Image.open(path_a))
hash_b = imagehash.phash(Image.open(path_b))
distance = hash_a - hash_b
return distance <= max_bitsIf too many unrelated pairs get flagged, lower max_bits before changing anything else.

What cross-split duplicates do to the score
Say 5 percent of 4,000 test images have a near-duplicate in the training set. On those 200 images the model has effectively seen the answer and scores near 100 percent. On the other 3,800 it scores its real 84 percent:
$$\frac{200 \times 1.0 + 3800 \times 0.84}{4000} \approx 0.848$$
That is less than a point of inflation. At 20 percent contamination, 800 duplicated test images, the same math gives about 0.87 against a true 0.84. The reported number then overstates the model by about three points.

Contamination
Contamination is test data showing up in the training data. Near-duplicates across the split are one way in. It can also get in through tuning settings against the test set. A third way is a pretrained model that was trained on a huge collection of web images, if that collection happened to include your test images. You usually cannot check what that collection held.
Run near-duplicate detection before splitting and record the check in the dataset's documentation. Also write down what data any pretrained model was trained on.

Common mistakes
- Splitting images at random when several come from one patient, product, video or scene. Find the leaking key and split by group.
- Checking a split by its sizes only. Check that no group id appears on both sides.
- Deduplicating by file bytes. Resized copies and burst frames have different bytes, so hash the images instead.
- Choosing models by test score. Compare on the validation set and use the test set once.
- Reading a small gap on a small test set as a real difference. At 200 test images, 2 points is within the give-or-take range.
- Assuming a pretrained model never saw your test images. Write down what it was trained on.
Related concepts
Wrong labels in the test set cap the score from the other direction, by marking correct predictions as wrong. Image annotation: label taxonomies, annotator agreement, and label noise shows how that cap works. Duplicates often come from how the photos were collected, such as burst shots from a fixed camera, which how to build your own image dataset covers.
QuiddityML teaches splits, leakage and near-duplicates in the vision data unit of its Computer Vision track. The exercises include filling in a grouped split function and putting the lines of a near-duplicate check in order (QuiddityML).