Boss lesson · Unit 02
Gradient descent by hand
Fit a line with raw tensors and meet every classic loop bug
What you practise
- Fit
y = 2x + 1with raw tensors: forward, loss, backward, update underno_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?
Correct answer
Above 0, heading for 2
Why
All predictions are too low, so raising w lowers the loss: the gradient is negative and w -= lr * grad moves w up. One step is a nudge, not a jump, and w and b move together.
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.
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.