Lesson 2 · Unit 03
The training loop
Losses, optimizers and the five lines in the right order
What you practise
- Loss functions (MSE, cross-entropy and what shapes it wants), optimizers,
zero_grad/backward/stepin order, epochs,train()vseval()
Try a question from this lesson
Pick one
opt.step() does w -= lr * w.grad for every tensor the optimizer was given. What does this print?
w = torch.tensor(1.0, requires_grad=True)
opt = torch.optim.SGD([w], lr=0.5)
loss = (w - 3) ** 2
loss.backward()
opt.step()
print(w.item())Hint
Find the slope of the loss where the parameter starts, then move against it by the learning rate times that slope.
Correct answer
3.0
Why
The slope at w = 1 is 2(1 - 3) = -4, and 1 - 0.5 × (-4) = 3.0. The optimizer holds the parameters and the learning rate, and does the no_grad() update for you. SGD is plain gradient descent.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The five lines
Every PyTorch training loop is built from these five lines. The optimizer replaces your hand-written update and zeroing, for every parameter of the model at once.
One trip through all the batches is called an epoch.
for x, y in batches:
opt.zero_grad() # clear
pred = model(x) # predict
loss = loss_fn(pred, y) # measure
loss.backward() # gradients
opt.step() # updateConcept
Cross-entropy takes raw scores
nn.CrossEntropyLoss is the loss for picking one class out of C.
It wants the model's raw scores (logits), one row per sample, and the correct class of each sample as an integer index. It applies softmax itself, so the model's last layer outputs plain scores, not probabilities.
logits (N, C) float raw scores
target (N,) int64 class index
loss () one number10 more exercises in the app
- 1× fill the blanks
- 3× type the answer
- 4× multiple choice
- 1× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.