TExcelTAD
Home › Calculus Essentials › Gradient Descent

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 f′(x)f'(x) tells you which way is uphill and how steep it is. To go down, step against it:

x←x−η⋅f′(x)x \leftarrow x - \eta \cdot f'(x)

η\eta (eta) is the learning rate (step size). For a function of several variables, replace the derivative by the gradient ∇f\nabla f, the vector of partial derivatives, which points in the direction of steepest ascent:

θ←θ−η⋅∇f(θ)\theta \leftarrow \theta - \eta \cdot \nabla f(\theta)

Near a minimum the gradient shrinks, so the steps shrink automatically. The method stops being useful when ∇f≈0\nabla f \approx 0, which happens at a minimum, but also at saddle points and flat plateaus.

Note: Gradient descent is Euler's method with step η\eta applied to the "gradient flow" equation θ′=−∇f(θ)\theta' = -\nabla f(\theta). The ball rolls downhill; Euler follows it in discrete steps.

One dimension and the learning rate

Take f(x)=(x−3)2+1f(x) = (x - 3)^2 + 1, minimum at x=3x = 3, with f′(x)=2(x−3)f'(x) = 2(x - 3). One step maps the distance to the minimum d=x−3d = x - 3 to (1−2η) d(1 - 2\eta)\,d, so we can predict everything: the method converges when ∣1−2η∣<1\lvert 1 - 2\eta \rvert < 1, i.e. 0<η<10 < \eta < 1.

python · try it yourself
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
η\eta Factor 1−2η1 - 2\eta 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 η\eta depends on the curvature: for f′′=2f'' = 2 the ideal step is 1/f′′1/f''. 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 f(x,y)=x2+10y2f(x, y) = x^2 + 10y^2 with ∇f=(2x,20y)\nabla f = (2x, 20y). The steep yy direction limits the learning rate to η<2/20=0.1\eta < 2/20 = 0.1, and with such a small η\eta the flat xx direction crawls.

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

η=0.02\eta = 0.02 is safe but slow: yy is gone quickly, yet xx only shrinks by 0.96 per step and is still at 0.69 after 60 steps. η=0.09\eta = 0.09 zigzags across the valley (the yy factor 1−20⋅0.09=−0.81 - 20 \cdot 0.09 = -0.8 flips sign every step) while sliding along it much faster, and reaches the minimum. η=0.101\eta = 0.101 is just past the limit: the yy factor is −1.02 and the yy coordinate slowly explodes. The ratio of the largest to the smallest curvature (here 20:220 : 2) 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 y^=wx+b\hat{y} = wx + b to noisy data by minimising the mean squared error

L(w,b)=1n∑(wxi+b−yi)2∂L∂w=2n∑(wxi+b−yi) xi∂L∂b=2n∑(wxi+b−yi)\begin{aligned} L(w, b) &= \frac{1}{n} \sum (wx_i + b - y_i)^2 \\ \frac{\partial L}{\partial w} &= \frac{2}{n} \sum (wx_i + b - y_i)\,x_i \\ \frac{\partial L}{\partial b} &= \frac{2}{n} \sum (wx_i + b - y_i) \end{aligned}

(both partial derivatives come from the chain rule):

python · try it yourself
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 ww and bb agree with the exact least-squares answer. Try η=0.2\eta = 0.2 and the loss blows up: the largest curvature of LL (the top eigenvalue of its Hessian, 2[mean x2mean xmean x1]2\begin{bmatrix} \text{mean } x^2 & \text{mean } x \\ \text{mean } x & 1 \end{bmatrix}) is about 19.3 for this data, so η\eta must stay below 2/19.3≈0.102/19.3 \approx 0.10.

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 η\eta 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 f(x)=x2−4xf(x) = x^2 - 4x with η=0.25\eta = 0.25, starting at x=0x = 0. Write down x1,x2,x3x_1, x_2, x_3.

Answer

x1=1x_1 = 1, x2=1.5x_2 = 1.5, x3=1.75x_3 = 1.75 (heading for the minimum at x=2x = 2).

Solution
f′(x)=2x−4x1=0−0.25⋅(−4)=1x2=1−0.25⋅(−2)=1.5x3=1.5−0.25⋅(−1)=1.75\begin{aligned} f'(x) &= 2x - 4 \\ x_1 &= 0 - 0.25 \cdot (-4) = 1 \\ x_2 &= 1 - 0.25 \cdot (-2) = 1.5 \\ x_3 &= 1.5 - 0.25 \cdot (-1) = 1.75 \end{aligned}

The gap to 2 halves every step, because 1−ηf′′=1−0.25⋅2=0.51 - \eta f'' = 1 - 0.25 \cdot 2 = 0.5.

Exercise 2: The learning-rate limit

For f(x)=5x2f(x) = 5x^2, which learning rates make gradient descent converge? Which η\eta reaches the minimum in one step?

Answer

0<η<0.20 < \eta < 0.2; η=0.1\eta = 0.1 jumps to 0 in one step.

Solution
f′(x)=10x⇒x←x−10ηx=(1−10η) xconverge  ⟺  ∣1−10η∣<1  ⟺  0<η<0.2one step  ⟺  1−10η=0  ⟺  η=0.1=1/f′′\begin{aligned} &f'(x) = 10x \quad\Rightarrow\quad x \leftarrow x - 10\eta x = (1 - 10\eta)\,x \\ &\text{converge} \iff \lvert 1 - 10\eta \rvert < 1 \iff 0 < \eta < 0.2 \\ &\text{one step} \iff 1 - 10\eta = 0 \iff \eta = 0.1 = 1/f'' \end{aligned}

Exercise 3: A 2-D gradient

For f(x,y)=(x−1)2+2(y+2)2f(x, y) = (x - 1)^2 + 2(y + 2)^2, compute ∇f\nabla f at (3,0)(3, 0) and the point after one step with η=0.1\eta = 0.1.

Answer

∇f(3,0)=(4,8)\nabla f(3, 0) = (4, 8); the new point is (2.6,−0.8)(2.6, -0.8).

Solution
∂f∂x=2(x−1)=4,∂f∂y=4(y+2)=8(3,0)−0.1⋅(4,8)=(2.6,−0.8)\begin{aligned} &\frac{\partial f}{\partial x} = 2(x - 1) = 4, \qquad \frac{\partial f}{\partial y} = 4(y + 2) = 8 \\ &(3, 0) - 0.1 \cdot (4, 8) = (2.6, -0.8) \end{aligned}

ff drops from 4+8=124 + 8 = 12 to 2.56+2.88=5.442.56 + 2.88 = 5.44.

Exercise 4: Fit without an intercept

Data (1,3),(2,5),(3,8)(1, 3), (2, 5), (3, 8). Fit y^=wx\hat{y} = wx by gradient descent on the MSE, starting at w=0w = 0 with η=0.05\eta = 0.05, and compare with the exact answer w=∑xy/∑x2w = \sum xy / \sum x^2.

Answer

w→37/14≈2.642857w \to 37/14 \approx 2.642857.

Solution
L(w)=13∑(wxi−yi)2L′(w)=23∑(wxi−yi) xi=23(14w−37)L′=0⇒w=37/14≈2.642857\begin{aligned} L(w) &= \frac{1}{3} \sum (wx_i - y_i)^2 \\ L'(w) &= \frac{2}{3} \sum (wx_i - y_i)\,x_i = \frac{2}{3}(14w - 37) \\ L' &= 0 \quad\Rightarrow\quad w = 37/14 \approx 2.642857 \end{aligned}
python · try it yourself
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?

  1. Training is just slower
  2. The steps overshoot more and more and the loss diverges
  3. The model becomes more accurate
  4. The gradient becomes zero

Why does the update subtract the gradient?

  1. The gradient points in the direction of steepest increase
  2. Subtraction is faster
  3. The gradient is always negative
  4. To keep parameters positive

On f(x,y)=x2+100y2f(x, y) = x^2 + 100y^2, plain gradient descent is slow because…

  1. The function has no minimum
  2. The gradient cannot be computed
  3. The steep yy direction forces a small η\eta, which makes progress along xx tiny
  4. The minimum is at infinity