Save, Load and Use Your Model
A trained model only lives in memory. When your Colab session resets, it is gone, along with every minute of training. In this last lesson you will save your model, load it back, use it to classify a new image, and pick your next step.
Keep your notebook open with the trained cnn model from lesson 5. If your session reset, run the lesson 3 data cells and the lesson 5 CNN cells again first.
What You'll Learn
- What a
state_dictis - The recommended way to save and load a model in PyTorch
- How to save to Google Drive so your file survives a Colab reset
- How to save a checkpoint so you can resume training later
- How to run your saved model on a single new image
- Where to go after this course
What Gets Saved: the state_dict
A model has two parts:
- The code: your
FashionCNNclass, which says what layers exist and how data flows. - The learned numbers: the weights and biases inside those layers.
The learned numbers live in a dictionary called the state_dict. Each key is a layer name and each value is a tensor:
for name, tensor in cnn.state_dict().items():
print(f"{name:25s} {tuple(tensor.shape)}")
You will see names like features.0.weight with shape (32, 1, 3, 3): 32 filters, 1 input channel, 3 by 3 pixels each.
Save and Load the Recommended Way
The official PyTorch tutorial recommends saving only the state_dict:
import torch
torch.save(cnn.state_dict(), "fashion_cnn.pt")
To load it, first create the model from your class, then fill in the weights:
loaded = FashionCNN()
loaded.load_state_dict(torch.load("fashion_cnn.pt", weights_only=True))
loaded = loaded.to(device)
loaded.eval()
Two details matter here:
- You need the class code to load the weights. The file holds numbers, not code. Keep your model class in your notebook or in a
.pyfile next to the weights. weights_only=Truetells PyTorch to load only tensors and plain data, not any Python code that could be hidden in the file. As of November 2026 this is already the default intorch.load, but writing it out makes your intent clear. Only load model files from people you trust.
Check that the loaded model gives the same result:
test_loss, test_acc = evaluate(loaded, test_loader, loss_fn)
print(f"Loaded model accuracy: {test_acc:.1%}")
It should match the accuracy from lesson 5 exactly.
Keep the File: Save to Google Drive
Files in Colab are deleted when the session resets. Mount your Google Drive and save there instead:
from google.colab import drive
drive.mount("/content/drive")
torch.save(cnn.state_dict(), "/content/drive/MyDrive/fashion_cnn.pt")
Colab asks you to allow access the first time. After that the file shows up in your Drive like any other file. Next time, mount Drive again and load from the same path.
You can also download the file to your computer from the Files panel on the left side of Colab. Right-click the file and choose Download.
Save a Checkpoint to Resume Training
If you want to stop training and continue later, the weights alone are not enough. The optimizer has its own state too, and you want to know which epoch you reached. Save all of it in one dictionary:
checkpoint = {
"epoch": 5,
"model_state": cnn.state_dict(),
"optimizer_state": cnn_optimizer.state_dict(),
}
torch.save(checkpoint, "checkpoint.pt")
To resume:
checkpoint = torch.load("checkpoint.pt", weights_only=True)
model = FashionCNN().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
model.load_state_dict(checkpoint["model_state"])
optimizer.load_state_dict(checkpoint["optimizer_state"])
start_epoch = checkpoint["epoch"]
model.train() # back to training mode
Saving a checkpoint every epoch is a good habit on Colab, where a session can end without warning.
Use Your Model on a New Image
Here is a small function that takes one image tensor and returns the model's top guess. It puts together what you learned in lesson 3:
def predict(model, image, classes):
model.eval()
with torch.no_grad():
logits = model(image.unsqueeze(0).to(device))
probs = logits.softmax(dim=1)[0]
top = probs.argmax().item()
return classes[top], probs[top].item()
image, label = test_data[42]
guess, confidence = predict(loaded, image, test_data.classes)
print(f"Guess: {guess} ({confidence:.0%}) Truth: {test_data.classes[label]}")
Try a few different index numbers. With about 90% accuracy, about 1 in 10 guesses will be wrong, often a shirt mixed up with a similar item.
You can also try a photo of your own. Upload a picture of a shoe or a shirt into Colab's Files panel, then turn it into the same format as the training data: grayscale, 28 by 28 pixels, light item on a dark background.
from PIL import Image, ImageOps
from torchvision.transforms import v2
img = Image.open("my_shoe.jpg").convert("L") # grayscale
img = ImageOps.invert(img) # Fashion-MNIST items are light on dark
to_input = v2.Compose([
v2.Resize((28, 28)),
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
])
guess, confidence = predict(loaded, to_input(img), test_data.classes)
print(guess, f"{confidence:.0%}")
Do not be surprised if it gets your photo wrong. Fashion-MNIST images are centered, clean and small. Real photos have backgrounds, shadows and odd angles. This gap between training data and real data is one of the most common problems in deep learning, and it is the reason transfer learning from large photo datasets is so popular.
What You Built in This Course
- Created and reshaped tensors and moved them to a GPU
- Ran gradient descent by hand, then let autograd do it
- Built a network with
nn.Moduleand trained it with a full training loop - Used a validation split to spot overfitting and fixed it with early stopping and dropout
- Built a CNN and used transfer learning with a pretrained ResNet18
- Saved, loaded and used your model
Where to Go Next
Strengthen the basics
- Machine Learning Fundamentals with Python covers classic models, metrics and feature engineering with scikit-learn. Many problems with tables of data are solved better by these models than by a neural network.
- Calculus for Machine Learning and Linear Algebra for AI explain the math behind gradients and matrix multiplication.
Go toward language models
- Transformers and Attention Explained shows the architecture behind ChatGPT and other large language models. Transformers are built from the same pieces you used here: linear layers, activations, a loss and an optimizer.
- How LLMs Actually Work explains tokens, parameters and model size.
Practice project ideas
- Train the CNN for 15 epochs with early stopping and try to beat 92% on Fashion-MNIST.
- Try transfer learning on a dataset you care about. torchvision includes others, such as Flowers102 and OxfordIIITPet.
- Swap ResNet18 for a different pretrained model from
torchvision.modelsand compare accuracy and speed.
Key Takeaways
- A model's learned numbers live in its state_dict. Save it with
torch.save(model.state_dict(), path). - To load, create the model from its class, then call
load_state_dict(torch.load(path, weights_only=True)). - Save to Google Drive on Colab, since local Colab files disappear when the session resets.
- Save a checkpoint with the model, the optimizer and the epoch so you can resume training.
- Call
model.eval()and usetorch.no_grad()before making predictions.
Quiz

Ask Byte about this lesson
A private chat about this lesson. Byte has read the whole lesson, answers in seconds, and shows the section each answer comes from. Ask follow-ups in any language.
Questions & Answers
Public questions about this lesson. The AI Tutor answers right away in your language, the FreeAcademy team checks answers, and every learner can read them.

