Classify a Photo with a Pretrained Model
Training an image classifier from nothing takes a million labelled photos and days of computing. A pretrained model skips all of that: you download weights someone else already trained, prepare your photo exactly the way those weights expect, and read back the classes the network thinks are most likely. Knowing what such a model can and cannot answer, and why the preparation matters so much, is what makes its answers trustworthy.
Weights that someone else trained
A network is a fixed arrangement of layers plus a long list of numbers, its weights. The arrangement alone classifies nothing: with random weights every answer is noise. What makes a network useful is training, the loop of batches, a loss and an optimizer that nudges the weights epoch after epoch until the predictions match the labels.
A pretrained model is a network whose weights have already been through that loop, run by someone else on a large collection of labelled images. The result is saved as a file of weights. You build the same arrangement of layers on your own computer, load the file into it, and the network behaves exactly as it did at the end of its training.
- Labelled images over a million photos
- Training done once, by the publisher
- Weights file downloaded and cached
- Your program same layers, same weights
- Labelled images to Training
- Training to Weights file
- Weights file to Your program
The torchvision library ships many such models. Each one comes with a builder function, which creates the layers, and an enum, a class whose members name the sets of weights available for them. MobileNetV3-Small, a network designed to run on phone processors, has one set, IMAGENET1K_V1:
from torchvision.models import mobilenet_v3_small, MobileNet_V3_Small_Weights
weights = MobileNet_V3_Small_Weights.IMAGENET1K_V1
model = mobilenet_v3_small(weights=weights)
model.eval()The first time this runs, the weights (about 10 MB for this model) are downloaded into a cache directory; later runs read them from there. Without the weights argument the builder returns the same layers with random weights.
You may also see MobileNet_V3_Small_Weights.DEFAULT. Today it means the same set. But DEFAULT always stands for the best weights available, so a later release may point it to newer ones. Naming the set yourself keeps the results fixed. Older tutorials write pretrained=True instead; it still loads weights, but it is deprecated, prints a warning and may be removed in a later release.
model.eval() switches layers that behave differently while training, such as batch normalisation and dropout, to their fixed prediction behaviour. A model used for predictions is always put in evaluation mode first.
True or false?
Calling mobilenet_v3_small() with no arguments gives a model that already recognises everyday objects.
False. By default no pretrained weights are used, so the layers start with random numbers and the answers are noise. The weights argument is what loads the trained values.
Running the same program a second time does not download the weights again.
True. The file is stored in a cache directory on the first run, and later runs load it from there.
The 1,000 classes it can answer with
The weights of most torchvision classifiers were trained on ImageNet, more exactly the collection used in the ImageNet challenge of 2012: about 1.4 million photos, each labelled with exactly one of 1,000 categories. The categories are everyday things: animals of many breeds, vehicles, tools, food, furniture, a few plants. The last layer of such a network therefore has 1,000 outputs, one score per category, in a fixed order.
The names come with the weights, in that same order, as weights.meta["categories"]. Output 0 is the score for the first name, output 999 the score for the last.
| Index | Name |
|---|---|
| 0 | tench |
| 1 | goldfish |
| 883 | vase |
| 938 | cauliflower |
| 985 | daisy |
| 987 | corn |
| 999 | toilet tissue |
This list is the whole world of the model. It has no output for "something else" and no way to say "I do not know": whatever photo goes in, the answer is one of these 1,000 names. Flowers show the limit clearly. daisy is a category, so a daisy photo can be named correctly. Tulip, rose, sunflower and dandelion are not in the list at all; the only category with "flower" in its name is cauliflower. A tulip photo still gets an answer, but it has to be some other name from the list.
True or false?
An ImageNet classifier shown a photo of a tulip can answer that it does not recognise the flower.
False. It has exactly one output per category and no output for anything outside them, so it always answers with one of its 1,000 names.
The class names in weights.meta["categories"] are in the same order as the outputs of the last layer.
True. Name number i belongs to output number i, which is how a score is turned back into a readable class.
Model size and speed
Pretrained classifiers differ enormously in size, and on a laptop processor size decides whether a model is pleasant to use. Two numbers describe it. The parameters are the weights themselves: more of them means a bigger file and more memory. The computation per image is counted in GFLOPS, billions of arithmetic operations for one forward pass; it decides how long each prediction takes. A CPU does far fewer operations per second than a graphics card, so the second number matters most there.
Both are traded against accuracy, which is published in two forms. Top-1 accuracy counts how often the first answer is right. Top-5 accuracy counts how often the right class is anywhere among the five most likely ones, which is why it is always higher. The published figures for a few torchvision weights, measured on ImageNet images, show the trade:
| Weights | Top-1 accuracy | Top-5 accuracy | Parameters | GFLOPS |
|---|---|---|---|---|
| MobileNetV3-Small V1 | 67.7 % | 87.4 % | 2.5 M | 0.06 |
| MobileNetV3-Large V1 | 74.0 % | 91.3 % | 5.5 M | 0.22 |
| MobileNetV3-Large V2 | 75.3 % | 92.6 % | 5.5 M | 0.22 |
| ResNet-18 V1 | 69.8 % | 89.1 % | 11.7 M | 1.81 |
- MobileNetV3-Small 0.06
- MobileNetV3-Large 0.22
- ResNet-18 1.81
ResNet-18 needs about 30 times the computation of MobileNetV3-Small and has more than four times its parameters, yet its top-1 accuracy is only about 2 points higher. MobileNetV3-Large gains about 7 points for under four times the work. For learning, experimenting and training on a CPU, a small model that answers in a moment is usually the better choice, and its lower accuracy is a known, measured cost.
True or false?
The model with the most parameters in this table is also the most accurate one.
False. ResNet-18 has 11.7 million parameters and reaches 69.8 %, while MobileNetV3-Large reaches 74 to 75 % with 5.5 million. Design matters as much as size.
On a CPU, the GFLOPS of a model is a good first guide to how long one prediction takes.
True. GFLOPS counts the operations of one forward pass, and a CPU has to work through them, so a model with 30 times the operations is much slower per image.
Normalisation: the value range the network expects
A photo arrives as whole numbers from 0 to 255 per colour channel, and converting it to floats from 0 to 1 keeps the picture unchanged. ImageNet networks expect one more step. During training, every image was shifted and scaled per channel so that, across the whole collection, each channel was roughly centred on zero with a spread of about one. The weights learned to work with numbers in that range, so new images must arrive in the same range.
This step is called normalisation. For each channel, subtract that channel's mean and divide by its standard deviation, both measured once over the training images:
for each channel c
ImageNet, in the order red, green, blue
Here is what that does to three pixels. The second column shows each pixel after scaling to 0 to 1, and the last three columns show the normalised value it gets in each channel:
| Pixel | Scaled (0 to 1) | Red | Green | Blue |
|---|---|---|---|---|
| black (0, 0, 0) | 0.0 | -2.12 | -2.04 | -1.80 |
| grey (200, 200, 200) | 0.784 | 1.31 | 1.47 | 1.68 |
| white (255, 255, 255) | 1.0 | 2.25 | 2.43 | 2.64 |
Two things stand out. The values are no longer between 0 and 1: dark pixels become negative and bright ones go above 2. And the same grey turns into a different number in each channel, because each channel has its own mean and standard deviation. In torchvision this step is v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]); it works on float tensors, which is why the scaling to 0 to 1 comes first.
True or false?
After ImageNet normalisation, every value of the image lies between 0 and 1.
False. Scaling to 0 to 1 is a separate step that comes first. Normalisation then subtracts a mean and divides by a standard deviation, so a black pixel becomes about -2 and a white one above 2.
The mean and standard deviation used for normalisation come from the images the network was trained on, not from the photo being classified.
True. They were measured once over the training collection. Every new photo is shifted by the same fixed numbers, so it lands in the range the weights learned.
Preprocessing that ships with the weights
Normalisation is only one part of preparing a photo. A set of weights was trained on images that were all resized, cropped, scaled and normalised in one particular way, and it expects new images prepared exactly the same way. The details are not universal: they can differ between model families, between variants of one family and even between two versions of the weights of the same network.
For MobileNetV3-Small with IMAGENET1K_V1, the preparation is four steps in a fixed order:
- Resize shorter side to 256
- Centre crop 224 x 224
- Scale 0..255 to 0.0..1.0
- Normalise ImageNet mean and std
- Resize to Centre crop
- Centre crop to Scale
- Scale to Normalise
The resize keeps the proportions of the photo: only the shorter side becomes 256 pixels, and the square of 224 by 224 is then cut from the middle. The result is a float tensor of shape (3, 224, 224).
Getting any of these steps wrong produces no error. A photo squashed to 224 by 224 instead of cropped, one left unnormalised, or one normalised with other numbers still has the right shape, so the model happily returns 1,000 scores. They are simply worse: the network sees inputs unlike anything it was trained on, and its accuracy drops without any warning. Writing the steps out by hand invites exactly this kind of quiet mistake.
torchvision avoids it by bundling the preparation into every set of weights. weights.transforms() returns the exact steps those weights were evaluated with, and it accepts a Pillow image directly:
from PIL import Image
preprocess = weights.transforms()
with Image.open("photo.jpg") as im:
img = im.convert("RGB")
batch = preprocess(img).unsqueeze(0)
print(batch.shape) # torch.Size([1, 3, 224, 224])Pillow opens and decodes the file, and convert("RGB") makes sure there are exactly three colour channels. Because the preparation comes from the weights object, switching to other weights later brings their own preparation along without changing a line. The network takes batches, so unsqueeze(0) adds a batch dimension of size 1 in front of the single image.
True or false?
If a photo is prepared with the wrong normalisation, PyTorch raises an error when it is passed to the model.
False. The tensor still has the right shape and type, so the model runs and returns scores. The only sign of the mistake is that the answers get worse.
weights.transforms() resizes every photo straight to 224 x 224, whatever its proportions.
False. It resizes the shorter side to 256 and keeps the proportions, then cuts the 224 x 224 centre, so the photo is never stretched.
Two sets of weights for the same network can expect different preprocessing.
True. The preparation depends on how each set was trained and evaluated, which is why each weights object carries its own transforms.
Reading the most likely classes
The model returns 1,000 raw scores, one per category, not probabilities. Softmax turns them into probabilities that are all positive and add up to 1, the same step a classifier uses during training before cross-entropy compares them with the label. Since only a prediction is needed here, torch.no_grad() tells PyTorch not to record anything for gradients, which saves memory and time.
import torch
with torch.no_grad():
scores = model(batch).squeeze(0) # 1,000 raw scores
probs = scores.softmax(0)
top = torch.topk(probs, k=5)
categories = weights.meta["categories"]
for p, i in zip(top.values, top.indices):
print(f"{categories[i.item()]:<20} {p.item():.3f}")torch.topk returns the k largest values and their positions, sorted from largest to smallest. The positions are category indices, and the list of names turns them into words.
Reading five answers instead of one tells far more than the first answer alone:
- A first answer at 0.9 with the rest near zero means the model is sure among its own classes. A first answer at 0.25 followed by several close ones means it is torn, and the order of those answers is close to chance.
- The runners-up show what the model confused the photo with. Two dog breeds side by side, or a pot beside a vase, are sensible mix-ups; unrelated answers suggest the photo looks like nothing it was trained on.
- The right class is often second or third even when the first answer is wrong. That is what top-5 accuracy measures, and why it is much higher than top-1 accuracy.
The probabilities always add up to 1 among the 1,000 categories, and nowhere else. Shown a tulip, a category it does not have, the model still spreads all of its probability over names it does have: perhaps a plant that looks similar, perhaps an object that often appears beside flowers, such as a pot or a vase. Its first answer can even be confident. A high probability here means only "this is the closest of my 1,000 names", never "this is what the photo shows". Reading the top predictions with the category list in mind is how you tell the two apart.
True or false?
The 1,000 numbers the model returns already add up to 1.
False. They are raw scores from the last linear layer and can be any size or sign. Softmax turns them into probabilities that add up to 1.
A probability of 0.8 for one ImageNet class on a tulip photo does not mean the model knows what a tulip is.
True. The probabilities are shared only among the 1,000 known classes. A high value says one known class fits best, even when the true answer is not among them.