Gradient Descent
Most ML models are trained by the same simple loop: compute the gradient of the loss, take a small step against it, repeat. This lesson derives gradient descent, runs it on a least-squares problem, and shows what its convergence depends on: the step size and the curvature of the loss. More depth in Optimization.
The update rule
To minimize , start at and iterate
with step size (learning rate) . By the first-order Taylor expansion, for small each step decreases by about . The iteration stops changing where : a minimum, a maximum or a saddle, although gradient descent almost never stops at the last two.
Gradient descent for least squares
For the gradient is (Partial Derivatives and Gradients). We know the exact answer from the normal equations, so we can watch gradient descent approach it.
import numpy as np
rng = np.random.default_rng(0)
N = 200
X = np.column_stack([np.ones(N), rng.normal(size=N), rng.normal(size=N)])
y = X @ np.array([1.0, 2.0, -3.0]) + 0.5 * rng.normal(size=N)
theta_star = np.linalg.solve(X.T @ X, X.T @ y)
theta = np.zeros(3)
lr = 0.1
for i in range(201):
grad = -2 / N * X.T @ (y - X @ theta)
if i % 50 == 0:
loss = np.mean((y - X @ theta) ** 2)
print(f"step {i:3d}: loss {loss:.5f}, distance to optimum {np.linalg.norm(theta - theta_star):.2e}")
theta -= lr * grad
print("gradient descent:", np.round(theta, 4), " normal equations:", np.round(theta_star, 4))step 0: loss 15.80164, distance to optimum 3.74e+00
step 50: loss 0.24798, distance to optimum 4.62e-05
step 100: loss 0.24798, distance to optimum 1.89e-09
step 150: loss 0.24798, distance to optimum 9.23e-14
step 200: loss 0.24798, distance to optimum 1.94e-15
gradient descent: [ 1.0047 2.0336 -2.9702] normal equations: [ 1.0047 2.0336 -2.9702]
How fast? It depends on the curvature
For a quadratic with SPD , the update is . Along each eigenvector of the error is multiplied by every step. So:
- the iteration converges only if for every eigenvalue, i.e. ;
- the slowest direction shrinks by per step. With the best step size the rate is governed by the condition number : roughly steps per digit of accuracy.
import numpy as np
A = np.diag([1.0, 20.0]) # condition number 20
x0 = np.array([1.0, 1.0])
for lr in (0.01, 0.05, 0.09, 0.11):
x = x0.copy()
for _ in range(100):
x = x - lr * (A @ x)
status = "diverged" if np.linalg.norm(x) > 1 else "converging"
print(f"lr={lr:4}: |x| after 100 steps = {np.linalg.norm(x):.3e} ({status}; limit 2/20 = 0.1)")lr=0.01: |x| after 100 steps = 3.660e-01 (converging; limit 2/20 = 0.1)
lr=0.05: |x| after 100 steps = 5.921e-03 (converging; limit 2/20 = 0.1)
lr=0.09: |x| after 100 steps = 8.019e-05 (converging; limit 2/20 = 0.1)
lr=0.11: |x| after 100 steps = 8.282e+07 (diverged; limit 2/20 = 0.1)
With the steep direction oscillates with growing amplitude. Feature standardization helps precisely because it reduces the condition number of .
In software
torch.optim.SGD(params, lr=...)without momentum is this update (on mini-batch gradients, see Stochastic Gradient Descent).StandardScalerbefore gradient-based models is a conditioning fix.- Learning-rate finders sweep upward until the loss blows up, then back off: they look for the edge.
Exercises
Exercise 1: One step by hand
For starting at with , compute one gradient descent step.
Answer
.
Solution
. New point: . drops from 7 to .
Exercise 2: Largest stable step
The Hessian of a quadratic loss has eigenvalues 0.5, 4 and 50. What is the largest step size for which gradient descent converges?
Answer
.
Solution
. The flat direction () then shrinks by only per step at best: about 115 steps per factor 10.
Exercise 3: Minimize a 1D function (code)
Run gradient descent on from with for 10 steps. What error factor does each step apply?
Answer
Each step halves the distance to 3.
Solution
, so .
x = 0.0
for i in range(10):
x -= 0.25 * 2 * (x - 3)
print(round(x, 6), round(3 - x, 6), round(3 * 0.5**10, 6))2.99707 0.00293 0.00293
Test yourself
Gradient descent updates parameters by…
On a quadratic with Hessian eigenvalues up to , gradient descent converges if…
- always
A large condition number of the Hessian makes gradient descent…
- faster
- slow, zig-zagging along steep directions while crawling along flat ones
- exact in one step
- independent of the step size