Training a Network in PyTorch
Training a network in PyTorch means repeating one loop: take a batch of examples, run them forward, measure the loss, run backward() to get gradients, and let an optimizer update the weights. One pass over all the training data is an epoch, and training usually runs for many epochs.
This lesson completes the chapter's checkpoint: train a small network on handwritten digits in PyTorch and reach a stated accuracy. The target is at least 95% on test images the network has never seen.
The Training Vocabulary
| Term | Description |
|---|---|
| Batch | A small group of examples processed together, such as 32 |
| Epoch | One full pass over the training data |
| Loss function | It is used to measure how wrong the predictions are; CrossEntropyLoss for classes |
| Optimizer | It is used to update the weights from the gradients; SGD, Adam |
DataLoader | It is used to split data into shuffled batches |
model.train() and model.eval() | Switch between training and evaluation behavior |
The Data
scikit-learn includes 1,797 handwritten digits, each an 8 × 8 grayscale image stored as 64 pixel values from 0 to 16, with its true digit, 0 to 9. It needs no download, so the program runs anywhere. Larger datasets like MNIST (70,000 images of 28 × 28) work the same way.
Example: The Checkpoint
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
torch.manual_seed(0) # the same starting weights every run
# 1,797 handwritten digits, each an 8x8 image (64 pixels, 0-16), bundled with scikit-learn
digits = load_digits()
X = torch.tensor(digits.data / 16, dtype=torch.float32) # scale pixels to 0-1
y = torch.tensor(digits.target) # the digit, 0-9
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
print("Training images:", len(X_train), "| test images:", len(X_test))
train_batches = DataLoader(TensorDataset(X_train, y_train), batch_size=32, shuffle=True)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
loss_fn = nn.CrossEntropyLoss() # for choosing one of several classes
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
def accuracy(images, labels):
with torch.no_grad(): # no gradients needed to evaluate
return (model(images).argmax(dim=1) == labels).float().mean().item()
for epoch in range(1, 21): # 20 passes over the training data
model.train()
total = 0.0
for images, labels in train_batches: # 43 batches of up to 32 images
optimizer.zero_grad() # 1. clear old gradients
loss = loss_fn(model(images), labels) # 2. forward pass and loss
loss.backward() # 3. backpropagation
optimizer.step() # 4. update the weights
total += loss.item() * len(labels)
if epoch in (1, 2, 5, 10, 20):
model.eval()
print(f"epoch {epoch:2}: loss {total / len(X_train):.4f} train {accuracy(X_train, y_train):.1%}"
f" test {accuracy(X_test, y_test):.1%}")
torch.save(model.state_dict(), "digits_model.pt") # keep the learned weightsTraining images: 1347 | test images: 450
epoch 1: loss 1.3346 train 89.1% test 87.6%
epoch 2: loss 0.3555 train 93.4% test 92.9%
epoch 5: loss 0.1593 train 97.4% test 95.3%
epoch 10: loss 0.0558 train 99.2% test 96.4%
epoch 20: loss 0.0142 train 99.9% test 97.8%Explanation:
- The data: pixels are divided by 16 so they run from 0 to 1, and 450 images are kept aside as a test set. The
DataLoadershuffles the 1,347 training images into 43 batches of up to 32 each epoch. - The model is the one from "PyTorch Basics": 64 inputs, 32 hidden ReLU neurons, 10 outputs.
CrossEntropyLossapplies softmax to the 10 outputs and measures how much probability went to the correct digit. Adam is an optimizer that adapts the step size for each weight.- The four-line loop is the heart of all deep learning:
zero_grad()clears the previous batch's gradients, the forward pass computes the loss,backward()computes the gradients, andstep()updates the weights. - Results: after one epoch the network is already right 87.6% of the time on unseen digits. It passes the 95% target at epoch 5, and after 20 epochs reaches 97.8% on the test images. Training accuracy (99.9%) is a little higher, a small gap that shows mild overfitting.
torch.save()stores the learned weights for later.
With torch.manual_seed(0) and the fixed split, this program gives the same numbers every time on the same machine and PyTorch version; other setups may differ slightly.
Example: Using the Trained Model
This program loads the saved weights and looks at the mistakes. It uses digits_model.pt from the program above.
import torch
from sklearn.datasets import load_digits
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from torch import nn
digits = load_digits()
X = torch.tensor(digits.data / 16, dtype=torch.float32)
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
model.load_state_dict(torch.load("digits_model.pt")) # the weights saved by the training program
model.eval()
with torch.no_grad():
predicted = model(X_test).argmax(dim=1)
print(f"Test accuracy: {(predicted == y_test).float().mean().item():.1%}", "(target: at least 95%)")
print(confusion_matrix(y_test, predicted)) # rows: real digit, columns: predicted
with torch.no_grad():
chances = torch.softmax(model(X_test[:1]), dim=1)[0]
print("First test image is a", y_test[0].item(), "| model says", chances.argmax().item(),
f"with {chances.max().item():.1%} confidence")Test accuracy: 97.8% (target: at least 95%)
[[43 0 0 0 2 0 0 0 0 0]
[ 0 45 0 0 0 0 0 0 1 0]
[ 0 1 43 0 0 0 0 0 0 0]
[ 0 0 0 46 0 0 0 0 0 0]
[ 0 0 0 0 45 0 0 0 0 0]
[ 0 0 0 0 0 45 0 0 0 1]
[ 0 1 0 0 0 0 43 0 1 0]
[ 0 0 0 0 0 0 0 45 0 0]
[ 0 3 0 0 0 0 0 0 40 0]
[ 0 0 0 0 0 0 0 0 0 45]]
First test image is a 1 | model says 1 with 78.7% confidenceExplanation: load_state_dict() puts the saved weights into a fresh network of the same shape, and model.eval() switches it to evaluation mode. The confusion matrix from "Evaluating Models: Metrics" shows the 10 mistakes in 450 images: the most common is reading an 8 as a 1, three times, and twice a 0 was read as a 4. The first test image is a 1, which the model gets right with 78.7% confidence.
Example: Optimizers and Batch Sizes
This program trains the same network for 10 epochs with four different settings.
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
digits = load_digits()
X = torch.tensor(digits.data / 16, dtype=torch.float32)
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
def run(make_optimizer, batch_size, epochs=10):
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 32), nn.ReLU(), nn.Linear(32, 10))
optimizer = make_optimizer(model.parameters())
batches = DataLoader(TensorDataset(X_train, y_train), batch_size=batch_size, shuffle=True)
for _ in range(epochs):
for images, labels in batches:
optimizer.zero_grad()
nn.functional.cross_entropy(model(images), labels).backward()
optimizer.step()
with torch.no_grad():
return (model(X_test).argmax(dim=1) == y_test).float().mean().item(), len(batches) * epochs
setups = {
"SGD, lr 0.01, batch 32": (lambda p: torch.optim.SGD(p, lr=0.01), 32),
"SGD, lr 0.1, batch 32": (lambda p: torch.optim.SGD(p, lr=0.1), 32),
"Adam, lr 0.01, batch 32": (lambda p: torch.optim.Adam(p, lr=0.01), 32),
"Adam, lr 0.01, batch 512": (lambda p: torch.optim.Adam(p, lr=0.01), 512),
}
for name, (make_optimizer, batch_size) in setups.items():
acc, updates = run(make_optimizer, batch_size)
print(f"{name:25} 10 epochs = {updates:3} weight updates test accuracy {acc:.1%}")SGD, lr 0.01, batch 32 10 epochs = 430 weight updates test accuracy 63.6%
SGD, lr 0.1, batch 32 10 epochs = 430 weight updates test accuracy 91.8%
Adam, lr 0.01, batch 32 10 epochs = 430 weight updates test accuracy 96.4%
Adam, lr 0.01, batch 512 10 epochs = 30 weight updates test accuracy 90.2%Explanation:
| Setting | Test accuracy | What it shows |
|---|---|---|
| SGD, lr 0.01 | 63.6% | Plain gradient descent with small steps is still far from done after 10 epochs |
| SGD, lr 0.1 | 91.8% | A better learning rate helps a lot |
| Adam, lr 0.01, batch 32 | 96.4% | Adam's adaptive steps train fastest here |
| Adam, batch 512 | 90.2% | Bigger batches mean fewer updates: only 30 in 10 epochs instead of 430 |
Batch size is a trade-off: bigger batches give smoother gradients and use a GPU more efficiently, but fewer updates per epoch. Common sizes are 32 to 256.
Common Mistakes
Forgetting optimizer.zero_grad(). Gradients pile up across batches and training goes wrong.
Evaluating in training mode or with gradients on. Use model.eval() and torch.no_grad() for evaluation.
Applying softmax before CrossEntropyLoss. The loss applies it itself; pass raw scores.
Judging by training accuracy. 99.9% on training images means little; the 97.8% on unseen images is the real result.
Interview Corner
Describe a PyTorch training loop.
For each epoch, for each batch: zero the gradients, run the forward pass, compute the loss, call loss.backward(), and call optimizer.step(). Evaluate on validation data with model.eval() and torch.no_grad().
What is the difference between a batch and an epoch?
A batch is the group of examples used for one weight update; an epoch is one full pass through all the training data, made of many batches.
Practice
Exercise: a wider network. Change the hidden layer to 64 neurons, then 128. Does test accuracy improve beyond 97.8%, and does the gap between training and test accuracy grow?
Check your understanding:
- How many batches make one epoch here, and why?
- At which epoch did the network pass the 95% target?
- Why did batch size 512 score lower after 10 epochs?
Key Takeaways
Quick reference
| Need | Code |
|---|---|
| Batches | DataLoader(TensorDataset(X, y), batch_size=32, shuffle=True) |
| Loss for classes | nn.CrossEntropyLoss() |
| Optimizer | torch.optim.Adam(model.parameters(), lr=0.01) |
| One training step | optimizer.zero_grad(); loss.backward(); optimizer.step() |
| Save and load | torch.save(model.state_dict(), path), model.load_state_dict(torch.load(path)) |
Was this tutorial helpful?