Classify a New Photo with Your Model

A trained classifier is only useful once another program can load it and use it on photos it has never seen. That takes more than a file of weights: the program has to rebuild the network, load the weights without trusting the file blindly, prepare every photo exactly as during evaluation, and turn the scores into class names. And even when it all works, the probabilities the model prints mean less than they seem to, because the model can only ever choose among the classes it was trained on.

Rebuild, load, then switch to evaluation mode

The usual way to save a trained model is to save its state dict: a dictionary that maps the name of every layer's parameter (such as classifier.3.weight) to its tensor of numbers. It holds the numbers only. It does not describe the network those numbers belong to, so a program that wants to use them has to build that network again in code first.

Using a model to make predictions, rather than to train it, is called inference. Getting a model ready for inference takes four steps, always in this order.

  • Build the network same layers, same sizes
  • Read the file torch.load
  • Load the weights load_state_dict
  • Evaluation mode model.eval()
  • Build the network to Read the file
  • Read the file to Load the weights
  • Load the weights to Evaluation mode

Build the same network. The new network must have exactly the layers the trained one had, down to the size of each. If training replaced a pretrained model's last layer with one that has five outputs, the inference program builds the same model and replaces the same layer with a five-output layer too. It does not need the pretrained weights for this, because every number will be overwritten in the next step, so it builds the network with weights=None and downloads nothing.

Read the file, then load it. These are two separate calls. First torch.load turns the file back into Python objects, among them the dictionary of tensors. Then load_state_dict copies the tensors of that dictionary into the matching parameters of the network; it takes the dictionary, not a file path.

By default load_state_dict is strict: every name in the dictionary must match a parameter of the network, and every parameter must get a value. If not, it stops with an error that lists the missing and unexpected keys. That error is helpful, since it is how a mismatch between the rebuilt and the trained network shows up. A clean load reports <All keys matched successfully>.

Rebuilding a fine-tuned MobileNetV3-Small for inference
import torch
from torch import nn
from torchvision.models import mobilenet_v3_small

checkpoint = torch.load("model.pt", map_location="cpu", weights_only=True)
classes = checkpoint["classes"]

model = mobilenet_v3_small(weights=None)
model.classifier[3] = nn.Linear(1024, len(classes))
model.load_state_dict(checkpoint["state_dict"])
model.eval()

map_location="cpu" places every tensor on the CPU. A file saved on a CPU does not need it. A file saved on a GPU does: without it, its tensors would try to go back to the GPU and fail on a machine without one.

Switch to evaluation mode. Some layers behave differently while training. Dropout switches off a random share of values on every call. Batch normalisation normalises with the statistics of the current batch, and keeps updating its running averages. model.eval() changes both: dropout does nothing, and batch normalisation uses the averages it stored during training. Without it, the same photo can get different answers on different calls, and a single photo in a batch of one is normalised against itself. PyTorch's own tutorial states that skipping this step gives inconsistent inference results.

Evaluation mode is separate from gradients. During training, PyTorch records every computation so that a backward pass can follow. torch.no_grad() (or the stricter torch.inference_mode()) stops that recording, which saves memory and time when no training follows. Neither of them changes how dropout or batch normalisation behave, and model.eval() does not switch off gradients. An inference program uses both.

True or false?

Wrapping the prediction in torch.no_grad() also puts dropout and batch normalisation into evaluation mode.

False. The two are independent. no_grad only stops gradient recording; the layers change their behaviour only through model.eval().

If the rebuilt network has a final layer with a different number of outputs than the trained one, load_state_dict stops with an error.

True. The shapes of the saved and the new tensors differ, and a strict load refuses them instead of loading part of the model.

model.load_state_dict("model.pt") reads the weights straight from the file.

False. It takes a dictionary. The file is read first with torch.load, and its result is passed in.

Loading weights safely

A .pt file looks like a file of numbers, but torch.load reads it with Python's pickle format, which can store not only data but instructions to call functions while the file is read. A file built for that purpose can run any code on the computer that opens it: delete files, install a program, send data away. The documentation of torch.load carries the warning plainly: never load data from an untrusted source.

The defence is a restricted loader. With weights_only=True, torch.load rebuilds only what a state dict needs: tensors, dictionaries, lists, tuples, strings, whole numbers, floats, booleans and None, plus a short list of PyTorch's own types. It imports nothing while reading, and anything else in the file makes the load fail instead of running. Since PyTorch 2.6 this is the default (unless the call passes a pickle module of its own), and writing it out keeps the intent visible to anyone reading the code.

Value in the saved dictionaryweights_only=True
a state dict of tensorsloads
a list of class names as stringsloads
an epoch as int, an accuracy as floatloads
an accuracy as a NumPy float64fails: not an allowed global
an object of your own class, or a whole model saved with torch.save(model)fails: not an allowed global

When the safe load fails, the error message offers two ways out: load with weights_only=False, or allow the extra type with torch.serialization.add_safe_globals. It adds that both are only for a file from a source you trust. For a file you saved yourself, the better fix is at the saving end: store only plain values, for instance with float(accuracy) or tensor.item(), and save the state dict rather than the whole model. A whole model saved with torch.save(model, path) needs the unsafe loader and also depends on the exact classes and folder layout of the code that saved it.

For a file from an unknown source (a download, an attachment, a model someone shared) there is no safe way to load it with weights_only=False, because whether code runs is decided by the file, not by the program. The restricted loader is the only acceptable choice, and it has limits of its own. Its documentation says it narrows the surface for such attacks but does not guard against a file built to exhaust memory or time. It is also only as good as the installed version: PyTorch versions before 2.6.0 had a critical flaw (CVE-2025-32434) that let a file run code even through weights_only=True. Keeping PyTorch current is part of loading safely.

True or false?

A checkpoint that holds a state dict, a list of strings and an int loads with weights_only=True.

True. Tensors, dictionaries, lists, strings and plain numbers are exactly what the restricted loader accepts.

With weights_only=True, any file is safe to open, whatever its source.

False. It blocks code execution through pickle in current versions, but not files built to exhaust memory, and older versions had a flaw that let code run anyway.

What has to ship with the weights

Suppose the weights load cleanly and the network prints its output for a photo. That output is a row of scores, one per class, and nothing more: the network knows positions, not names. Position 0 is whichever class was numbered 0 when the training data was labelled. To print an answer, the program needs the list of class names in that same order.

The same scores read with two orders of names
OutputProbabilityOrder used in trainingOrder guessed later
00.05catdog
10.88dograbbit
20.07rabbitcat

With the order used in training, the answer is "dog". With an order rebuilt later, perhaps by listing a folder whose contents changed or were sorted differently, the same numbers say "rabbit", and nothing in the output warns that anything is wrong. The safe place for the names is the saved file itself, next to the weights. torchvision does the same with its own pretrained weights: the names of the outputs are stored with each set of weights in weights.meta["categories"].

The second thing that belongs to the model is the evaluation preprocessing: the exact steps that turned a photo into the input tensor while the model was measured. The weights only give good answers for inputs prepared that way. A photo resized to a different size, cropped differently or normalised with a different mean and standard deviation still produces scores, just worse ones, again without any error.

When the model was fine-tuned from torchvision weights and evaluated with their bundled preprocessing, the inference program does not have to write those steps by hand. It builds exactly the same steps again from the weights enum, and this downloads nothing:

from torchvision.models import MobileNet_V3_Small_Weights

preprocess = MobileNet_V3_Small_Weights.IMAGENET1K_V1.transforms()

For these weights, that resizes the shorter side to 256 pixels, crops the 224 by 224 centre, converts the pixel values to floats from 0 to 1 and normalises each channel with the mean and standard deviation of the training images. So a classifier really ships as three things together: the weights, the class names in their order and the preprocessing. The first is useless without the other two.

True or false?

If the class names are listed in the wrong order, the program raises an error when it prints a prediction.

False. Any list of the right length can be indexed, so it prints a confident wrong name without complaint.

A photo prepared with a different normalisation than in evaluation still gets a prediction, usually a less accurate one.

True. The network accepts any tensor of the right shape. Only the accuracy shows that the input is not what it was trained on.

Bringing any photo to the shape the model expects

The photos used in training were usually similar: colour JPEGs of a few common sizes. A photo from anywhere else can differ in more ways. Size is the easy part, since the preprocessing resizes and crops every image to 224 by 224 whatever its size and shape. The number of colour channels is the hard part, because the preprocessing does not change it. Pillow, the library that opens the file, describes each image by its mode, and the mode decides how many channels the tensor gets.

Pillow modeWhat it isChannels as a tensor
RGBcolour photo3
Lgreyscale1
RGBAcolour with a transparency channel (alpha)4
Pcolours from a palette, sometimes with transparency1

The network's first layer expects exactly three channels, and the normalisation has three means and three standard deviations, one per colour. A greyscale image with one channel or a transparent PNG with four never fits, and the bundled preprocessing does not fix that for you: the normalisation stops with an error about mismatched tensor sizes. The cure is one call before the preprocessing: image.convert("RGB"). For a greyscale image it copies the grey value into red, green and blue, which is exactly what a grey picture looks like in colour.

Transparency needs one more thought. Converting an RGBA image to RGB simply drops the alpha channel and keeps whatever colour the file stores under the transparent pixels, which may be black, white or leftovers of an old edit. To get the picture a person sees, place the image on a solid background first, for example white with Image.alpha_composite, and convert after that.

Phone photos add a last surprise. The camera often stores the pixels sideways and writes a small instruction, the EXIF orientation tag, telling viewers to rotate the picture. Pillow does not apply it when opening the file; ImageOps.exif_transpose does. A model trained on upright photos may do worse on a sideways one.

  • Open Image.open
  • Turn upright exif_transpose
  • Flatten alpha onto a background
  • Three channels convert("RGB")
  • Preprocess 3 x 224 x 224
  • Batch of one unsqueeze(0)
  • Open to Turn upright
  • Turn upright to Flatten alpha
  • Flatten alpha to Three channels
  • Three channels to Preprocess
  • Preprocess to Batch of one
Opening any photo as a three-channel image
from PIL import Image, ImageOps

def open_photo(path):
    image = Image.open(path)
    image = ImageOps.exif_transpose(image)
    if image.mode in ("RGBA", "LA") or "transparency" in image.info:
        image = image.convert("RGBA")
        background = Image.new("RGBA", image.size, (255, 255, 255, 255))
        image = Image.alpha_composite(background, image)
    return image.convert("RGB")

After open_photo, every file that Pillow can open becomes a three-channel image, and the preprocessing turns it into a tensor of shape (3, 224, 224). The network expects a batch, so unsqueeze(0) adds a batch dimension of size one in front: (1, 3, 224, 224). A file that is not an image at all makes Image.open raise UnidentifiedImageError, which a program can catch and report instead of crashing.

True or false?

The bundled preprocessing of torchvision weights converts a greyscale photo to three channels on its own.

False. It resizes, crops, converts to floats and normalises, but keeps the channel count. The conversion to RGB has to come first.

A photo of 4000 by 3000 pixels and one of 640 by 480 both reach the network as 224 by 224.

True. The preprocessing resizes the shorter side and crops the centre, so every input ends at the same size.

convert("RGB") on a transparent PNG places it on a white background.

False. It drops the alpha channel and keeps the colours stored under the transparent pixels. A background has to be composited first.

A closed set of classes

With the model loaded and the photo prepared, the prediction is a forward pass and a softmax, which turns the scores into probabilities between 0 and 1 that add up to 1. The most likely classes are read with torch.topk, largest first.

with torch.no_grad():
    batch = preprocess(open_photo("photo.jpg")).unsqueeze(0)
    probs = model(batch).squeeze(0).softmax(0)

top = torch.topk(probs, k=3)
for p, i in zip(top.values, top.indices):
    print(f"{classes[i.item()]}: {100 * p.item():.1f}%")

That "add up to 1" is the key to what the numbers mean. The softmax shares out a total of 1 among the classes the model was trained on, and only among them. There is no output for "none of these". So a model trained on cats, dogs and rabbits, shown a photo of a toaster, still divides its whole confidence between cat, dog and rabbit. With three classes, at least one of them must get a third or more, and one is always first.

A photo of a dog (illustration)
  • cat 0.04
  • dog 0.93
  • rabbit 0.03
A photo of a toaster (illustration)
  • cat 0.08
  • dog 0.11
  • rabbit 0.81

Nothing forces the toaster's probabilities to be spread out evenly either. The model has never been taught what a toaster looks like, so its features may happen to resemble one class far more than the others, and the answer can be just as confident as for a real dog. Research has shown how far this goes: Nguyen, Yosinski and Clune produced images that look like noise to people and that trained networks labelled as objects with 99.99 % confidence.

So a probability tells how the model ranks its own classes for this input. It says nothing about whether the input belongs to any of them.

Even for photos of the trained classes, a probability is not a measured chance of being right. Guo and colleagues found that modern deep networks are poorly calibrated: collect many answers the model gave with 90 %, and clearly fewer than 90 % of them can be correct. What does hold is a tendency: Hendrycks and Gimpel found that correct answers tend to have a higher top probability than mistakes and unfamiliar images. A low top probability is therefore a useful hint to look closer, and a high one is no proof.

In practice this means saying clearly what the classifier is for. It answers the question "which of these classes is this photo?", and it should only be asked about photos that show one of them. Showing the top few classes with their probabilities, instead of a single name, makes a near tie between two classes visible to whoever reads the answer.

True or false?

Shown a photo of none of its five classes, a classifier still gives at least one of them a probability of 0.2 or more.

True. The five probabilities always add up to 1, so they cannot all be below one fifth.

A top probability of 0.97 shows that the photo really contains that class.

False. The probability is shared only among the trained classes. A photo of something else can get just as high a value.

Correct predictions tend to have a higher top probability than wrong ones, so a low value is a useful warning sign.

True. This is a tendency found across many images, a hint to look closer, not a guarantee for one photo.