Part 04 / Topic 3 of 6
Gradient descent
Gradient descent: compute the gradient of the loss, step the parameters a little against it, repeat. The step size is the learning rate.
# examples/01_linear_regression_with_gradient_descent_checked.py
import numpy as np
rng = np.random.default_rng(1)
X = rng.uniform(0, 10, size=(200, 1))
y = 3.0 * X[:, 0] + 5.0 + rng.normal(0, 1, size=200)
w, b, lr = 0.0, 0.0, 0.01
for step in range(2000):
pred = w * X[:, 0] + b
err = pred - y
w -= lr * 2 * (err * X[:, 0]).mean()
b -= lr * 2 * err.mean()
X1 = np.c_[X, np.ones(len(X))]
w_exact, b_exact = np.linalg.lstsq(X1, y, rcond=None)[0]
print(f"gradient descent: w={w:.3f} b={b:.3f}")
print(f"exact solution: w={w_exact:.3f} b={b_exact:.3f}")
# gradient descent: w=2.986 b=4.981
# exact solution: w=2.986 b=4.981
Two thousand small steps land on the same answer as the formula, to three decimals. The data was generated with w=3, b=5 plus noise — both methods recover it.
The learning rate is the one knob that can ruin everything: too small crawls, too large diverges. Part 11 shows this measurably (lr=1.5 exploded the loss to 3e+29).
🧪 Quick quiz
- In gradient descent, what does the learning rate control?
- Why can you check gradient descent for linear regression against an exact answer?
Show the answers
- The size of each step against the gradient. Too small converges slowly; too large overshoots or diverges.
- Linear least squares has a closed-form solution — verified above, both gave w=2.986, b=4.981.
Done here? The practice set for Part 4 — 4 exercises with solutions — is on the part page.