TExcelTAD
Home › Math for Machine Learning › Gradient Descent

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 f:Rd→Rf: \mathbb{R}^d \to \mathbb{R}, start at x0\mathbf{x}_0 and iterate

xi+1=xi−γ ∇f(xi)T\mathbf{x}_{i+1} = \mathbf{x}_i - \gamma\,\nabla f(\mathbf{x}_i)^T

with step size (learning rate) γ>0\gamma > 0. By the first-order Taylor expansion, for small γ\gamma each step decreases ff by about γ∥∇f∥2\gamma\lVert \nabla f \rVert^2. The iteration stops changing where ∇f=0\nabla f = \mathbf{0}: a minimum, a maximum or a saddle, although gradient descent almost never stops at the last two.

Gradient descent for least squares

For L(θ)=1N∥y−Xθ∥2L(\boldsymbol{\theta}) = \frac{1}{N}\lVert \mathbf{y} - X\boldsymbol{\theta} \rVert^2 the gradient is −2NXT(y−Xθ)-\frac{2}{N}X^T(\mathbf{y} - X\boldsymbol{\theta}) (Partial Derivatives and Gradients). We know the exact answer from the normal equations, so we can watch gradient descent approach it.

python · try it yourself
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 f(x)=12xTAxf(\mathbf{x}) = \frac{1}{2}\mathbf{x}^TA\mathbf{x} with SPD AA, the update is xi+1=(I−γA)xi\mathbf{x}_{i+1} = (I - \gamma A)\mathbf{x}_i. Along each eigenvector of AA the error is multiplied by 1−γλ1 - \gamma\lambda every step. So:

  • the iteration converges only if ∣1−γλ∣<1\lvert 1 - \gamma\lambda \rvert < 1 for every eigenvalue, i.e. γ<2/λmax⁡\gamma < 2/\lambda_{\max};
  • the slowest direction shrinks by 1−γλmin⁡1 - \gamma\lambda_{\min} per step. With the best step size the rate is governed by the condition number κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min}: roughly κ\kappa steps per digit of accuracy.
python · try it yourself
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 γ=0.11>2/λmax⁡\gamma = 0.11 > 2/\lambda_{\max} the steep direction oscillates with growing amplitude. Feature standardization helps precisely because it reduces the condition number of XTXX^TX.

In software

  • torch.optim.SGD(params, lr=...) without momentum is this update (on mini-batch gradients, see Stochastic Gradient Descent).
  • StandardScaler before gradient-based models is a conditioning fix.
  • Learning-rate finders sweep γ\gamma upward until the loss blows up, then back off: they look for the 2/λmax⁡2/\lambda_{\max} edge.

Exercises

Exercise 1: One step by hand

For f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2 starting at (2,1)(2, 1) with γ=0.1\gamma = 0.1, compute one gradient descent step.

Answer

(1.6,0.4)(1.6, 0.4).

Solution

∇f=(2x,6y)=(4,6)\nabla f = (2x, 6y) = (4, 6). New point: (2−0.4,1−0.6)=(1.6,0.4)(2 - 0.4, 1 - 0.6) = (1.6, 0.4). ff drops from 7 to 2.56+0.48=3.042.56 + 0.48 = 3.04.

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

γ<0.04\gamma < 0.04.

Solution

γ<2/λmax⁡=2/50=0.04\gamma < 2/\lambda_{\max} = 2/50 = 0.04. The flat direction (λ=0.5\lambda = 0.5) then shrinks by only 1−0.04⋅0.5=0.981 - 0.04 \cdot 0.5 = 0.98 per step at best: about 115 steps per factor 10.

Exercise 3: Minimize a 1D function (code)

Run gradient descent on f(x)=(x−3)2+1f(x) = (x - 3)^2 + 1 from x=0x = 0 with γ=0.25\gamma = 0.25 for 10 steps. What error factor does each step apply?

Answer

Each step halves the distance to 3.

Solution

xi+1=xi−0.25⋅2(xi−3)x_{i+1} = x_i - 0.25 \cdot 2(x_i - 3), so xi+1−3=0.5(xi−3)x_{i+1} - 3 = 0.5(x_i - 3).

python · try it yourself
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…

  1. x+γ∇fT\mathbf{x} + \gamma\nabla f^T
  2. x−γ∇fT\mathbf{x} - \gamma\nabla f^T
  3. x−H−1∇fT\mathbf{x} - H^{-1}\nabla f^T
  4. γx\gamma\mathbf{x}

On a quadratic with Hessian eigenvalues up to λmax⁡\lambda_{\max}, gradient descent converges if…

  1. γ<2/λmax⁡\gamma < 2/\lambda_{\max}
  2. γ>λmax⁡\gamma > \lambda_{\max}
  3. γ=1\gamma = 1
  4. always

A large condition number of the Hessian makes gradient descent…

  1. faster
  2. slow, zig-zagging along steep directions while crawling along flat ones
  3. exact in one step
  4. independent of the step size