Bitpath

Lesson 2 · Unit 03

The training loop

Losses, optimizers and the five lines in the right order

13 exercisesabout 3 min

What you practise

  • Loss functions (MSE, cross-entropy and what shapes it wants), optimizers, zero_grad / backward / step in order, epochs, train() vs eval()

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?

Python
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.

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.

Python
for x, y in batches:
    opt.zero_grad()          # clear
    pred = model(x)          # predict
    loss = loss_fn(pred, y)  # measure
    loss.backward()          # gradients
    opt.step()               # update

Concept

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 number

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy