Sub topic 13
Inspecting, validating, and tuning augmentation strength
This chapter assumes you can write a PyTorch training loop, know the train/validation/test split, and have met the transforms from earlier chapters (geometric, photometric, occlusion, mixing, and automated policies). Here you will check that an augmentation setup does what you intended, then tune how strong it is.
Why augmentation needs checking
Augmentation bugs rarely raise errors. A pipeline that flips a segmentation mask differently from its image, or crops away the object, still trains. The loss goes down and the accuracy is a little worse than it should be. You will not see the cause unless you look at the data.
Strength is the second problem. Too little augmentation leaves overfitting in place. Too much makes the training distribution differ from the test distribution, and the model underfits. The right level depends on dataset size, model capacity, and training length. You find it by experiment, not by copying a recipe.
Step 1: Look at the images
Before any training run, save a grid of augmented samples and look at it. Check these things:
- The object is still visible and still recognizable in most samples.
- The label still holds. A flipped "6" and a flipped "9" are different problems from a flipped cat.
- Colors look plausible for your domain. Heavy hue shifts can turn a ripe fruit into an unripe one.
- Borders look acceptable. Large black or reflected regions from rotation suggest the angle range is too wide.
- Masks and boxes still line up with the objects they describe.
The script below draws the same image through a pipeline several times. It undoes normalization so the colors are displayable.
import torch
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from PIL import Image
from torchvision import transforms
mean = torch.tensor([0.485, 0.456, 0.406]).view(3, 1, 1)
std = torch.tensor([0.229, 0.224, 0.225]).view(3, 1, 1)
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
transforms.ToTensor(),
transforms.Normalize(mean.flatten().tolist(), std.flatten().tolist()),
])
def denormalize(t):
return (t * std + mean).clamp(0, 1)
def save_grid(image, tf, path="aug_grid.png", n=16):
fig, axes = plt.subplots(4, 4, figsize=(8, 8))
for ax in axes.flat:
sample = denormalize(tf(image))
ax.imshow(sample.permute(1, 2, 0).numpy())
ax.axis("off")
fig.tight_layout()
fig.savefig(path, dpi=100)
plt.close(fig)
if __name__ == "__main__":
# Replace with a path to any image on your machine.
img = Image.new("RGB", (320, 240), (200, 120, 40))
save_grid(img, train_tf)Run it on several different images, not one. Include the hardest cases in your data: small objects, objects near the edge, and dark images. Re-run it every time you change the pipeline.
Look at batches from the real DataLoader too, not only from a standalone transform. This catches bugs in the dataset class, such as a transform applied to the wrong field. It also catches a missing .copy() after a negative-stride flip.
Step 2: Check the numbers
Visual inspection finds semantic problems. Numeric checks find plumbing problems.
- Tensor statistics. After normalization, a batch should have per-channel mean near 0 and standard deviation near 1 if your mean and std match the data. Large offsets mean the wrong constants or a missing
ToTensorscaling step. - Dtype and range. Confirm the dtype (
float32) and the range beforeNormalize:[0, 1]afterToTensor. - Shape. Confirm every sample has the same shape, or the collate function will fail or silently pad.
- Label distribution. Count labels over one epoch of augmented data. Mixing methods and crops should not shift class frequency.
- Determinism of evaluation. Run the evaluation pipeline twice on the same image and assert the outputs are equal.
import torch
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
eval_tf = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
from PIL import Image
img = Image.new("RGB", (300, 300), (90, 140, 200))
a = eval_tf(img)
b = eval_tf(img)
assert a.dtype == torch.float32
assert a.shape == (3, 224, 224)
assert torch.equal(a, b), "evaluation pipeline is not deterministic"
print("eval pipeline OK")For reproducing a specific augmented sample, remember that DataLoader workers each have their own random state. PyTorch seeds each worker's torch generator differently per epoch, but if your transforms use NumPy's global generator, older versions of NumPy could produce identical random streams in every worker. Use torch random functions inside transforms, or seed NumPy in a worker_init_fn.
Step 3: Test the pipeline with controlled experiments
Once the data looks right, ask whether augmentation actually helps. The only reliable way is to compare runs that differ in one thing.
- Train a baseline with only the minimum preprocessing: resize and normalize, no random transforms.
- Train again with one augmentation added. Keep the seed, schedule, and model the same.
- Compare the validation metric, not the training metric.
- Repeat with different seeds when the difference is small.
Run several seeds. A change of 0.3 points in accuracy is often within seed-to-seed noise. If three seeds of each setup overlap, you have not shown a difference.
Add transforms one at a time, or remove them one at a time from a full pipeline (an ablation). Ablation tells you which parts carry weight. It often shows that two or three transforms give most of the gain.
Reading the learning curves
The gap between training and validation metrics tells you which direction to move.
| Symptom | Likely cause | Adjustment |
|---|---|---|
| Training accuracy near 100%, validation much lower | Overfitting, augmentation too weak | Increase strength or add transform types |
| Training and validation both low, small gap | Underfitting, augmentation too strong or model too small | Reduce strength, train longer, or enlarge model |
| Training loss noisy and slow to fall | Heavy augmentation or aggressive mixing | Lower magnitude, reduce mixing probability |
| Validation worse than training on a specific condition | Domain mismatch | Add transforms that simulate that condition |
| Validation fluctuates between epochs | Small validation set or unstable training | Use more seeds, a larger validation set, or EMA weights |
Training accuracy measured on augmented data is lower than on clean data, so a lower training accuracy by itself does not mean something broke. To compare fairly, also compute training accuracy using the evaluation transform, on a subset of the training set. This shows whether the model fits the clean data.
Tuning strength
Every transform has parameters that set how strong it is. Common ones:
- Crop scale range in
RandomResizedCrop. A lower bound of 0.08 is aggressive. 0.5 to 0.8 is gentler and suits small objects. - Rotation angle limit. Often 10 to 30 degrees for natural photos. Close to 0 for text or orientation-dependent data.
ColorJitterfactors. 0.1 to 0.4 is a common range.- Probability
pfor each random transform. - RandAugment
magnitudeandnum_ops. - Mixup
alphaand CutMix probability. - RandomErasing
pand area range.
Tune in a sensible order
- Start from a recipe known to work for your model family and image size.
- Fix the geometric transforms first, since they affect label validity most.
- Add photometric transforms that match real variation in your deployment data.
- Add regularizing transforms (RandomErasing, mixup, CutMix) last, and only if overfitting remains.
- Tune one strength knob at a time on a coarse grid, for example magnitude 3, 6, 9, 12.
With RandAugment you have two knobs, which makes a small grid practical:
import itertools
from torchvision import transforms
def make_train_tf(num_ops, magnitude):
return transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.RandAugment(num_ops=num_ops, magnitude=magnitude),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
grid = list(itertools.product([1, 2], [3, 6, 9, 12]))
for num_ops, magnitude in grid:
tf = make_train_tf(num_ops, magnitude)
print(f"num_ops={num_ops} magnitude={magnitude} -> train and compare on validation")Strength depends on other settings
- Dataset size. Small datasets benefit from stronger augmentation. Large ones need less.
- Model capacity. Larger models overfit more easily and tolerate stronger augmentation.
- Training length. Strong augmentation slows convergence. A short schedule may favor mild settings, while a long schedule can use heavy augmentation and still converge.
- Resolution. Crops at low resolution remove a larger share of the useful detail.
When you change one of these, re-check augmentation strength.
Validation rules that protect your results
- Tune on the validation set. Report once on the test set at the end. If you keep tuning against the test set, your final number is optimistic.
- Never apply random augmentation to validation or test images. Only deterministic preprocessing belongs there.
- A fixed validation set is needed to compare runs. If you split randomly each run, differences can come from the split.
- When data is small, use cross-validation, and keep augmentation inside each training fold only.
- Duplicate or near-duplicate images (including offline augmented copies) must stay on one side of the split. Augment after splitting, not before.
Test-time augmentation (averaging predictions over several transformed copies of a test image) is a separate technique. If you use it, the transforms must be label-preserving and fixed in number, and you should report it separately from the single-view result.
A short debugging checklist
- Save and view a grid of augmented training samples.
- Confirm the evaluation pipeline is deterministic and has no random transforms.
- Compare normalized batch statistics against expectations.
- Overfit a tiny subset (say 32 images) with augmentation turned off. If the model cannot reach near-zero loss, the bug is elsewhere.
- Turn augmentation on for the same subset. Loss should still fall, though more slowly.
- Check training accuracy with the evaluation transform to separate fitting problems from augmentation noise.
- Run an ablation with at least three seeds before keeping a transform.
Exercise
Your model reaches 99% training accuracy (measured on augmented batches) and 71% validation accuracy. You add RandomErasing and raise RandAugment magnitude from 5 to 10. Validation rises to 74%, but training accuracy on augmented batches falls to 88%. Is something wrong, and what should you check next?
Show answer
Nothing is necessarily wrong. Stronger augmentation makes augmented training batches harder, so lower training accuracy on them is expected, and validation improved. Next, measure training accuracy with the evaluation transform on a training subset to confirm the model still fits clean data. Then view a grid of augmented samples to confirm the labels still hold, run at least three seeds to check that the 3-point gain exceeds seed noise, and look at per-class metrics. If the gap is still large, try a further increase in strength; if clean training accuracy dropped sharply, the augmentation is too strong.
Exercise
A teammate augments the whole dataset offline to triple its size, then splits it randomly into train and validation sets. Validation accuracy is very high but the model performs poorly in production. What is the likely cause, and how do you fix it?
Show answer
Augmented copies of the same original image can land in both the training and validation sets, which leaks training information into validation and inflates the metric. Split the original images first, then augment only the training portion (preferably online during training), and keep the validation set free of random transforms.