Linear Regression From Scratch With PyTorch Autograd
Linear regression is the best first model for learning PyTorch, because you can check the answer. In this tutorial you will generate noisy data from a known line, define the parameters as tensors, compute the mean squared error, let autograd produce gradients, and update the parameters by gradient descent. No nn module or optimiser is used, so every step is visible.
Step 1: create data
We generate points from the line y = 3x + 2 and add noise. Since we know the true slope and intercept, we can tell whether training worked.
import torch
torch.manual_seed(42)
n = 200
x = torch.rand(n, 1) * 10 # inputs in [0, 10)
noise = torch.randn(n, 1) * 0.5
y = 3.0 * x + 2.0 + noise # targets
Both x and y have shape (200, 1): 200 samples with one feature each. Keeping the second dimension, instead of using shape (200,), will make the extension to several features straightforward.
Step 2: define the parameters
w = torch.randn(1, 1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
The weight starts random and the bias at zero. Both require gradients because we want to learn them. The model is pred = x @ w + b: a matrix product of shape (200, 1) @ (1, 1) plus a bias that broadcasts across all rows.
Step 3: the training loop
lr = 0.01
for epoch in range(500):
pred = x @ w + b
loss = ((pred - y) ** 2).mean() # mean squared error
loss.backward()
with torch.no_grad():
w -= lr * w.grad
b -= lr * b.grad
w.grad.zero_()
b.grad.zero_()
if epoch % 100 == 0:
print(f"epoch {epoch:3d} loss {loss.item():.4f}")
print("w =", w.item(), "b =", b.item())
Walk through the loop. First the forward pass produces predictions. The loss measures how far they are from the targets; squaring makes errors positive and punishes big ones more. Then loss.backward() fills w.grad and b.grad with the slope of the loss in each direction. We update inside torch.no_grad() because the update itself should not be recorded in the graph, and we use in-place operators (-=) so w remains the same leaf tensor. Finally, we zero the gradients so the next iteration starts fresh.
The printed loss should fall quickly in the first hundred epochs and then flatten near 0.25, which is the variance of the noise we added (0.5 squared). The final w should be close to 3 and b close to 2. Small differences are expected because of the noise and the finite number of steps.
Choosing the learning rate
The learning rate lr controls the step size. Try lr = 0.1 on this data: the loss will blow up to huge numbers or nan, because the step overshoots the minimum and the error grows each time. Try lr = 0.0001: training becomes very slow, and after 500 epochs the weights are still far from the target. The best value is the largest one that still decreases the loss smoothly. Scaling the inputs to a similar range, for example dividing x by 10, makes a larger learning rate safe and training faster.
Extending to many features
Nothing in the loop depends on having one feature. For d features, make x shape (n, d) and w shape (d, 1).
d = 3
X = torch.randn(500, d)
true_w = torch.tensor([[1.5], [-2.0], [0.5]])
Y = X @ true_w + 0.7 + 0.1 * torch.randn(500, 1)
w = torch.zeros(d, 1, requires_grad=True)
b = torch.zeros(1, requires_grad=True)
for _ in range(300):
loss = ((X @ w + b - Y) ** 2).mean()
loss.backward()
with torch.no_grad():
w -= 0.1 * w.grad
b -= 0.1 * b.grad
w.grad.zero_()
b.grad.zero_()
print(w.flatten(), b) # close to [1.5, -2.0, 0.5] and 0.7
The learned weights land very close to the true ones. This is the same model that nn.Linear(3, 1) implements; the next posts replace each hand-written piece with the library version.
Common mistakes
- Using
w = w - lr * w.gradinstead of an in-place update insideno_grad. It creates a new non-leaf tensor with no.gradon the next step. - Forgetting to zero gradients, so updates grow larger each epoch.
- Mismatched shapes such as predictions
(200, 1)and targets(200,), which broadcast into a200x200matrix and give a wrong loss. - Unscaled inputs with a large learning rate, causing divergence.
You have now trained a model with only tensors and autograd. Everything that follows in this course is the same idea with better building blocks.
Comments
No comments yet. Have a question or a tip? Be the first to share it.