Why Preprocessing Is Part of the Model
A network trained on images learned from tensors of one exact size, scale and colour statistics. A pretrained network from torchvision was trained on ImageNet photographs that were resized, cropped to 224 by 224 and normalised with fixed numbers. To use it, every image you give it must go through the same steps. If one step differs, nothing fails: the network still returns ten or a thousand scores, but it is answering a question about inputs it never saw. The same applies to a network you train yourself: training and prediction must share preprocessing exactly.
This lesson builds that preprocessing from torchvision's transforms v2,
the torchvision.transforms.v2 module, and checks it against the version
torchvision ships with each set of pretrained weights.
The Steps and What Each Does

Read the diagram from the top, following the shape. v2.Resize(256)
scales the image so that its shorter side is 256 pixels and keeps the
proportions: a scene 300 pixels high and 400 wide becomes 256 by 341,
because 400 times 256 divided by 300 is 341.3 and the size is rounded down. Resizing has to invent
pixel values between the old ones; bilinear interpolation blends the
four nearest, and antialias=True, the default, smooths first so that
shrinking does not create jagged patterns.
v2.CenterCrop(224) cuts the central 224 by 224 square, discarding the
edges of the longer side. Resizing then cropping keeps proportions; resizing
straight to 224 by 224 would stretch or squash the picture.
v2.ToDtype(torch.float32, scale=True) turns uint8 0 to 255 into
float32 0.0 to 1.0, as in Decode and inspect images.
v2.Normalize(mean, std) computes, for each channel, (value - mean) / std. The numbers [0.485, 0.456, 0.406] and [0.229, 0.224, 0.225] are
the average and spread of red, green and blue over ImageNet's training
photographs. After normalising, each channel averages 0 with a spread of 1
over those photographs, which is what the network's first layer was trained
on. A value of 0 becomes -2.12 in the red channel,
and 1 becomes 2.64 in the blue.
v2.Compose([...]) chains the steps into one callable, applied in order.
The Preprocessing Bundled with Weights
Every pretrained weight set in torchvision carries its preprocessing:
ResNet18_Weights.IMAGENET1K_V1.transforms() returns it, and printing it
shows its settings. It is a preset object, not a Compose, but it does the
same steps. Using weights.transforms() is the safest way to match a
pretrained network, and it needs no download: the numbers are stored in
torchvision, not in the weight file. Rebuilding it by hand shows what it
does, and is how you would write preprocessing for a network that does not
come with one.
Exercise: Rebuild the Bundled Preprocessing
You will build the pipeline by hand, compare it with
weights.transforms() on the same image, then break it in two common ways
and measure the difference.
Starting state: the course environment from the setup lesson.
Effects: creates scene.png and reference.pt in the lesson folder.
weights.transforms() downloads nothing; no network access.
Output: Outputs shown below are illustrative. Shapes and the printed values should match.
-
In a terminal with the course environment active and
TORCH_HOMEset (see Set up the pinned CPU environment), create the lesson folder. macOS and Linux:mkdir -p ~/cv-practice/resize-crop-and-normalise cd ~/cv-practice/resize-crop-and-normaliseWindows PowerShell:
mkdir $HOME\cv-practice\resize-crop-and-normalise cd $HOME\cv-practice\resize-crop-and-normalise -
Save this as
make_scene.py:"""Draw a test scene 400 pixels wide and 300 high: a sky-to-ground gradient with a few shapes.""" from PIL import Image, ImageDraw image = Image.new("RGB", (400, 300)) draw = ImageDraw.Draw(image) for y in range(300): shade = int(80 + y * 0.5) draw.line([(0, y), (399, y)], fill=(shade // 2, shade, 255 - shade // 2)) draw.ellipse([60, 80, 160, 180], fill=(230, 60, 40)) draw.rectangle([220, 140, 330, 250], fill=(250, 210, 40)) draw.polygon([(180, 40), (230, 120), (130, 120)], fill=(30, 120, 60)) image.save("scene.png") print("scene.png:", image.size, image.mode)Pillow's
ImageDrawpaints a sky-to-ground gradient and three shapes on a 400 by 300 canvas; Pillow gives sizes as width then height. Run it withpython make_scene.py:scene.png: (400, 300) RGB -
Save this as
preprocess.py:"""Rebuild ResNet-18's bundled preprocessing with v2 transforms and compare.""" import torch from PIL import Image from torchvision.models import ResNet18_Weights from torchvision.transforms import v2 weights = ResNet18_Weights.IMAGENET1K_V1 bundled = weights.transforms() print(bundled) by_hand = v2.Compose([ v2.Resize(256, interpolation=v2.InterpolationMode.BILINEAR, antialias=True), v2.CenterCrop(224), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), ]) image = v2.ToImage()(Image.open("scene.png")) print("decoded:", tuple(image.shape), image.dtype) reference = bundled(image) mine = by_hand(image) print("bundled:", tuple(reference.shape), reference.dtype) print("by hand:", tuple(mine.shape), mine.dtype) difference = (reference - mine).abs() print("largest difference:", f"{difference.max().item():.4f}", "| values that differ:", f"{(difference > 1e-6).float().mean().item():.2%}") print("channel means:", [round(m, 3) for m in mine.mean(dim=(1, 2)).tolist()]) torch.save(reference, "reference.pt")The script prints the bundled preset, builds the same steps by hand and runs both on the scene. The largest difference and the share of values that differ are the comparison; the channel means show what normalising did.
reference.ptkeeps the correct tensor for the next step. Run it withpython preprocess.py:ImageClassification( crop_size=[224] resize_size=[256] mean=[0.485, 0.456, 0.406] std=[0.229, 0.224, 0.225] interpolation=InterpolationMode.BILINEAR ) decoded: (3, 300, 400) torch.uint8 bundled: (3, 224, 224) torch.float32 by hand: (3, 224, 224) torch.float32 largest difference: 0.0175 | values that differ: 0.12% channel means: [-0.055, 0.607, 0.505]
Why the Two Are Not Exactly Equal
The bundled preset was written with torchvision's older transforms
functions; v2.Resize uses a newer implementation for uint8 images. Both
round the resized values to whole numbers, and they round about one value in
a thousand differently, by one step out of 255. One step, divided by the
green channel's standard deviation of 0.224, is 1 / 255 / 0.224 = 0.0175:
exactly the largest difference printed. Two pipelines that agree to within
one rounding step are the same preprocessing; a difference of 0.1 or more
would mean a different step.
-
Save this as
mismatch.py:"""Two common preprocessing mistakes, measured against the correct tensor.""" import torch from PIL import Image from torchvision.transforms import v2 reference = torch.load("reference.pt") image = v2.ToImage()(Image.open("scene.png")) mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225] no_normalise = v2.Compose([ v2.Resize(256, antialias=True), v2.CenterCrop(224), v2.ToDtype(torch.float32, scale=True), ])(image) squashed = v2.Compose([ v2.Resize((224, 224), antialias=True), v2.ToDtype(torch.float32, scale=True), v2.Normalize(mean=mean, std=std), ])(image) for name, t in [("correct", reference), ("no Normalize", no_normalise), ("squashed to 224", squashed)]: print(f"{name:<16} shape={tuple(t.shape)} min={t.min().item():6.3f} max={t.max().item():6.3f} " f"mean={t.mean().item():6.3f} mean abs difference={(t - reference).abs().mean().item():.3f}")Run it with
python mismatch.py. Illustrative output:correct shape=(3, 224, 224) min=-1.604 max= 2.163 mean= 0.352 mean abs difference=0.000 no Normalize shape=(3, 224, 224) min= 0.118 max= 0.980 mean= 0.528 mean abs difference=0.864 squashed to 224 shape=(3, 224, 224) min=-1.604 max= 2.163 mean= 0.367 mean abs difference=0.416
Reading the Result
All three tensors have the shape a network expects, so a network would accept every one of them. Without Normalize the values stay between 0.118 and 0.980 (30 and 250 out of 255, the scene's darkest and brightest colours), all positive, and every value is on average 0.864 away from what the network should see. Squashing to 224 by 224 keeps the range, because the same colours are present, but moves every shape: the whole 400-pixel width is squeezed into 224 columns instead of the middle being cropped, so values differ by 0.416 on average. Neither mistake raises an error. The printed range and the comparison with a reference tensor are what catch them.
Success: the by-hand pipeline matches the bundled one to within 0.0175, and both mistakes show mean differences far larger than that.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
TypeError: Input tensor should be a float tensor. Got torch.uint8. | Normalize placed before ToDtype | Convert to float first |
TypeError: Normalize() does not support PIL images. | The pipeline was given a Pillow image without ToImage | Start the pipeline with a tensor |
| A largest difference near 1 or 2 | A different mean or standard deviation, or a missing step | Compare your pipeline with the printed preset line by line |
Shape (3, 256, 341) at the end | CenterCrop missing | Add it after Resize |
Reset: run python make_scene.py and python preprocess.py again; they
overwrite scene.png and reference.pt.
Independent task: at the end of preprocess.py, apply the steps of
by_hand one at a time, looping over by_hand.transforms, and print each
step's class name with the shape, dtype, minimum and maximum after it. Write
your predictions for all four lines first.
Hint 1: by_hand.transforms is a plain list: apply each step to the
output of the one before.
Hint 2: Only ToDtype changes the dtype, and only Normalize can make
values negative.
-
Clean up. macOS and Linux:
cd ~/cv-practice ls rm -rf resize-crop-and-normaliseWindows PowerShell:
cd $HOME\cv-practice ls Remove-Item -Recurse resize-crop-and-normaliseCheck that
lslistsresize-crop-and-normalisebefore you remove it. The environment,weightsanddatastay for later lessons.
Check Your Understanding
- An inference script skips
Normalizebefore calling a pretrained network. What happens, and why does nothing report an error? - A photograph is 300 pixels wide and 400 high. What shape does
v2.Resize(256)give, and thenv2.CenterCrop(224)?
Answer and Reasoning
Independent task
x = v2.ToImage()(Image.open("scene.png"))
for step in by_hand.transforms:
x = step(x)
print(f"{type(step).__name__:<11} shape={tuple(x.shape)} dtype={x.dtype} min={x.min().item():.3f} max={x.max().item():.3f}")
Resize shape=(3, 256, 341) dtype=torch.uint8 min=30.000 max=250.000
CenterCrop shape=(3, 224, 224) dtype=torch.uint8 min=30.000 max=250.000
ToDtype shape=(3, 224, 224) dtype=torch.float32 min=0.118 max=0.980
Normalize shape=(3, 224, 224) dtype=torch.float32 min=-1.604 max=2.163
Resizing and cropping change the shape but not the type; the darkest and
brightest colours survive both. Only ToDtype changes the type, and only
Normalize moves the values below zero.
Understanding check
- The network receives values from 0 to 1, all positive, where it was trained on values centred near 0 in each channel. Its first layer multiplies inputs by learned weights; shifted inputs shift every feature after it, so the scores, and often the predicted class, change. Nothing reports an error because the shape and type are still right: the network cannot tell that the numbers mean something else. Predict with pretrained weights measures how much the predictions change.
(3, 341, 256): the shorter side, now the width, becomes 256, and the height becomes 400 times 256 divided by 300, which is 341.3, rounded down. Then(3, 224, 224): the crop keeps the middle 224 rows and columns, removing 117 rows, about half from the top and half from the bottom, and 16 columns from each side.