Gradient descent

Walking downhill one step at a time — and the one number that decides whether you arrive, oscillate or fly off.

What you'll learn
  • Write the gradient descent update and know what each part does
  • Predict from the curvature which step sizes converge
  • Explain why a stretched valley makes gradient descent zig-zag

The gradient \(\nabla f(x)\) points uphill, in the direction where \(f\) grows fastest. So to go downhill, step the other way:

\[x_{k+1} = x_k - \eta\,\nabla f(x_k)\]

\(\eta\) is the step size, or learning rate. grad.py draws this on the one-dimensional cost

\[J(w) = \tfrac12 (w - 1.5)^2 + 0.3\]

starting at \(w = 3.2\): the tangent at the start points uphill, so descent moves left, towards the minimum at \(w = 1.5\).

How big a step?

For this cost the gradient is \(J’(w) = w - 1.5\), so one step does

\[w_{k+1} - 1.5 = (1 - \eta)\,(w_k - 1.5)\]

The distance to the minimum is multiplied by \(1 - \eta\) every step. That single factor explains everything:

Step size Factor \(1-\eta\) Behaviour
\(0 < \eta < 1\) between 0 and 1 approaches smoothly, from one side
\(\eta = 1\) 0 lands on the minimum in one step
\(1 < \eta < 2\) between −1 and 0 overshoots, oscillates, but converges
\(\eta > 2\) below −1 overshoots further each time — diverges
η = 0.1 and η = 1.9 finish at exactly the same cost: both shrink the error by a factor of 0.9 per step, one from the near side and one by oscillating. η = 0.5 and 1.5 both shrink it by 0.5.

In general the limit is \(\eta < 2/L\), where \(L\) is the largest curvature of the function — the largest eigenvalue of its Hessian, from the quadratic-forms lesson. Here \(L = 1\).

Two dimensions: the zig-zag

In more than one dimension the curvature differs by direction, and a single step size has to suit all of them. Take a stretched valley, \(f = \tfrac12(x^2 + 8y^2)\): curvature 1 along \(x\), 8 along \(y\).

Gradient descent across the contours of a stretched valley. The steep direction caps the step size at 2/8 = 0.25, and anything above 1/8 overshoots in that direction — while the shallow direction crawls. Drag η past 0.25 to watch it diverge.

The steep direction forces a small step; the shallow direction then crawls. The ratio of largest to smallest curvature — the condition number again — measures how bad this gets. It is the reason practical optimizers use momentum, or rescale the problem, rather than plain gradient descent.

Try it yourself. Modify grad.py to actually run the iteration from \(w = 3.2\) and print \(w_k\) for \(\eta = 0.5\), \(1.0\), \(1.9\) and \(2.1\). Check each against the factor \(1 - \eta\) in the table. Then, in the animation, find the step size that reaches the minimum in the fewest steps — and explain why it is not 0.25.

View source on GitHub →