Bitpath

Boss lesson · Unit 02

Gradient descent by hand

Fit a line with raw tensors and meet every classic loop bug

13 exercisesabout 3 min

What you practise

  • Fit y = 2x + 1 with raw tensors: forward, loss, backward, update under no_grad, zero the gradients
  • Every classic mistake in that loop

Try a question from this lesson

Pick one

Four points lie on y = 2x + 1. A model w * x + b starts with w = 0 and b = 0, so it predicts 0 everywhere. After one good gradient step, where is w?

Hint

Every prediction is too low. Which way must the slope of the line move to shrink the errors?

The idea

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Five moves on repeat

Training is the same five moves every step: predict, measure the loss, get the gradients, step each parameter against its gradient, clear the gradients.

Here x and y are the data, w and b are tensors with requires_grad=True, and lr is the learning rate.

Python
for step in range(200):
    pred = w * x + b
    loss = ((pred - y) ** 2).mean()
    loss.backward()
    with torch.no_grad():
        w -= lr * w.grad
        b -= lr * b.grad
    w.grad.zero_()
    b.grad.zero_()

11 more exercises in the app

  • 3× type the answer
  • 5× multiple choice
  • 1× fill the blanks
  • 1× order the lines
  • 1× true or false

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