Learning path: Neural Networks from Scratch to Embeddings · Step 4 of 9
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.
What you will learn
- Explain a mini-batch, a step and an epoch, and count the steps per epoch
- Write the four moves of every training step: forward, loss, backward, step
- Pick a learning rate by comparing too small, about right and too big
- Compare SGD with Adam and read training vs validation loss to spot overfitting
Before you start
- Loss and Backpropagation
- Gradient Descent Explained
Imagine you're revising for an exam from a big textbook. You don't read the whole book and only then test yourself. After each chapter you do a quick self-check and fix what you got wrong, right away. When you reach the end, you start again and read the whole book a few more times.
That's the training loop. A chapter is one mini-batch. A self-check and fix is one step (one nudge of the weights). One full read of the book is one epoch.
One epoch, step by step
We train the digit network (784 inputs, 128 hidden, 10 outputs) on MNIST. The first 48,000 training images train, the last 12,000 validate. Pixels are divided by 255 and each picture is flattened to 784 numbers.
import numpy as np
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
torch.manual_seed(42)
d = np.load("mnist.npz")
X = torch.tensor(d["x_train"].reshape(-1, 784) / 255.0, dtype=torch.float32)
y = torch.tensor(d["y_train"], dtype=torch.long)
X_tr, y_tr = X[:48000], y[:48000]
X_va, y_va = X[48000:], y[48000:]
print(X_tr.shape, X_va.shape)
torch.Size([48000, 784]) torch.Size([12000, 784])
Inside one epoch: shuffle the 48,000 images, cut them into mini-batches of 32, and for each batch do four moves.
How many nudges per epoch?
n_train, batch_size = 48_000, 32
steps = n_train // batch_size
print("steps per epoch:", steps)
for epoch in range(1, 4):
print("epoch", epoch, "->", steps, "weight updates")
steps per epoch: 1500
epoch 1 -> 1500 weight updates
epoch 2 -> 1500 weight updates
epoch 3 -> 1500 weight updates
// is whole-number division: 48,000 / 32 = 1,500. One weight update per mini-batch, so ten epochs would be 15,000 small nudges.
The four moves in code
def make_model():
torch.manual_seed(42)
return nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
def fmt(values):
return " ".join(f"{v:.2f}" for v in values)
model = make_model()
opt = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.CrossEntropyLoss()
batches = torch.randperm(6000).split(32)
for step, idx in enumerate(batches[:4], 1):
loss = loss_fn(model(X_tr[idx]), y_tr[idx])
opt.zero_grad()
loss.backward()
opt.step()
print(step, round(loss.item(), 3))
1 2.298
2 2.314
3 2.273
4 2.27
The loss line runs the forward pass and measures the loss. opt.zero_grad() clears the old gradients, loss.backward() finds the new ones (see Loss and Backpropagation), and opt.step() nudges the weights. The loss moves a little with each batch.
The same loop as a function
To run experiments, the notebook wraps that loop in train(). It trains on the first n images and records the average training loss and the validation loss (on 2,000 validation images) after each epoch. Small subsets keep every run to seconds on a CPU.
def train(opt_name, lr, n=6000, epochs=5, batch_size=32):
model = make_model()
opt = getattr(torch.optim, opt_name)(model.parameters(), lr=lr)
loss_fn = nn.CrossEntropyLoss()
g = torch.Generator().manual_seed(42)
tr_hist, va_hist = [], []
for epoch in range(epochs):
total = 0.0
for idx in torch.randperm(n, generator=g).split(batch_size):
loss = loss_fn(model(X_tr[idx]), y_tr[idx])
opt.zero_grad()
loss.backward()
opt.step()
total += loss.item() * len(idx)
with torch.no_grad():
va = loss_fn(model(X_va[:2000]), y_va[:2000]).item()
tr_hist.append(round(total / n, 3))
va_hist.append(round(va, 3))
return tr_hist, va_hist
Learning rate: how big a step
The learning rate is the most important knob. Same network, SGD, 6,000 images, five epochs, three rates. The printed numbers are the validation loss after each epoch:
for lr in [0.001, 0.1, 5.0]:
tr, va = train("SGD", lr)
print(f"lr = {lr:<5}", fmt(va))
lr = 0.001 2.26 2.23 2.19 2.14 2.10
lr = 0.1 0.54 0.42 0.39 0.33 0.32
lr = 5.0 2.46 2.37 2.35 2.44 2.50
- 0.001, too small: 2.26 to 2.10. It's crawling.
- 0.1, about right: 0.54 down to 0.32. It falls quickly, then settles.
- 5.0, too big: 2.46 to 2.50. It keeps overshooting and ends higher than it started.
It's the same story as in Gradient Descent Explained, now on a network with 101,770 knobs.
Who picks the step: SGD or Adam
The optimiser decides how big each step is. Same network, same data, eight epochs; only the optimiser changes:
_, sgd = train("SGD", 0.01, epochs=8)
_, adam = train("Adam", 0.001, epochs=8)
print("SGD ", fmt(sgd))
print("Adam", fmt(adam))
SGD 1.82 1.23 0.89 0.72 0.63 0.57 0.53 0.50
Adam 0.42 0.34 0.35 0.28 0.27 0.27 0.26 0.25
SGD uses one step size for every weight and ends at 0.50. Adam keeps its own step size for every weight and adds momentum, like a ball rolling downhill. It goes from 0.42 to 0.25. Adam with a learning rate of 0.001 is the usual default.
Training loss vs validation loss: when to stop
Now a run that's built to overfit: only 1,000 training images for 30 epochs, so the network can memorise them.
tr, va = train("Adam", 0.001, n=1000, epochs=30)
best = int(np.argmin(va)) + 1
print("epoch train validation")
for ep in (1, 10, 30):
print(f"{ep:>5} {tr[ep-1]:.3f} {va[ep-1]:>10.3f}")
print("best epoch:", best, "validation loss", min(va))
epoch train validation
1 1.708 1.150
10 0.137 0.452
30 0.012 0.532
best epoch: 10 validation loss 0.452
plt.plot(range(1, 31), tr, label="training loss")
plt.plot(range(1, 31), va, label="validation loss")
plt.axvline(best, ls="--", color="gray")
plt.xlabel("epoch")
plt.legend()
plt.show()

The training loss falls all the way, from 1.708 to 0.012. The validation loss is best at epoch 10 (0.452) and then climbs to 0.532. After epoch 10 the gap keeps opening: that's overfitting (the same idea as in Polynomial Regression, Overfitting and Underfitting), and it's your signal to stop.
Common mistakes
- Forgetting
opt.zero_grad(). PyTorch adds new gradients to the old ones, so every step would use a pile of stale blame. - Judging training by the training loss alone. It always goes down; watch the validation loss.
- Copying a learning rate between optimisers. 0.1 worked for SGD here; Adam's usual default is 0.001.
- Training far past the best validation epoch. More epochs is not always better.
Quick recap
| Term | Meaning | Here |
|---|---|---|
| Mini-batch | A few examples, one nudge | 32 images |
| Epoch | One full pass over the training data | 1,500 steps |
| Learning rate | How big each step is | 0.1 good for SGD; 5.0 overshoots |
| Optimiser | Who picks the step | Adam 0.25 vs SGD 0.50 after 8 epochs |
| Validation loss | When to stop | Best at epoch 10, then climbs |
Try it yourself
Run the learning-rate cell with 0.5 and with 0.01. Where do they land between our three curves?
The notebook and mnist.npz are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Loss and Backpropagation: How Wrong, and Who Is to Blame
Next →Your First Neural Network with Keras: MNIST Digits at 97.7%
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
Your First Neural Network with Keras: MNIST Digits at 97.7%
Build the 784-128-10 digit network in Keras in five steps: load and scale, Sequential with Flatten and Dense, compile, fit for ten epochs, and test once. It reads handwritten digits with 97.72% test accuracy.