Save the Model and Predict a New Image

Training a network can take minutes or hours, but everything it learned lives in its weights and biases. To use it later, in another program or on another day, you keep those numbers in a file, put them back into the same network, and then ask it about inputs it has never seen. That works only when the file is loaded safely, the network is switched to prediction, and each new input is prepared exactly the way the training examples were.

What a trained network leaves behind

A trained network is two things: the code that says how the data flows through its layers, and the numbers that training adjusted. The code you already have in your script. The numbers are what is worth keeping.

PyTorch collects those numbers in a state dict: a plain Python dictionary from each parameter's name to its tensor. The names come from the attribute names you gave the layers in the constructor. Take a small digit classifier with a hidden layer:

import torch
from torch import nn

class DigitNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.hidden = nn.Linear(784, 128)
        self.output = nn.Linear(128, 10)

    def forward(self, x):
        x = torch.relu(self.hidden(x))
        return self.output(x)

model = DigitNet()
for name, tensor in model.state_dict().items():
    print(name, tuple(tensor.shape))

Each linear layer contributes one weight entry and one bias entry, named after its attribute, hidden or output. ReLU has no entry, because it has nothing to learn: it only turns negative values into zero.

The state dict of DigitNet
KeyShapeNumbers
hidden.weight(128, 784)100,352
hidden.bias(128,)128
output.weight(10, 128)1,280
output.bias(10,)10
Total101,770

Writing that dictionary to a file takes one line. The usual file extensions are .pt and .pth:

torch.save(model.state_dict(), "digits.pt")

torch.save can also save the whole model object, with torch.save(model, "digits.pt"). That looks simpler, but PyTorch recommends against it, and the reason lies in how the file is written. torch.save uses Python's pickle format, and pickle does not store the class itself. It stores only where to find the class: the name of its module and the name of the class. When the file is loaded, Python looks the class up again at that place. So if you rename the class, move it to another file, or load the model in another project, the lookup fails.

A state dict avoids this, because it holds only names and tensors. Any program that builds a network with the same layer names and shapes can use it.

True or false?

A saved state dict contains everything needed to run the network, including its forward method.

False. It holds only the named tensors. The class that says how data flows through the layers has to exist in the program that loads it.

Renaming self.hidden to self.layer1 in the class changes the keys a state dict of that network has.

True. The keys are built from the attribute names, so the key becomes layer1.weight, and a file saved with hidden.weight no longer matches.

Putting the weights back into a rebuilt network

Because the file holds only numbers, loading happens in two steps. First the program builds the network from its class, exactly as at the start of training: at that moment it has fresh random weights. Then the saved tensors are copied into it, replacing every one of those random values.

  • Build DigitNet() random weights
  • torch.load weights_only=True
  • load_state_dict keys must match
  • model.eval() trained weights
  • Build DigitNet() to torch.load
  • torch.load to load_state_dict
  • load_state_dict to model.eval()
model = DigitNet()
state = torch.load("digits.pt", weights_only=True)
model.load_state_dict(state)
model.eval()

torch.load reads the file and gives back the dictionary; load_state_dict takes that dictionary, not a file name. By default it is strict: every key in the file must match a key of the network, and every shape must fit. A renamed layer or a hidden layer of a different size stops the load with an error that names the problem, which is far better than a network that quietly runs on half-random weights. In an interactive session a successful load prints <All keys matched successfully>.

Why weights_only matters

A pickle file is more than data. While it is being read, it can tell Python to import modules and call functions, so a file someone sends you could run code on your computer the moment you load it. weights_only=True restricts the loader to tensors, plain values such as numbers and strings, and dictionaries; anything else stops the load with an UnpicklingError. A state dict is made of exactly those things, which is one more reason to save one.

Since PyTorch 2.6, weights_only=True is the default, and the official tutorials still write it out to make the intent plain. Older code and many articles pass weights_only=False, which turns the protection off; that is only for files you made yourself. Even with the restriction, PyTorch advises never loading files from a source you do not trust: it does not protect against a file built to exhaust memory, for instance.

True or false?

model.load_state_dict("digits.pt") loads the weights from the file.

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

With weights_only=True, a file that contains a pickled Python object of some other class fails to load.

True. The restricted loader builds only tensors, plain values and dictionaries, so it refuses anything else instead of running it.

Loading a state dict into a network whose hidden layer has 64 units instead of 128 gives a network that works, only a little less accurately.

False. The shapes no longer fit, so load_state_dict raises an error and nothing is loaded.

Asking the trained network for an answer

Using a trained network to predict is called inference. Three things go with it.

  • Evaluation mode. model.eval() switches layers that behave differently in training, such as dropout (a layer that switches off random values, but only while training), to their prediction behaviour. A network made of linear layers and ReLU computes the same in both modes, but calling it costs nothing and keeps the code right if such a layer is added later.
  • No gradient tracking. Predicting never calls backward(), so recording every operation would only use memory and time. with torch.no_grad(): turns the recording off. It is a separate switch from eval(): neither does the other's job, so inference uses both.
  • Softmax to read the probability. The network returns raw scores, one per class. Softmax turns them into probabilities that are positive and add up to 1.

As a reminder of what softmax does, take three classes with the scores 2.0, 1.0 and 0.1. Each score is turned into a positive number with \( e^{x} \), and each is divided by their total:

$$p_i = \frac{e^{s_i}}{e^{s_1} + e^{s_2} + \dots + e^{s_n}}$$

Softmax of the scores s

ClassScoree to the scoreProbability
A2.07.390.66
B1.02.720.24
C0.11.110.10
Total11.211.00

The highest score always gets the highest probability, so the predicted class is the same whether you take argmax of the scores or of the probabilities. Softmax adds the number behind the answer: here class A, at about 66%.

model.eval()
with torch.no_grad():
    scores = model(x)                    # shape [1, 10]
    probs = torch.softmax(scores, dim=1)
    digit = probs.argmax(dim=1).item()
    confidence = probs[0, digit].item()

print(digit, f"{confidence:.0%}")

dim=1 applies softmax across the ten scores of each example, not down the batch. .item() turns a one-element tensor into an ordinary Python number.

True or false?

Calling model.eval() also stops PyTorch from recording operations for gradients.

False. eval() only switches layer behaviour. Recording is turned off separately, with torch.no_grad().

Removing the softmax line changes which digit argmax picks.

False. Softmax keeps the order of the scores, so the largest score and the largest probability belong to the same class.

Preparing a new input the way training did

A network has only ever seen inputs in one exact form. Take a digit classifier trained on 28 by 28 greyscale images, with brightness scaled from 0.0 to 1.0 and each image laid out as one row of 784 values. Its weights were learned for exactly those 784 positions and that range of values. A photo of a digit from a phone is none of these: it may be thousands of pixels wide, in colour, with brightness stored from 0 to 255. Before the network can read it, it has to go through the same preparation as the training examples.

  • Open the file any size, colour
  • Greyscale, resize 1 channel, 28×28
  • Scale values 0.0 to 1.0
  • Add the batch [1, 784]
  • Open the file to Greyscale, resize
  • Greyscale, resize to Scale values
  • Scale values to Add the batch
import torch
from PIL import Image
from torchvision.transforms import v2

transform = v2.Compose([
    v2.ToImage(),
    v2.ToDtype(torch.float32, scale=True),
])

image = Image.open("my-digit.png").convert("L").resize((28, 28))
x = transform(image)      # shape [1, 28, 28], values 0.0 to 1.0
x = x.reshape(1, 784)     # a batch of one example

Pillow's convert("L") makes the image greyscale and resize((28, 28)) gives it the training size (width first, then height). The transform turns it into a float tensor with values from 0.0 to 1.0. The last line matters as much as the others: during training the network always received a batch, a tensor whose first dimension counts the examples, so a single image is given as a batch of one.

The safest rule is to reuse the exact transform the training data went through instead of rewriting it. Many projects add one more step after the scaling, normalisation with v2.Normalize(mean, std): it subtracts a mean, usually the average brightness of the training images, from every value and divides the result by a standard deviation, a number for how widely the values spread around that average, so that they centre on zero. This project does not use it, but if training did, the new image needs the same step with the same two numbers. Each mismatch has its own effect:

Must match trainingIf it does not
Size: 28 x 28, one channelThe shapes no longer fit the first layer, and PyTorch raises an error.
Value range: the same scaling, and any normalisation stepNo error: values from 0 to 255 are read as extremely bright pixels, and the scores mean little.
Layout: a batch of one, flattened if training wasAn error about shapes, or a tensor read along the wrong dimension.
Look: the same brightness for strokes and background, a centred digit of similar sizeNo error: the network sees a picture unlike any it learned from.

The rows without an error are the ones to watch. A wrong size stops the program; a wrong value range or an inverted image runs quietly and gives an answer that looks just as sure as a right one.

True or false?

If a new image has the right shape, the network reads it correctly even when its values run from 0 to 255 instead of 0.0 to 1.0.

False. The shape fits, so nothing fails, but every value is far larger than any the weights were trained on, and the prediction is unreliable.

A single prepared image of shape [1, 28, 28] is usually reshaped to [1, 784] before a network of linear layers can take it.

True. The first linear layer expects a batch of rows of 784 values, so the image becomes one row in a batch of one.

An answer is not proof

Softmax always shares a total of 1 among the classes the network knows. A digit classifier has ten classes and no class for "this is not a digit", so it has to choose one of the ten for every input: a blank square, a photo of a cat, or random noise. It cannot decline to answer.

Nor is the answer always hesitant. The probability depends on how the scores happen to fall for that input, and an input far from anything in training can push one score well above the rest. The chart shows the shape such an answer can take for an image of random noise; the numbers are made up for the picture, and a real network gives its own.

Probabilities for random noise (illustrative)
  • 0 0.02
  • 1 0.01
  • 2 0.06
  • 3 0.09
  • 4 0.01
  • 5 0.04
  • 6 0.02
  • 7 0.01
  • 8 0.72
  • 9 0.02

So a high probability tells you how strongly the network prefers one class over the other nine, not whether the answer is right. It is meaningful for inputs like the ones the network was measured on, and says nothing for inputs unlike them. In practice that means checking inputs before trusting answers: prepare them exactly as in training, and treat a confident answer on an unusual input as a guess.

True or false?

A digit classifier given a photo of a cat can answer 8 with a probability of over 70%.

True. Softmax must share 1 among the ten digits, and nothing stops one of them from taking most of it, even for an input unlike any digit.

If the highest probability is above 90%, the prediction can be trusted.

False. A high probability only shows a strong preference among the known classes. On inputs unlike the training data it can be high and wrong.