Gradient Descent
Gradient descent finds the minimum of a function by repeatedly stepping downhill, in the direction opposite to the derivative (or gradient). It is the workhorse behind training linear models, neural networks and large language models. This lesson implements it from scratch on a 1-D function, a 2-D bowl and a tiny linear regression, and shows what goes wrong when the learning rate is too small or too big.
The update rule
The derivative tells you which way is uphill and how steep it is. To go down, step against it:
(eta) is the learning rate (step size). For a function of several variables, replace the derivative by the gradient , the vector of partial derivatives, which points in the direction of steepest ascent:
Near a minimum the gradient shrinks, so the steps shrink automatically. The method stops being useful when , which happens at a minimum, but also at saddle points and flat plateaus.
Note: Gradient descent is Euler's method with step applied to the "gradient flow" equation . The ball rolls downhill; Euler follows it in discrete steps.
One dimension and the learning rate
Take , minimum at , with . One step maps the distance to the minimum to , so we can predict everything: the method converges when , i.e. .
def descend(eta, x=0.0, steps=50):
path = [x]
for _ in range(steps):
x = x - eta * 2 * (x - 3)
path.append(x)
return path
for eta in [0.01, 0.1, 0.5, 0.9, 1.05]:
p = descend(eta)
print(f"eta = {eta:<4}: x1 = {p[1]:7.3f} x5 = {p[5]:8.3f} x50 = {p[50]:10.4f}")eta = 0.01: x1 = 0.060 x5 = 0.288 x50 = 1.9075
eta = 0.1 : x1 = 0.600 x5 = 2.017 x50 = 3.0000
eta = 0.5 : x1 = 3.000 x5 = 3.000 x50 = 3.0000
eta = 0.9 : x1 = 5.400 x5 = 3.983 x50 = 3.0000
eta = 1.05: x1 = 6.300 x5 = 7.832 x50 = -349.1726
| Factor | Behaviour | |
|---|---|---|
| 0.01 | 0.98 | too small: after 50 steps still far from 3 |
| 0.1 | 0.8 | steady convergence |
| 0.5 | 0 | lands exactly on the minimum in one step (only for this parabola) |
| 0.9 | −0.8 | overshoots, zigzags in, still converges |
| 1.05 | −1.1 | each step overshoots further: divergence |
The best depends on the curvature: for the ideal step is . That observation is the idea behind Newton's method, which divides by the second derivative.
Two dimensions: narrow valleys
Real loss surfaces are stretched: steep in some directions, flat in others. Take with . The steep direction limits the learning rate to , and with such a small the flat direction crawls.
import numpy as np
import matplotlib.pyplot as plt
grad = lambda p: np.array([2 * p[0], 20 * p[1]])
f = lambda p: p[0]**2 + 10 * p[1]**2
plt.figure(figsize=(6, 4))
X, Y = np.meshgrid(np.linspace(-9, 9, 200), np.linspace(-3, 3, 200))
plt.contour(X, Y, X**2 + 10 * Y**2, levels=[1, 4, 10, 25, 50, 80], colors="0.75")
for eta in [0.02, 0.09, 0.101]:
p, path = np.array([8.0, 2.0]), []
for step in range(60):
path.append(p)
p = p - eta * grad(p)
path = np.array(path)
plt.plot(path[:, 0], path[:, 1], ".-", ms=3, label=f"η = {eta}")
print(f"eta = {eta:<5}: after 60 steps f = {f(p):.3e} at ({p[0]:.4f}, {p[1]:.4f})")
plt.ylim(-3, 3); plt.legend(); plt.title("Gradient descent on x² + 10y²")eta = 0.02 : after 60 steps f = 4.772e-01 at (0.6908, 0.0000)
eta = 0.09 : after 60 steps f = 3.004e-09 at (0.0001, 0.0000)
eta = 0.101: after 60 steps f = 4.306e+02 at (0.0000, 6.5621)
is safe but slow: is gone quickly, yet only shrinks by 0.96 per step and is still at 0.69 after 60 steps. zigzags across the valley (the factor flips sign every step) while sliding along it much faster, and reaches the minimum. is just past the limit: the factor is −1.02 and the coordinate slowly explodes. The ratio of the largest to the smallest curvature (here ) is the condition number; the larger it is, the slower plain gradient descent becomes. Momentum and Adam were invented to cope with exactly this. The curvatures are the eigenvalues of the Hessian.
A tiny linear regression
Fit a line to noisy data by minimising the mean squared error
(both partial derivatives come from the chain rule):
import numpy as np
rng = np.random.default_rng(7)
x = rng.uniform(0, 5, 30)
y = 2.0 * x + 1.0 + rng.normal(0, 0.5, 30) # true line: w = 2, b = 1
w, b, eta = 0.0, 0.0, 0.05
for epoch in range(1, 501):
err = w * x + b - y
gw, gb = 2 * np.mean(err * x), 2 * np.mean(err)
w, b = w - eta * gw, b - eta * gb
if epoch in (1, 10, 50, 200, 500):
print(f"epoch {epoch:3d}: loss {np.mean(err**2):8.4f} w = {w:.4f} b = {b:.4f}")
print("least squares (np.polyfit):", np.round(np.polyfit(x, y, 1), 4))epoch 1: loss 47.4770 w = 2.0439 b = 0.6210
epoch 10: loss 0.2023 w = 2.1052 b = 0.6834
epoch 50: loss 0.1953 w = 2.0727 b = 0.7915
epoch 200: loss 0.1938 w = 2.0501 b = 0.8665
epoch 500: loss 0.1938 w = 2.0492 b = 0.8695
least squares (np.polyfit): [2.0492 0.8695]
The loss falls from about 47 to 0.2 within 10 epochs and then creeps down; after 500 epochs and agree with the exact least-squares answer. Try and the loss blows up: the largest curvature of (the top eigenvalue of its Hessian, ) is about 19.3 for this data, so must stay below .
In software
- Machine learning: every model in linear regression, logistic regression and neural networks is trained by some form of gradient descent. Stochastic gradient descent (SGD) uses the gradient of a random mini-batch instead of the full dataset.
- LLMs: training a language model is gradient descent with Adam on billions of parameters; the gradients come from backpropagation and automatic differentiation.
- Learning-rate schedules (warm-up, cosine decay) exist because the right changes during training.
- Beyond ML: inverse kinematics, layout engines, image registration and physics constraint solvers all minimise an error function by following its gradient.
Go further: Linear Regression by Gradient Descent uses this loop to fit a real model, then moves on to mini-batch SGD and the scikit-learn version.
Exercises
Exercise 1: Three steps by hand
Minimise with , starting at . Write down .
Answer
, , (heading for the minimum at ).
Solution
The gap to 2 halves every step, because .
Exercise 2: The learning-rate limit
For , which learning rates make gradient descent converge? Which reaches the minimum in one step?
Answer
; jumps to 0 in one step.
Solution
Exercise 3: A 2-D gradient
For , compute at and the point after one step with .
Answer
; the new point is .
Solution
drops from to .
Exercise 4: Fit without an intercept
Data . Fit by gradient descent on the MSE, starting at with , and compare with the exact answer .
Answer
.
Solution
xs, ys = [1, 2, 3], [3, 5, 8]
w, eta = 0.0, 0.05
for step in range(100):
g = 2 / 3 * sum((w * x - y) * x for x, y in zip(xs, ys))
w -= eta * g
print(f"gradient descent w = {w:.6f} exact {37 / 14:.6f}")gradient descent w = 2.642857 exact 2.642857
Test yourself
What happens if the learning rate is far too large?
- Training is just slower
- The steps overshoot more and more and the loss diverges
- The model becomes more accurate
- The gradient becomes zero
Why does the update subtract the gradient?
- The gradient points in the direction of steepest increase
- Subtraction is faster
- The gradient is always negative
- To keep parameters positive
On , plain gradient descent is slow because…
- The function has no minimum
- The gradient cannot be computed
- The steep direction forces a small , which makes progress along tiny
- The minimum is at infinity