Part 10 / Topic 4 of 7
The training loop
Five lines, always the same, worth memorising:
# examples/02_a_complete_pytorch_training_loop_on.py (core)
for epoch in range(1, 21):
model.train()
for xb, yb in loader:
opt.zero_grad() # 1. clear old gradients
loss = loss_fn(model(xb), yb) # 2. forward 3. loss
loss.backward() # 4. gradients
opt.step() # 5. update
# epoch 5 last batch loss 1.145 test accuracy 0.894
# epoch 10 last batch loss 0.550 test accuracy 0.928
# epoch 15 last batch loss 0.271 test accuracy 0.933
# epoch 20 last batch loss 0.206 test accuracy 0.950
A two-layer MLP reaches 0.950 on the digits test set in 20 epochs. Compare Part 9: same mechanics, but autograd wrote the backward pass and Adam chose the step sizes.
Done here? The practice set for Part 10 — 4 exercises with solutions — is on the part page.