Sub topic 15
Saving the model and predicting on new images
This chapter covers the last step of the workflow: saving the trained classifier, reloading it in a fresh process, and predicting on new images. It assumes you can read PyTorch code and have trained a classifier as in the earlier chapters. You should also know why validation images use a fixed resize and crop instead of random augmentation.
What you need to save
A trained model is more than its weights. To get the same predictions later, you must reproduce three things:
- The architecture. The code that builds the model, here a ResNet-18 with a new final layer.
- The weights. The values in
model.state_dict(). - The conventions around the model. These are the class names in index order and the preprocessing used at evaluation time.
The third item is the one people forget. The model outputs a number between 0 and num_classes - 1. Only ImageFolder knows that index 2 means "daisy". If you lose that list, or rebuild it from a folder that has since gained a class, your predictions will be mislabeled with no error.
ImageFolder sorts class folder names alphabetically, so the order is stable as long as the folders do not change. Saving the list alongside the weights removes the dependency.
Saving a checkpoint
Save the state_dict, not the whole model object. torch.save(model, path) pickles the class by reference to its module path, so it breaks when you rename or move code. A state_dict is a plain dictionary of tensors and loads into any compatible model.
import torch
torch.save(
{"state_dict": model.state_dict(), "classes": train_ds.classes},
"classifier.pt",
)Consider also storing the architecture name and image size, so the loading code does not have to guess:
checkpoint = {
"state_dict": model.state_dict(),
"classes": train_ds.classes,
"arch": "resnet18",
"image_size": 224,
}
torch.save(checkpoint, "classifier.pt")If you plan to resume training later, also save optimizer.state_dict() and the epoch number. For inference alone, they are not needed.
Loading in a fresh process
Loading reverses the steps. Build the same architecture, replace the head with the right number of outputs, then load the weights. You do not need to download the ImageNet weights again, because the saved weights overwrite them.
import torch
import torch.nn as nn
from torchvision import models
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
checkpoint = torch.load("classifier.pt", map_location=device, weights_only=True)
classes = checkpoint["classes"]
model = models.resnet18(weights=None)
model.fc = nn.Linear(model.fc.in_features, len(classes))
model.load_state_dict(checkpoint["state_dict"])
model = model.to(device)
model.eval()Three details matter here.
map_location=devicelets you load a checkpoint saved on a GPU machine onto a CPU-only machine. Without it, loading fails when CUDA is not available.weights_only=Truerestricts unpickling to tensors and plain containers. Loading a checkpoint runs pickle, and a malicious file can execute code. Use this flag for any file you did not create yourself. The checkpoint above contains only tensors, a list of strings, and simple values, so it loads under this restriction.model.eval()is required. It switches batch normalization to its stored running statistics and turns off dropout. A model left in train mode gives different, batch-dependent outputs.
The inference pipeline
The diagram shows what happens to a single image, from file to label.
Every step before the model must match what the model saw during validation. The model was trained on inputs that were resized, cropped, scaled to the range 0 to 1, and normalized with the ImageNet mean and standard deviation. If you skip normalization or use a different resize, accuracy drops, and nothing raises an error. Do not use the random training transforms at inference. They would make the same photo produce different predictions on each call.
Predicting one image
from PIL import Image
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
val_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
image = Image.open("photo.jpg").convert("RGB")
batch = val_tfms(image).unsqueeze(0).to(device)
with torch.inference_mode():
probs = model(batch).softmax(dim=1)[0]
top = probs.argmax().item()
print(classes[top], f"{probs[top].item():.3f}")Line by line:
.convert("RGB")handles grayscale images and PNGs with an alpha channel, which would otherwise produce a tensor with 1 or 4 channels and fail inside the first convolution..unsqueeze(0)adds a batch dimension. The model expects shape(N, 3, 224, 224), and one image has shape(3, 224, 224).torch.inference_mode()disables gradient tracking and some autograd bookkeeping, which reduces memory use and time. It is slightly stricter thantorch.no_grad(): tensors created inside it cannot later be used in autograd.softmax(dim=1)turns the raw outputs (logits) into values that sum to 1 across classes. The training loss,CrossEntropyLoss, applies softmax internally, so the model itself outputs logits and you apply softmax only when you want probabilities.
Showing the top few predictions
Often the second and third guesses are useful, especially when classes look alike. topk gives them directly.
def predict(path, k=3):
image = Image.open(path).convert("RGB")
batch = val_tfms(image).unsqueeze(0).to(device)
with torch.inference_mode():
probs = model(batch).softmax(dim=1)[0]
values, indices = probs.topk(min(k, len(classes)))
return [(classes[i], v.item()) for v, i in zip(values, indices)]
for label, p in predict("photo.jpg"):
print(f"{label:>15s} {p:.3f}")The min(k, len(classes)) guard avoids an error when you have fewer classes than k.
Predicting many images
Calling the model once per image wastes the hardware. For a folder of images, group them into batches. A small Dataset and a DataLoader do this with parallel loading.
from pathlib import Path
from torch.utils.data import Dataset, DataLoader
class FolderOfImages(Dataset):
def __init__(self, folder, transform):
exts = {".jpg", ".jpeg", ".png"}
self.paths = sorted(p for p in Path(folder).iterdir() if p.suffix.lower() in exts)
self.transform = transform
def __len__(self):
return len(self.paths)
def __getitem__(self, i):
image = Image.open(self.paths[i]).convert("RGB")
return self.transform(image), str(self.paths[i])
ds = FolderOfImages("new_photos", val_tfms)
loader = DataLoader(ds, batch_size=32, shuffle=False, num_workers=2)
with torch.inference_mode():
for images, paths in loader:
probs = model(images.to(device)).softmax(dim=1)
confidences, indices = probs.max(dim=1)
for path, conf, idx in zip(paths, confidences, indices):
print(f"{path}: {classes[idx.item()]} ({conf.item():.3f})")Keep shuffle=False so output order is predictable. Returning the path with each image lets you tie every prediction back to its file.
Interpreting the probabilities
A softmax probability is not a calibrated statement of confidence. A fine-tuned network often reports 0.99 for a wrong answer. Two consequences follow.
- The model must choose a class. It has no "none of the above" output. A photo of a car passed to a flower classifier still gets a flower label, often with high probability.
- A threshold is a rough filter. You can reject predictions below, say, 0.7 and send them for human review. Choose the threshold from validation data by checking how accuracy changes as you raise it. Do not guess it.
If out-of-category inputs are likely in your application, the cleaner remedy is to add an explicit "other" class with representative examples during training.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Predictions are the right classes shifted or scrambled | Class list rebuilt from a different folder, or not saved | Load `classes` from the checkpoint |
| Accuracy at inference is far below validation accuracy | Missing normalization, or a different resize or crop | Reuse the validation transform exactly |
| Same image gives different results on each run | Model left in train mode, or random transforms used | Call `model.eval()` and use the deterministic transform |
| `size mismatch for fc.weight` | Head not replaced before loading | Rebuild `model.fc` with `len(classes)` outputs |
| CUDA error when loading on a laptop | Checkpoint saved from GPU, loaded without `map_location` | Pass `map_location` |
| Shape error in the first convolution | Image is grayscale or has an alpha channel | Call `.convert("RGB")` |
| Memory grows during prediction | Gradients tracked | Wrap prediction in `torch.inference_mode()` |
Beyond this chapter
For serving at scale, two options are common. Exporting to ONNX or TorchScript lets you run the model without the Python training code. Wrapping the predict function in a small web service lets other programs call it. Both reuse the same rule: the preprocessing travels with the model. Whatever runtime you pick, test it by comparing its output on a few validation images against the PyTorch output from this chapter.
Exercise
You load a saved checkpoint in a new script and run predictions on your validation images. Accuracy is 12% on a 10-class problem, close to chance, although training reported 94%. The weights load without errors and model.eval() is called. Name two likely causes and how you would check each.
Show answer
First, the preprocessing may differ from validation, for example Normalize is missing or the images are resized to a different size. Check by printing the tensor mean and standard deviation of a batch, which should be near 0 and 1 for ImageNet-style normalization, and by comparing against the batches produced by the validation DataLoader. Second, the class names may be in a different order than the model's output indices, for example because the list was rebuilt from a changed folder. Check by comparing checkpoint["classes"] with train_ds.classes from the original run, and by confirming that the labels you compare against use the same index order. A third possibility is that the head was built with the right size but the loaded fc weights were not applied because of a wrong key, though load_state_dict would normally raise an error in that case.
Exercise
Why does the chapter save model.state_dict() instead of the whole model with torch.save(model, path), and why use weights_only=True when loading?
Show answer
Saving the whole model pickles a reference to the class definition, so loading fails if the code is renamed or moved. A state_dict is a plain dictionary of tensors that loads into any model with matching layer names and shapes. Loading uses pickle, which can run arbitrary code from an untrusted file. weights_only=True limits unpickling to tensors and simple containers, which makes loading a file from an unknown source much safer.