Sub topic 15
Saving the Model and Predicting on New Images
Assume you know Python, PyTorch modules, tensors, and the usual training steps. This chapter focuses on the boundary between training and use: saving enough information to reproduce a classifier and applying it safely to a new image.
Save the weights and class names
A trained model has learned parameter values, but those values are not enough by themselves. In a classifier, output index 0 must always refer to the same class. Save the class-name order with the weights.
A state_dict is a dictionary containing a model's learned tensors. Saving it is usually more portable than saving the entire Python model object.
import torch
checkpoint = {
"architecture": "resnet18",
"state_dict": model.state_dict(),
"classes": train_ds.classes,
}
torch.save(checkpoint, "classifier.pt")Save the preprocessing settings too when they are not fixed by your application. A model trained with ImageNet normalization expects inputs prepared in that same way during inference.
Rebuild the model for inference
To load a state_dict, create the same architecture first. Then replace its final layer with the same number of output classes. Use weights=None because the checkpoint contains your fine-tuned weights.
import torch
import torch.nn as nn
from PIL import Image
from torchvision import models, transforms
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
checkpoint = torch.load("classifier.pt", map_location=device)
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()
val_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
[0.485, 0.456, 0.406],
[0.229, 0.224, 0.225],
),
])
image = Image.open("photo.jpg").convert("RGB")
batch = val_tfms(image).unsqueeze(0).to(device)
with torch.inference_mode():
probabilities = model(batch).softmax(dim=1)[0]
top_values, top_indices = probabilities.topk(
min(3, len(classes))
)
for value, index in zip(top_values, top_indices):
print(f"{classes[index]}: {value.item():.3f}")unsqueeze(0) adds the batch dimension, changing one image from shape (channels, height, width) to (1, channels, height, width). softmax converts the model's raw logits into values that sum to one across the classes.
Interpret predictions carefully
The largest probability is the model's preferred class, not a guarantee that the prediction is correct. If the top probability is low, route the image for review or return an “uncertain” result.
Use the same color channels, crop policy, image size, and normalization during inference that you used for validation. Do not use random training augmentation for a production prediction.
Exercise
Why should inference load the saved class list instead of generating a new list from directory names?
Show answer
The model's output positions correspond to the class order used during training. A different order would attach the wrong name to a correct output index.