Lab: Your First PyTorch Training Loop
Build a complete PyTorch training and evaluation loop for a multilayer perceptron on the scikit-learn digits images: a Dataset and DataLoader, an nn.Module, cross-entropy loss and AdamW, a one-batch overfitting check, per-epoch validation with the best weights saved, and a single test evaluation.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Data, Dataset and DataLoader
- Step 2: The model as an nn.Module
- Step 3: Overfit one batch first
- Step 4: Train with validation and keep the best weights
- Step 5: Evaluate on the test set once
- Check your understanding
- Apply it
- Review prompt
Lessons of Deep Learning Fundamentals
- From Logistic Regression to a Neural Network Concept · 20 min
- Backpropagation and Autograd, Step by Step Worked example · 25 min
- Lab: Your First PyTorch Training Loop Lab · 30 min
- Optimizers, Learning Rates and Schedules Concept · 20 min
- Lab: Reading Loss Curves and Fixing a Broken Run Lab · 30 min
- Check: Why Did Training Fail? Knowledge check · 6 questions
What you will learn
- Implement a PyTorch training and evaluation loop for a multilayer perceptron with nn.Module, a DataLoader, a suitable loss and an optimizer such as SGD or AdamW.
Prerequisites: Machine Learning Fundamentals, Linear Algebra & Calculus for ML
01. Goal and setup
In the previous lessons you trained a network with a few lines in one script. Real projects split the same ideas into parts that you can test and reuse: data loading, the model, one training epoch, evaluation and checkpointing. In this lab you build each part, check it on its own, and put them together to classify handwritten digits.
The data is the digits dataset that ships with scikit-learn: 1,797 greyscale images of 8 × 8 pixels, each labelled 0 to 9. It is small enough to train in seconds on a laptop CPU, and the code is the same as for larger image sets such as Fashion-MNIST, which you would only need to download.
You need: Python 3.12, PyTorch 2 (CPU build) and scikit-learn 1.9. All randomness is seeded, so on PyTorch 2.x your numbers should match the expected outputs closely; the last digit can differ on other CPUs or library versions.
mlp-lab/
├── data.py step 1: splits, Dataset and DataLoader
├── model.py step 2: the MLP as an nn.Module
├── overfit.py step 3: can the model memorise one batch?
├── engine.py step 4: one training epoch, one evaluation pass
├── train.py step 4: the loop, with the best weights saved
└── test.py step 5: one evaluation on the test setmkdir mlp-lab && cd mlp-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "scikit-learn==1.9.*"02. Step 1: Data, Dataset and DataLoader
PyTorch separates what the data is from how it is served. A Dataset returns one example by index; TensorDataset wraps tensors that are already in memory. A DataLoader draws examples from a Dataset in mini-batches, small groups of examples that are processed together, and can shuffle them. The training loader shuffles, with its own seeded generator so that the order is repeatable, because a fresh order each epoch gives the optimizer varied batches. The validation and test loaders do not need to: the order does not change their scores.
The split is 60/20/20, stratified by digit. Pixel values run from 0 to 16, so dividing by 16 puts every input between 0 and 1, which keeps the first layer's outputs in a sensible range. Labels must be integer class indices (torch.long), the format nn.CrossEntropyLoss expects.
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch.utils.data import DataLoader, TensorDataset
def loaders(batch_size=64, seed=0):
X, y = load_digits(return_X_y=True) # 1,797 images of 8 x 8 pixels
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=seed)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=seed)
def dataset(X, y):
X = torch.tensor(X / 16.0, dtype=torch.float32) # pixels 0..16 -> 0..1
return TensorDataset(X, torch.tensor(y, dtype=torch.long))
shuffle_rng = torch.Generator().manual_seed(seed)
return (DataLoader(dataset(X_train, y_train), batch_size, shuffle=True,
generator=shuffle_rng),
DataLoader(dataset(X_val, y_val), batch_size),
DataLoader(dataset(X_test, y_test), batch_size))
if __name__ == "__main__":
train, val, test = loaders()
print("rows:", len(train.dataset), len(val.dataset), len(test.dataset))
print("batches per epoch:", len(train))
xb, yb = next(iter(train))
print("one batch:", tuple(xb.shape), xb.dtype, tuple(yb.shape), yb.dtype)
print("first labels:", yb[:10].tolist())python data.pyrows: 1077 360 360
batches per epoch: 17
one batch: (64, 64) torch.float32 (64,) torch.int64
first labels: [9, 4, 1, 4, 5, 9, 7, 0, 2, 5]Each image arrives as a flat vector of 64 floats. With 1,077 training rows and a batch size of 64 there are 17 batches per epoch: 16 full ones and a last one of 53. Keep that last batch in mind for step 4.
03. Step 2: The model as an nn.Module
An nn.Module is a class with layers created in __init__ and the computation in forward. Layers assigned as attributes are registered automatically, so model.parameters() finds their weights. This MLP has two hidden layers of 128 ReLU units with dropout after each: during training, dropout sets a random 20% of the activations to zero, which stops the network from relying on any single unit and reduces overfitting. The last layer outputs 10 logits, one raw score per digit, with no softmax: nn.CrossEntropyLoss applies log-softmax itself.
import torch
from torch import nn
class MLP(nn.Module):
def __init__(self, n_in=64, hidden=128, n_classes=10, dropout=0.2):
super().__init__()
self.net = nn.Sequential(
nn.Linear(n_in, hidden), nn.ReLU(), nn.Dropout(dropout),
nn.Linear(hidden, hidden), nn.ReLU(), nn.Dropout(dropout),
nn.Linear(hidden, n_classes), # logits: no softmax here
)
def forward(self, x):
return self.net(x)
if __name__ == "__main__":
torch.manual_seed(0)
model = MLP()
print(model)
print("trainable parameters:", sum(p.numel() for p in model.parameters()))
logits = model(torch.randn(5, 64))
print("logits shape:", tuple(logits.shape))python model.pyMLP(
(net): Sequential(
(0): Linear(in_features=64, out_features=128, bias=True)
(1): ReLU()
(2): Dropout(p=0.2, inplace=False)
(3): Linear(in_features=128, out_features=128, bias=True)
(4): ReLU()
(5): Dropout(p=0.2, inplace=False)
(6): Linear(in_features=128, out_features=10, bias=True)
)
)
trainable parameters: 26122
logits shape: (5, 10)A forward pass on a fake batch of 5 vectors returns shape (5, 10): one row of logits per example. Checking shapes like this before training catches most wiring mistakes. The 26,122 parameters are (64 × 128 + 128) + (128 × 128 + 128) + (128 × 10 + 10).
04. Step 3: Overfit one batch first
Before a full run, check that the model can memorise a single batch. A correct loop drives the loss on 64 fixed examples close to zero within a few hundred steps. If it cannot, something in the wiring is broken (labels, loss, missing step()), and no amount of data will fix it. Dropout is switched off here because the goal is to test the loop, not to generalise.
import math
import torch
from torch import nn
from data import loaders
from model import MLP
torch.manual_seed(0)
train, _, _ = loaders()
xb, yb = next(iter(train)) # one fixed batch of 64 images
model = MLP(dropout=0.0) # no dropout for this sanity check
loss_fn = nn.CrossEntropyLoss() # takes raw logits and class indices
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
print(f"loss of uniform guessing over 10 classes: ln(10) = {math.log(10):.3f}")
for step in range(201):
loss = loss_fn(model(xb), yb)
if step in (0, 25, 50, 100, 200):
acc = (model(xb).argmax(1) == yb).float().mean().item()
print(f"step {step:3d} loss {loss.item():.4f} batch accuracy {acc:.2f}")
opt.zero_grad()
loss.backward()
opt.step()python overfit.pyloss of uniform guessing over 10 classes: ln(10) = 2.303
step 0 loss 2.3196 batch accuracy 0.06
step 25 loss 1.6155 batch accuracy 0.55
step 50 loss 0.4796 batch accuracy 0.97
step 100 loss 0.0287 batch accuracy 1.00
step 200 loss 0.0051 batch accuracy 1.00The starting loss, 2.32, is close to ln(10) = 2.303, the cross-entropy of guessing uniformly over 10 classes: a freshly initialised network knows nothing, and its loss should start near that value. By step 100 every image in the batch is classified correctly. The loop works; now train for real.
05. Step 4: Train with validation and keep the best weights
engine.py holds the two functions every project needs. train_one_epoch puts the model in training mode (model.train(), dropout on), runs the four moves for each batch and returns the average loss. evaluate switches to evaluation mode (model.eval()) and runs under torch.no_grad(), so no computation graph is built. Evaluation mode turns dropout off and, in networks with batch normalisation, makes those layers use the running averages collected during training instead of the statistics of the current batch; forgetting it gives noisy, pessimistic scores. Both weight each batch loss by the batch size, so the smaller last batch counts in proportion to its 53 examples.
train.py uses AdamW, an optimizer that adapts the step size for each weight and applies weight decay; the next lesson explains it. After each epoch it measures the validation loss and, when it improves, stores a deep copy of the weights. model.state_dict() returns references to the live tensors, so without copy.deepcopy the "best" weights would keep changing as training continues.
import torch
def train_one_epoch(model, loader, loss_fn, opt):
model.train() # dropout on
total, n = 0.0, 0
for xb, yb in loader:
loss = loss_fn(model(xb), yb) # forward pass and loss
opt.zero_grad()
loss.backward() # gradients
opt.step() # update
total += loss.item() * len(xb) # weight by batch size: the last is smaller
n += len(xb)
return total / n
@torch.no_grad() # no graph needed: saves memory and time
def evaluate(model, loader, loss_fn):
model.eval() # dropout off
total, correct, n = 0.0, 0, 0
for xb, yb in loader:
logits = model(xb)
total += loss_fn(logits, yb).item() * len(xb)
correct += (logits.argmax(1) == yb).sum().item()
n += len(xb)
return total / n, correct / nimport copy
import torch
from torch import nn
from data import loaders
from engine import evaluate, train_one_epoch
from model import MLP
torch.manual_seed(0)
train, val, _ = loaders()
model = MLP()
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
best_loss, best_epoch = float("inf"), 0
print("epoch train loss val loss val acc")
for epoch in range(1, 31):
train_loss = train_one_epoch(model, train, loss_fn, opt)
val_loss, val_acc = evaluate(model, val, loss_fn)
if val_loss < best_loss: # keep a real copy of the best weights
best_loss, best_epoch = val_loss, epoch
best_state = copy.deepcopy(model.state_dict())
if epoch in (1, 2, 5, 10, 15, 20, 25, 30):
print(f"{epoch:5d} {train_loss:10.4f} {val_loss:8.4f} {val_acc:7.3f}")
torch.save(best_state, "best.pt")
print(f"best epoch {best_epoch}: val loss {best_loss:.4f}, saved to best.pt")python train.pyepoch train loss val loss val acc
1 2.2376 2.1105 0.781
2 1.9308 1.6438 0.844
5 0.5985 0.4468 0.908
10 0.2584 0.2029 0.947
15 0.1703 0.1471 0.961
20 0.1281 0.1309 0.969
25 0.1063 0.1179 0.969
30 0.0808 0.1177 0.972
best epoch 28: val loss 0.1175, saved to best.ptBoth losses fall steadily and validation accuracy climbs from 0.781 to about 0.97. In the first epochs the validation loss is below the training loss. That is normal: the training loss is averaged over an epoch during which the model was still improving, and it is measured with dropout on. Towards the end the validation loss flattens around 0.118 while the training loss keeps falling, so more epochs would buy little. The best validation loss came at epoch 28, and those weights are in best.pt.
06. Step 5: Evaluate on the test set once
Load the saved weights into a fresh model and score the test images, which played no part in training or in choosing the epoch. torch.load(..., weights_only=True) restricts loading to tensors and plain containers, which is the safe default for files you did not create yourself.
import torch
from torch import nn
from data import loaders
from engine import evaluate
from model import MLP
_, _, test = loaders()
model = MLP()
model.load_state_dict(torch.load("best.pt", weights_only=True))
test_loss, test_acc = evaluate(model, test, nn.CrossEntropyLoss())
n = len(test.dataset)
print(f"test loss {test_loss:.4f} accuracy {test_acc:.3f} on {n} images")python test.pytest loss 0.1365 accuracy 0.967 on 360 imagesTest accuracy is 0.967, in line with the validation accuracy, so the model generalises as expected. With 360 test images, one more or one fewer mistake moves accuracy by about 0.003, so treat the third decimal with care.
07. Check your understanding
08. Apply it
The practice project asks you to train an MLP in plain PyTorch and reach a target validation accuracy. Start from these files.
- Set a target (for example 0.95 validation accuracy on digits, or 0.88 on Fashion-MNIST if you download it) and record the epoch at which you reach it.
- Replace AdamW with
torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9), run again and compare the curves, still choosing on validation only. - Keep
overfit.pyin the repository as a smoke test that you run after every change to the model or the loop.
09. Review prompt
Without looking back, describe the job of a Dataset and of a DataLoader and why only the training loader shuffles; write the five lines of a training step; name the two calls that switch a model between training and evaluation behaviour and what torch.no_grad() adds; explain the purpose of the one-batch check and the loss it should start from on 10 classes; and say why the best weights are deep-copied.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.