Sub topic 14
Common pitfalls and how to avoid them
This chapter assumes you can write a PyTorch training loop and know how a train/validation/test split works. It also assumes you have used torchvision.transforms or a similar library. Each pitfall below has a symptom, a cause, and a check you can run.
Leakage: augmented copies that cross the split
Leakage happens when information from the validation or test data reaches training. Augmentation creates three common routes for it.
Offline augmentation before splitting. Suppose you generate five flipped, rotated, and recolored copies of every file and then split the folder at random. A rotated copy of an image can land in training while its original lands in validation. The model has effectively seen the validation image, so validation accuracy is inflated. Split first, then augment only the training side.
Near-duplicates from the data source. Video frames, multiple scans of one patient, and several photos of one product are close to duplicates even without augmentation. Augmentation makes the problem worse because a lightly altered duplicate is even harder to spot. Split by the group that defines the real unit of generalization (video, patient, product), not by file.
Statistics computed on the wrong data. If you compute normalization mean and standard deviation, or any other fitted parameter, from the validation or test set, you leak a small amount of information. Compute them on the training set only.
import random
def split_by_group(samples, val_fraction=0.2, seed=0):
# samples: list of (path, label, group_id)
groups = sorted({g for _, _, g in samples})
random.Random(seed).shuffle(groups)
n_val = max(1, int(len(groups) * val_fraction))
val_groups = set(groups[:n_val])
train = [s for s in samples if s[2] not in val_groups]
val = [s for s in samples if s[2] in val_groups]
return train, val
samples = [(f"img_{i}.jpg", i % 2, f"video_{i // 5}") for i in range(20)]
train, val = split_by_group(samples)
train_groups = {s[2] for s in train}
val_groups = {s[2] for s in val}
assert train_groups.isdisjoint(val_groups)
print(len(train), len(val))The assertion is the useful part. Keep a check like it in your data preparation code, so a changed split fails loudly instead of silently inflating metrics.
Transforms that change the label
A transform is label-preserving only relative to a task. Horizontal flipping is safe for cats and unsafe for text. Before adding a transform, ask whether a human annotator would give the same label to the transformed image.
| Task | Risky transform | Why it breaks |
|---|---|---|
| Digit or character recognition | Horizontal flip, 180° rotation | A flipped or rotated "6" can look like a "9", and mirrored letters are not valid letters. |
| Left/right or direction labels | Horizontal flip | The flip swaps the meaning of "left" and "right" without changing the label. |
| Color-defined classes (ripe/unripe fruit, traffic lights) | Hue shift, strong saturation change | The class is carried by color. |
| Small-object detection or medical lesions | Aggressive random crop, random erasing | The object may be cropped or erased while the label still says it is present. |
| Texture or fine-detail tasks | Strong blur, heavy downscaling | The discriminating signal is destroyed. |
| Aerial and microscope images | Usually safe to flip vertically and rotate | Here the opposite holds: these tasks have no canonical "up", so these transforms are useful. |
RandomResizedCrop(224, scale=(0.08, 1.0)), the common default, can keep as little as 8% of the image. For an object that occupies a small part of the frame, many crops will contain only background. Raise the lower bound of scale (the earlier examples used 0.5) when objects are small or sparse.
Label changes can also be indirect. Mixup and CutMix create blended labels on purpose, so any metric computed on augmented training batches means something different from accuracy on clean images. Report training accuracy from a clean pass if you need to compare it with validation accuracy.
Domain mismatch
Augmentation should simulate variation you expect at deployment. It should not simulate variation you will never see.
- If a camera always produces sharp, well-lit images, heavy blur and strong brightness jitter spend model capacity on conditions that never occur.
- If deployment images are noisy and compressed, but training augmentation only flips and crops, the model meets a shift it was never exposed to. Add noise, blur, or JPEG-style degradation that matches what you actually see.
- Apparent object size differs between training and evaluation.
RandomResizedCropzooms in, so objects look larger in training than in a plain resize-and-center-crop evaluation. This is the train/test resolution discrepancy described in the FixRes paper (Touvron et al., 2019). If validation accuracy is lower than expected for a model trained with strong cropping, evaluating at a somewhat higher resolution can help. Treat this as an experiment, not a rule.
A practical check is to collect a few dozen real deployment images and compare them with your augmented training images. If the augmented images look nothing like deployment, the policy needs revising.
Train/eval mismatch
The evaluation pipeline must be deterministic and must match training in everything except randomness. Four mistakes are common.
- Random transforms in the evaluation pipeline. Metrics then vary from run to run, and a comparison between two models may only reflect different random crops.
- Different normalization. If training uses ImageNet mean and standard deviation and evaluation does not, accuracy drops sharply with no error message.
- Different channel order or value range. OpenCV loads images as BGR, while torchvision pretrained weights expect RGB. A pipeline that mixes
cv2.imreadwith PIL-based transforms can swap channels. Scaling to 0–1 versus 0–255 is a similar trap. - Wrong transform order.
RandAugmentandColorJitteroperate on PIL images or uint8 tensors, so they come beforeToTensorandNormalize.RandomErasingworks on tensors, so it comes after. AfterNormalize, pixel values are no longer in the 0–1 range, so brightness and contrast operations that clamp values give wrong results.
You can test the determinism requirement directly:
import numpy as np
import torch
from PIL import Image
from torchvision import transforms
def is_deterministic(tf, image, trials=3):
outs = [tf(image) for _ in range(trials)]
return all(torch.equal(outs[0], o) for o in outs[1:])
pixels = np.random.default_rng(0).integers(0, 256, (300, 300, 3), dtype=np.uint8)
image = Image.fromarray(pixels)
norm = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
eval_tf = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
norm,
])
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
norm,
])
print("eval deterministic:", is_deterministic(eval_tf, image))
print("train deterministic:", is_deterministic(train_tf, image))The first line prints True. The second prints False in practice, because the random crop makes three identical outputs very unlikely. Put the first check in your tests for the evaluation pipeline.
Randomness that is not random
When a DataLoader uses several worker processes, each worker gets its own copy of the dataset object. If your augmentation code owns a random generator created at import time, every worker starts from the same generator state. Different workers then produce the same "random" flips and crops, and your effective augmentation diversity drops. The random_hflip function in the paired-target example has this problem if it is used with workers.
import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
shared_rng = np.random.default_rng(0) # created once, copied into each worker
class BuggyDraws(Dataset):
def __len__(self):
return 8
def __getitem__(self, i):
return torch.tensor(shared_rng.random())
class FixedDraws(Dataset):
def __init__(self):
self.rng = None
def __len__(self):
return 8
def __getitem__(self, i):
if self.rng is None:
# torch.initial_seed() differs for every worker
self.rng = np.random.default_rng(torch.initial_seed())
return torch.tensor(self.rng.random())
def first_draws(dataset):
loader = DataLoader(dataset, batch_size=1, num_workers=2, shuffle=False)
return [round(b.item(), 3) for b in loader]
if __name__ == "__main__":
print("buggy:", first_draws(BuggyDraws()))
print("fixed:", first_draws(FixedDraws()))With two workers, items 0 and 1 come from different workers. In the buggy version they receive the same first value, and so do items 2 and 3. In the fixed version, each worker draws from its own stream. The if __name__ == "__main__": guard is required on platforms that start workers by spawning a new process.
Library transforms such as torchvision.transforms draw from PyTorch's random state, which PyTorch seeds separately in each worker. The risk is mainly in your own code that uses NumPy or Python generators. For reproducible experiments, set a seed for the main process and a worker_init_fn or generator argument on the DataLoader. Reproducibility means the same seed gives the same run on the same setup. It does not mean the augmentations are identical every epoch, which would defeat the purpose.
Masks and boxes that drift out of alignment
Segmentation and detection need pixels and annotations to transform together. The usual failures are listed below.
- Independent random draws. Calling a flip on the image and again on the mask gives two separate coin tosses. Draw once and apply the result to both, as in the earlier paired example.
- Wrong interpolation for masks. Bilinear interpolation on a mask with class IDs 1, 2, and 3 creates values like 1.5 that match no class. Use nearest-neighbor interpolation for masks.
- Boxes that are not updated. A horizontal flip moves boxes. Crops clip boxes and can remove them. After a crop, drop boxes whose remaining area is too small, and drop their labels too.
- Photometric transforms applied to masks. Color changes apply to the image only.
import numpy as np
def hflip_boxes(boxes, width):
# boxes: (N, 4) array of [x_min, y_min, x_max, y_max] in pixels
flipped = boxes.copy()
flipped[:, 0] = width - boxes[:, 2]
flipped[:, 2] = width - boxes[:, 0]
return flipped
boxes = np.array([[10, 20, 50, 80], [100, 30, 140, 90]])
print(hflip_boxes(boxes, width=200))The first box moves from x range 10–50 to 150–190, and x_min stays smaller than x_max. If the swap is skipped, boxes have negative width and training silently breaks.
Too much augmentation
More augmentation is not always better. Signs that the policy is too strong:
- Training loss stays high and the training accuracy on clean images is low (underfitting).
- Validation accuracy is lower than a run with weaker augmentation.
- Small models or short training schedules suffer more, because they cannot absorb the extra variety within the available epochs.
Strong policies such as RandAugment with a high magnitude, mixup, and CutMix usually need longer schedules to pay off. Change one setting at a time and compare against a baseline run with the same seed.
A debugging checklist
Always look at the data. Dump a grid of 16 augmented training images with their labels, masks, or boxes drawn on top, and repeat it after every pipeline change. Most label-changing transforms, channel swaps, and misaligned masks are visible within seconds.
Exercise
A team builds a classifier for handwritten digits. They generate five offline copies of each image (random rotations up to 180°, horizontal flips, and color jitter), then randomly split all files into 80% train and 20% validation. Validation accuracy is 99%, but accuracy on new scanned forms is 85%. Name three problems and a fix for each.
Show answer
First, the split happens after augmentation, so copies of the same source image appear in both train and validation. This leakage inflates the 99%. Fix: split by source image first, then augment only the training set. Second, rotation up to 180° and horizontal flips change digit identity (6 and 9 look alike, and mirrored digits are not valid digits), so some augmented labels are wrong. Fix: use small rotations (for example ±15°) and remove flips. Third, color jitter and the other transforms may not match the real scanned forms, which is a domain mismatch. Fix: compare augmented samples with real scans, and use augmentations that imitate scanner variation such as slight blur, noise, and contrast changes.
Exercise
You use a DataLoader with 4 workers, and your augmentation function calls a NumPy generator created at module level with np.random.default_rng(0). Why might the augmentations be less varied than expected, and how do you fix it?
Show answer
Each worker receives a copy of the same generator state, so workers produce identical random sequences and repeat the same flips and crops. Fix it by creating the generator lazily inside each worker from a per-worker seed such as torch.initial_seed(), or by seeding in a worker_init_fn.