Sub topic 9
Training versus evaluation transforms
This chapter assumes you can write a PyTorch training loop, you know the train/validation/test split, and you have seen the individual transforms from earlier chapters (flips, crops, color jitter, random erasing). Here the question is where each transform belongs once you build a full pipeline.
Two pipelines, two jobs
Augmentation exists to make the training set look more varied than it is. That helps the model generalize. It would hurt a measurement.
- The training pipeline is random. Each time an image is loaded it comes out differently. The model never sees the exact same input twice, which acts as a regularizer.
- The evaluation pipeline is deterministic. The same image always yields the same tensor. Validation and test metrics are then reproducible, and a change in accuracy between two runs reflects the model and not the dice rolls of the data loader.
Evaluation should also measure what you will face in deployment. In deployment nobody randomly crops or recolors the input, so the evaluation pipeline does only what is needed to get an image into the shape and scale the network expects.
What goes where
| Step | Training | Evaluation | Reason |
|---|---|---|---|
| Random resized crop | Yes | No | Randomness; evaluation uses a fixed resize and crop |
| Horizontal flip | Yes (if label-preserving) | No | Randomness |
| Color jitter, RandAugment | Yes | No | Randomness |
| Resize and center crop | No | Yes | Deterministic geometry |
| ToTensor | Yes | Yes | Converts PIL to a float tensor in [0, 1] |
| Normalize | Yes | Yes | The model must see the same input statistics in both |
| Random erasing | Yes (after ToTensor) | No | Randomness, works on tensors |
The last two rows of the shared steps are the key rule: everything that converts format or scale is shared, and everything random is training only. If normalization differs between the two pipelines, the model is evaluated on inputs from a different distribution than it trained on, and accuracy drops with no error message.
The training pipeline
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
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=mean, std=std),
])The order matters. The geometric and color transforms run on a PIL image, then ToTensor converts it to a float tensor with values in [0, 1], and Normalize subtracts the mean and divides by the standard deviation per channel. If you add RandomErasing, it goes after Normalize or at least after ToTensor, because it operates on tensors.
The mean and std values above are the ImageNet statistics. Use them when you fine-tune a model pretrained on ImageNet. If you train from scratch on your own data, compute the statistics on the training split only.
The evaluation pipeline
from torchvision import transforms
from torchvision.datasets import ImageFolder
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=mean, std=std),
])
val_ds = ImageFolder("data/val", transform=eval_tf)Resize(256) scales the shorter side to 256 pixels and keeps the aspect ratio. CenterCrop(224) then cuts the central 224 by 224 square. The ratio 224/256 = 0.875 is a common convention: it keeps the central object and drops some background near the edges.
Nothing here is random, so running it twice gives identical tensors.
Wiring the right transform to the right split
The most common implementation bug is not choosing the wrong transforms. It is attaching them to the wrong dataset. If you build one ImageFolder with train_tf and then call random_split, both halves share that one transform, so your validation set is augmented. Changing dataset.transform afterwards changes it for both halves too.
A safe pattern is to load the base dataset without a transform, so it returns PIL images, then wrap each split with its own transform.
import torch
from torch.utils.data import Dataset, random_split
from torchvision import transforms
from torchvision.datasets import ImageFolder
class TransformSubset(Dataset):
"""Applies its own transform to one split of a shared base dataset."""
def __init__(self, subset, transform):
self.subset = subset
self.transform = transform
def __len__(self):
return len(self.subset)
def __getitem__(self, i):
image, label = self.subset[i]
return self.transform(image), label
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
eval_tf = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
base = ImageFolder("data/all") # no transform: items are (PIL image, label)
gen = torch.Generator().manual_seed(0)
train_part, val_part = random_split(base, [0.8, 0.2], generator=gen)
train_ds = TransformSubset(train_part, train_tf)
val_ds = TransformSubset(val_part, eval_tf)The seeded generator makes the split itself reproducible. If your already lives in separate train and val folders, you do not need this wrapper. Create two ImageFolder objects, one per folder, as in the previous section.
Check that the pipelines behave as intended
Do not trust that the evaluation pipeline is deterministic. Test it. The script below builds a synthetic image, so it runs without any data on disk.
import torch
from PIL import Image
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
eval_tf = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
img = Image.effect_noise((300, 200), 50).convert("RGB")
torch.manual_seed(val_tf(img), eval_tf(img)
print("eval identical:", torch.equal(a, b)) # True
c, d = train_tf(img), train_train identical:", torch.equal(c, d)) # almost surely False
print("shapes:", a.shape, c# both torch.Size([3, 224, 224])Both pipelines must output the same shape, because the model has one fixed input size. The must match exactly and the training pair should not.
Two different things called "train mode"
Switching the model with model.train() and model.eval() is separate from choosing a transform pipeline. The model mode controls layers such as dropout and batch normalization. The transform pipeline is decided entirely by which dataset the batch came from. Calling model.eval() does not disable augmentation, and using val_ds does not put batch norm into inference mode. You need both set correctly in your validation loop: model.eval(), torch.no_grad(), and a loader built on the evaluation dataset.
Object size and the train-test resolution gap
RandomResizedCrop zooms into part of the image and resizes the crop to 224, so objects usually look larger in training than they do after the evaluation's resize and center crop. This is the train-test resolution discrepancy. The model is trained on apparent object sizes that are on average bigger than the ones it sees at test time.
Two practical consequences:
- If you raise the crop scale range (for example
scale=(0.8, 1.0)), the gap shrinks, but you give up some augmentation strength. - Some models improve when evaluation uses a slightly larger resolution than training, for example
Resize(288)withCenterCrop(256)for a model trained at 224. Treat this as something to measure on the validation set, not a rule.
Test-time augmentation is a deliberate exception
Test-time augmentation (TTA) runs several deterministic variants of one test image, such as the original and its horizontal flip, and averages the predictions. It is the one place where evaluation uses more than a single fixed view. Keep it explicit and fixed (the same list of views every time), and report it separately from the plain single-view result. Never use random transforms in evaluation and call the outcome a metric.
Where the pipelines diverge
Common mistakes
- Augmented validation set. Caused by a shared transform after
random_split. Symptom: validation accuracy is lower and noisier than expected, and changes between evaluations. - Missing normalization in evaluation. Training sees normalized inputs, evaluation sees values in [0, 1]. Symptom: validation accuracy far below training accuracy from the very first epoch, even with little overfitting.
- Different normalization statistics. Using ImageNet statistics for one pipeline and dataset statistics for the other has the same effect, with a smaller magnitude.
- Different channel order or color mode. Grayscale or RGBA files give tensors with 1 or 4 channels. Convert with
.convert("RGB")in the dataset, not only in training. - Random transform after normalization where it expects [0, 1]. Some operations assume value ranges. Check the documented input type of each transform.
Exercise
A teammate builds ImageFolder("data/all", transform=train_tf), splits it with random_split into 80% train and 20% validation, and reports a validation accuracy that changes by about 2 points each time the same checkpoint is evaluated. What is the likely cause, and how do you fix it without changing the model?
Show answer
The validation subset still uses train_tf, which contains random crops, flips, and color changes, so every pass over the same images produces different inputs and a different accuracy. Load the base dataset without a transform, split it with a seeded generator, and wrap each split with its own transform (random pipeline for training, resize, center crop, ToTensor, and Normalize for validation). Then re-evaluating the same checkpoint gives the same number.
Exercise
Your evaluation pipeline normalizes with the ImageNet mean and std, but the training pipeline forgot Normalize. Training loss looks fine. What do you expect to see on validation, and what check would catch the problem before training?
Show answer
Validation accuracy will be much worse than training accuracy, because the model trained on inputs in [0, 1] but is evaluated on mean-shifted, rescaled inputs. A check before training is to print the mean and std of a batch from each loader, which should be near 0 and 1 per channel for both, and to compare the shapes and value ranges of one training tensor and one evaluation tensor.