Type at least 2 letters. Enter opens the first result, Esc closes.

    Optimization · Lesson 1 · Gradient descent and curvature

    Loss surfaces and gradient descent

    Beginner 55 min 4 interactive figures 3 videos Colab notebook

    Before this lesson: partial derivatives and the gradient (calculus 02); vectors and dot products (linear algebra 01). Eigenvalues appear only as a preview. Time: about 55 minutes, plus the notebook.


    Why this matters #

    Every optimizer used to train neural networks is gradient descent with extra parts: SGD uses a noisy gradient from a minibatch (lesson 05), momentum adds memory of past steps (lesson 04), and Adam rescales each coordinate (lesson 06). So the basic behaviour of gradient descent explains a lot of what you see in practice. A loss that explodes in the first steps usually means a learning rate above the stability limit. A loss that falls quickly and then crawls usually means a narrow valley (an ill-conditioned problem, lesson 02). Standardizing input features before training linear models works because it makes the valley rounder.

    1. Predict first #

    2. The picture #

    Loss surfaces and level sets #

    An optimization problem asks for a point x⋆x^\star that makes a function f:Rd→Rf: \R^d \to \R as small as possible:

    min⁡x∈Rdf(x).\min_{x \in \R^d} f(x).

    ff is the objective. In machine learning it is the loss L(θ)L(\theta), the average error of a model with parameters θ\theta on the training data. We write ff and xx in general statements and LL and θ\theta when we talk about training.

    With two variables you can draw ff as a surface over the plane: the loss surface. A contour plot shows the same information from above. Each curve is a level set {x:f(x)=c}\{x : f(x) = c\}, the set of points with the same height cc. Where the curves are close together the surface is steep; where they are far apart it is flat.

    • A minimizer x⋆x^\star satisfies f(x⋆)≤f(x)f(x^\star) \le f(x) for all xx. The value f⋆=f(x⋆)f^\star = f(x^\star) is the optimal value. This is a global minimum.
    • A local minimum is a point that is lowest only in a small neighbourhood. A function can have several local minima with different heights.
    • A stationary point (or critical point) has ∇f(x)=0\nabla f(x) = 0. Minima, maxima and saddle points are stationary points. At a saddle point the surface goes up in some directions and down in others.

    The gradient points uphill, across the contours #

    The gradient ∇f(x)\nabla f(x) is the vector of partial derivatives. For a unit vector uu, the directional derivative ∇f(x)⊤u\nabla f(x)^\top u is the slope of ff when you walk from xx in the direction uu. Since ∇f(x)⊤u=∥∇f(x)∥cos⁡θ\nabla f(x)^\top u = \|\nabla f(x)\| \cos\theta, where θ\theta is the angle between uu and ∇f(x)\nabla f(x):

    • the slope is largest, ∥∇f(x)∥\|\nabla f(x)\|, when uu points along ∇f(x)\nabla f(x) (θ=0\theta = 0);
    • the slope is most negative, −∥∇f(x)∥-\|\nabla f(x)\|, when uu points along −∇f(x)-\nabla f(x);
    • the slope is zero when uu is perpendicular to ∇f(x)\nabla f(x). These are the directions along the level set, where the height does not change.
    Interactive figure: loading…

    Drag the violet point and the small grey handle uu. The violet curve is the level set through the point, the orange arrow is ∇f(x)\nabla f(x) and the blue arrow is −∇f(x)-\nabla f(x), the direction gradient descent takes. Notice that the gradient always crosses the level set at a right angle, so in the narrow valley it points mostly across the valley, not toward the minimum (the black star). Turn uu and watch ∇f(x)⊤u\nabla f(x)^\top u: it is largest along ∇f\nabla f and zero along the level set.

    Gradient descent #

    Gradient descent (GD) starts at a point x0x_0 and repeats

    xk+1=xk−η ∇f(xk),k=0,1,2,…x_{k+1} = x_k - \eta\, \nabla f(x_k), \qquad k = 0, 1, 2, \dots

    The positive number η\eta is the step size, called the learning rate in machine learning. Each step moves downhill, perpendicular to the current contour line. The step is long where the surface is steep (large gradient) and short where it is flat.

    One variable: four regimes #

    Take the simplest loss, a parabola f(x)=λ2x2f(x) = \tfrac{\lambda}{2}x^2 with curvature λ>0\lambda > 0. Then f′(x)=λxf'(x) = \lambda x and one step gives

    xk+1=xk−ηλ xk=(1−ηλ) xk,x_{k+1} = x_k - \eta\lambda\, x_k = (1 - \eta\lambda)\, x_k ,

    and so, after kk steps,

    xk=(1−ηλ)k x0.x_k = (1 - \eta\lambda)^k\, x_0 .

    Everything depends on the single number 1−ηλ1 - \eta\lambda:

    ηλ\eta\lambda 1−ηλ1 - \eta\lambda What the iterates do
    between 0 and 1 between 0 and 1 shrink toward 0, always on the same side: monotone convergence
    exactly 1 0 reach the minimum in one step
    between 1 and 2 between −1-1 and 0 jump over 0 every step, but ∣xk∣\lvert x_k\rvert still shrinks: oscillating convergence
    exactly 2 −1-1 jump between x0x_0 and −x0-x_0 forever
    above 2 below −1-1 jump over 0 and grow every step: divergence

    So gradient descent on this parabola converges exactly when 0<η<2/λ0 < \eta < 2/\lambda. A step that is too large does not fail at once. First it overshoots and oscillates (for 1/λ<η<2/λ1/\lambda < \eta < 2/\lambda); it diverges only after the overshoot becomes larger than the distance it started from.

    Interactive figure: loading…

    Predict, then play. Set ηλ\eta\lambda with the slider, choose your prediction, then press Play. The blue arrows are the gradient-descent steps on the parabola; the chart on the right shows xkx_k against kk. Try ηλ=0.5\eta\lambda = 0.5, 11, 1.51.5, 22 and 2.22.2.

    Quick check

    On f(x)=λ2x2f(x) = \tfrac{\lambda}{2}x^2 you use a step with ηλ=1.5\eta\lambda = 1.5. What do the iterates do?

    Two variables: one step size for two curvatures #

    Now take f(x)=12(x12+10 x22)f(x) = \tfrac12(x_1^2 + 10\,x_2^2). Its contours are ellipses, ten times steeper in the x2x_2 direction: a narrow valley along the x1x_1 axis. The gradient is ∇f(x)=(x1, 10 x2)\nabla f(x) = (x_1,\ 10\,x_2), so gradient descent works on each coordinate separately:

    xk+1,1=(1−η) xk,1,xk+1,2=(1−10 η) xk,2.\begin{aligned} x_{k+1,1} &= (1 - \eta)\, x_{k,1}, \\ x_{k+1,2} &= (1 - 10\,\eta)\, x_{k,2}. \end{aligned}

    These are two copies of the 1D problem, with λ=1\lambda = 1 and λ=10\lambda = 10, but one η\eta must serve both:

    • The steep coordinate x2x_2 needs η<2/10=0.2\eta < 2/10 = 0.2, or it diverges.
    • With η\eta just below 0.20.2, the factor for x2x_2 is close to −1-1: x2x_2 jumps from one wall of the valley to the other. This is the zig-zag.
    • With such a small η\eta, the factor for x1x_1 is 1−η≥0.81 - \eta \ge 0.8: progress along the valley floor is slow. This is the crawl.

    The best compromise makes the two factors equally bad: ∣1−η∣=∣1−10η∣|1 - \eta| = |1 - 10\eta| gives η=2/11\eta = 2/11, and then both factors have size 9/11≈0.829/11 \approx 0.82. Even with this best fixed step, the error shrinks by only 9/119/11 per step: about 69 steps to reduce it by a factor 10610^6, against 1 step when both curvatures are equal (a round bowl with η=1/λ\eta = 1/\lambda).

    The ratio of the largest to the smallest curvature, here 10/110/1, is the condition number κ\kappa. Lesson 02 defines it for any function and shows that it controls the speed of gradient descent.

    Interactive figure: loading…

    Drag the blue start point and change the step. The slider gives η\eta in units of 2/L2/L, where LL is the largest curvature (here L=κL = \kappa). The blue path is gradient descent; the chart shows f(xk)−f⋆f(x_k) - f^\star on a log scale, with the theory bound dashed. Use the Try buttons: "too small" crawls, "best" uses η=2/(1+κ)\eta = 2/(1 + \kappa), "just above 2/L2/L" diverges in the steep direction. Then raise κ\kappa, and switch to the rotated quadratic: the valley no longer follows an axis, and the picture is the same.

    Quick check

    Gradient descent runs on f(x)=12(x12+10 x22)f(x) = \tfrac12(x_1^2 + 10\,x_2^2). Which coordinate sets the largest step size that does not diverge, and what is that step?

    A first nonconvex surface #

    Real losses are not quadratic. The double well f(x)=(x12−1)2+12x22f(x) = (x_1^2 - 1)^2 + \tfrac12 x_2^2 has two minimizers, (−1,0)(-1, 0) and (1,0)(1, 0), and a saddle point at (0,0)(0, 0) between them. Gradient descent goes downhill from where it starts, so the start point decides which minimum it reaches. A start with x1>0x_1 > 0 ends at (1,0)(1, 0); a start with x1<0x_1 < 0 ends at (−1,0)(-1, 0). A start exactly on the line x1=0x_1 = 0 slides down to the saddle point and stops there, because the gradient has no x1x_1-component on that line. This start is a very special case; any tiny change of x1x_1 moves the path to one of the minima. Lesson 11 studies saddle points in high dimension.

    Try it in the trajectory figure above: choose double well and drag the start across the line x1=0x_1 = 0.

    3. Definitions and main results #

    Why −∇f-\nabla f is the steepest descent direction #

    Theorem 1 (steepest ascent and descent). Let ff be differentiable at xx with ∇f(x)≠0\nabla f(x) \ne 0. Among all unit vectors uu, the directional derivative ∇f(x)⊤u\nabla f(x)^\top u is largest for u=∇f(x)/∥∇f(x)∥u = \nabla f(x)/\|\nabla f(x)\| and smallest for u=−∇f(x)/∥∇f(x)∥u = -\nabla f(x)/\|\nabla f(x)\|.

    Proof.

    1. The directional derivative in direction uu is ddtf(x+tu)∣t=0=∇f(x)⊤u\frac{d}{dt} f(x + tu)\big|_{t=0} = \nabla f(x)^\top u (chain rule, calculus 02).
    2. By the Cauchy–Schwarz inequality, ∣∇f(x)⊤u∣≤∥∇f(x)∥ ∥u∥=∥∇f(x)∥|\nabla f(x)^\top u| \le \|\nabla f(x)\|\,\|u\| = \|\nabla f(x)\|.
    3. So −∥∇f(x)∥≤∇f(x)⊤u≤∥∇f(x)∥-\|\nabla f(x)\| \le \nabla f(x)^\top u \le \|\nabla f(x)\|. Equality on the right holds only when uu is a positive multiple of ∇f(x)\nabla f(x), and on the left only when uu is a negative multiple. ■\blacksquare

    Theorem 2 (the gradient is perpendicular to the level set). Let γ(t)\gamma(t) be a differentiable curve inside the level set {f=c}\{f = c\}, with γ(0)=x\gamma(0) = x. Then ∇f(x)⊤γ′(0)=0\nabla f(x)^\top \gamma'(0) = 0.

    Proof. f(γ(t))=cf(\gamma(t)) = c for all tt. Differentiate with the chain rule: 0=ddtf(γ(t))=∇f(γ(t))⊤γ′(t)0 = \frac{d}{dt} f(\gamma(t)) = \nabla f(\gamma(t))^\top \gamma'(t). Set t=0t = 0. ■\blacksquare

    So the gradient is perpendicular to every tangent direction of the level set. In 2D the level set is a curve, and the gradient is the normal of that curve.

    A small enough step always goes down #

    Theorem 3 (descent for small steps). Let ff be differentiable at xx with ∇f(x)≠0\nabla f(x) \ne 0. Then f(x−η∇f(x))<f(x)f(x - \eta\nabla f(x)) < f(x) for every small enough η>0\eta > 0.

    Proof.

    1. Write g=∇f(x)g = \nabla f(x) and φ(η)=f(x−ηg)\varphi(\eta) = f(x - \eta g). Then φ(0)=f(x)\varphi(0) = f(x).
    2. By the chain rule, φ′(0)=∇f(x)⊤(−g)=−∥g∥2<0\varphi'(0) = \nabla f(x)^\top(-g) = -\|g\|^2 < 0.
    3. A function with negative derivative at 0 is smaller than φ(0)\varphi(0) just to the right of 0: by the definition of the derivative, (φ(η)−φ(0))/η→−∥g∥2\big(\varphi(\eta) - \varphi(0)\big)/\eta \to -\|g\|^2, so the quotient is negative for all small η>0\eta > 0. ■\blacksquare

    The theorem says "small enough", but not how small. For a quadratic we can compute the exact range; lesson 02 gives a range for any LL-smooth function: 0<η<2/L0 < \eta < 2/L.

    Fixed points are stationary points. If gradient descent converges, xk→xˉx_k \to \bar x, and ∇f\nabla f is continuous, then taking the limit in xk+1=xk−η∇f(xk)x_{k+1} = x_k - \eta\nabla f(x_k) gives xˉ=xˉ−η∇f(xˉ)\bar x = \bar x - \eta\nabla f(\bar x), so ∇f(xˉ)=0\nabla f(\bar x) = 0. The limit is a stationary point: a minimum, or (rarely) a saddle point as in the double well.

    Gradient descent on quadratics #

    Theorem 4 (1D quadratic). For f(x)=λ2x2f(x) = \tfrac{\lambda}{2}x^2 with λ>0\lambda > 0, gradient descent gives xk=(1−ηλ)kx0x_k = (1 - \eta\lambda)^k x_0. It converges to 0 from every start if and only if 0<η<2/λ0 < \eta < 2/\lambda.

    Proof. The formula follows from xk+1=(1−ηλ)xkx_{k+1} = (1 - \eta\lambda)x_k by induction. A geometric sequence rkx0r^k x_0 with x0≠0x_0 \ne 0 goes to 0 if and only if ∣r∣<1|r| < 1. Here ∣1−ηλ∣<1|1 - \eta\lambda| < 1 means −1<1−ηλ<1-1 < 1 - \eta\lambda < 1, that is, 0<ηλ<20 < \eta\lambda < 2. ■\blacksquare

    Theorem 5 (separable 2D quadratic). Let f(x)=12(λ1x12+λ2x22)f(x) = \tfrac12(\lambda_1 x_1^2 + \lambda_2 x_2^2) with 0<λ1≤λ20 < \lambda_1 \le \lambda_2. Gradient descent converges from every start if and only if η<2/λ2\eta < 2/\lambda_2. The fixed step that makes the slower of the two factors ∣1−ηλi∣|1 - \eta\lambda_i| as small as possible is η=2/(λ1+λ2)\eta = 2/(\lambda_1 + \lambda_2), and then both factors have size (λ2−λ1)/(λ2+λ1)(\lambda_2 - \lambda_1)/(\lambda_2 + \lambda_1).

    Proof.

    1. The gradient is (λ1x1,λ2x2)(\lambda_1 x_1, \lambda_2 x_2), so each coordinate follows Theorem 4 with its own λi\lambda_i. Both converge if and only if η<2/λ1\eta < 2/\lambda_1 and η<2/λ2\eta < 2/\lambda_2. Since λ2≥λ1\lambda_2 \ge \lambda_1, the second condition is the binding one.
    2. The speed is set by the slower coordinate, ρ(η)=max⁡(∣1−ηλ1∣, ∣1−ηλ2∣)\rho(\eta) = \max\big(|1 - \eta\lambda_1|,\ |1 - \eta\lambda_2|\big).
    3. For η<1/λ2\eta < 1/\lambda_2 both factors fall as η\eta grows, and for η>1/λ1\eta > 1/\lambda_1 both rise. So the best η\eta lies in [1/λ2,1/λ1][1/\lambda_2, 1/\lambda_1]. There 1−ηλ11 - \eta\lambda_1 falls and ηλ2−1\eta\lambda_2 - 1 rises, and their maximum is smallest where they are equal: 1−ηλ1=ηλ2−11 - \eta\lambda_1 = \eta\lambda_2 - 1, so η=2/(λ1+λ2)\eta = 2/(\lambda_1 + \lambda_2).
    4. Insert this η\eta: 1−2λ1/(λ1+λ2)=(λ2−λ1)/(λ2+λ1)1 - 2\lambda_1/(\lambda_1 + \lambda_2) = (\lambda_2 - \lambda_1)/(\lambda_2 + \lambda_1). ■\blacksquare

    For λ1=1\lambda_1 = 1, λ2=10\lambda_2 = 10: the limit is η<0.2\eta < 0.2, the best step is 2/112/11, and the factor is 9/119/11. Lesson 03 proves the same for any quadratic 12x⊤Ax−b⊤x\tfrac12 x^\top A x - b^\top x, with λ1,λ2\lambda_1, \lambda_2 replaced by the smallest and largest eigenvalues of AA.

    Quick check

    On the double well f(x)=(x12−1)2+12x22f(x) = (x_1^2 - 1)^2 + \tfrac12 x_2^2, gradient descent with a small step starts at (−0.3, 1)(-0.3,\ 1). Where does it end?

    Stopping rules #

    Gradient descent never stops by itself. Common rules:

    1. Gradient norm: stop when ∥∇f(xk)∥≤ε\|\nabla f(x_k)\| \le \varepsilon.
    2. Small change: stop when ∣f(xk)−f(xk+1)∣≤ε ∣f(xk)∣|f(x_{k}) - f(x_{k+1})| \le \varepsilon\,|f(x_k)| (relative change) or when ∥xk+1−xk∥\|x_{k+1} - x_k\| is small.
    3. Budget: stop after a maximum number of steps (or time). In deep learning this is the usual rule, combined with a validation loss.

    Why the gradient norm is the most direct test. A minimizer of a differentiable function must have ∇f=0\nabla f = 0, so ∥∇f(xk)∥\|\nabla f(x_k)\| measures how far xkx_k is from satisfying this condition. It does not need f⋆f^\star, which you usually do not know. A small change of ff or xx only says that progress is slow, and progress can be slow far from the minimum: with a tiny step, or on a flat plateau, or along the floor of a narrow valley. For example, on f(x)=12x2f(x) = \tfrac12 x^2 with η=0.001\eta = 0.001 from x0=10x_0 = 10, one step changes ff by only 0.2%. A relative-change rule with ε=10−2\varepsilon = 10^{-2} stops at once, while the gradient norm is 10.

    The gradient norm has a limit too: on a very flat function it can be small far from the minimizer. Lesson 02 shows that for a μ\mu-strongly convex ff, f(x)−f⋆≤∥∇f(x)∥2/(2μ)f(x) - f^\star \le \|\nabla f(x)\|^2/(2\mu), so a small gradient does guarantee a small gap when μ\mu is not tiny. Always also keep a maximum number of steps.

    Quick check

    You run gradient descent with a step that is much too small. Which stopping rule is most likely to stop it far from the minimizer?

    Answers to section 1. (1) ηλ=0.4⋅4=1.6\eta\lambda = 0.4 \cdot 4 = 1.6, so xk=(−0.6)kx_k = (-0.6)^k: it converges, and the sign changes every step. (2) No. At η=0.2\eta = 0.2 the factor for x2x_2 is 1−10⋅0.2=−11 - 10 \cdot 0.2 = -1: x2x_2 jumps between 11 and −1-1 forever, and gradient descent no longer converges. (3) Neither. The gradient is perpendicular to the contour line. In a narrow valley this means it points mostly across the valley, up the wall, and not toward the minimum. The descent direction −∇f-\nabla f points mostly down to the valley floor.

    4. Worked example #

    Run gradient descent by hand on f(x)=12(x12+10 x22)f(x) = \tfrac12(x_1^2 + 10\,x_2^2) from x0=(2,1)x_0 = (2, 1). The minimizer is x⋆=(0,0)x^\star = (0, 0) with f⋆=0f^\star = 0, and f(x0)=12(4+10)=7f(x_0) = \tfrac12(4 + 10) = 7. The gradient is ∇f(x)=(x1, 10 x2)\nabla f(x) = (x_1,\ 10\,x_2), so ∇f(x0)=(2,10)\nabla f(x_0) = (2, 10) and ∥∇f(x0)∥=104≈10.2\|\nabla f(x_0)\| = \sqrt{104} \approx 10.2.

    (a) Step η=0.1\eta = 0.1 (=1/L= 1/L).

    x1=(2,1)−0.1 (2,10)=(2−0.2, 1−1)=(1.8, 0),f(x1)=12⋅1.82=1.62.\begin{aligned} x_1 &= (2, 1) - 0.1\,(2, 10) = (2 - 0.2,\ 1 - 1) = (1.8,\ 0), \\ f(x_1) &= \tfrac12 \cdot 1.8^2 = 1.62 . \end{aligned}

    The steep coordinate is solved in one step (1−10⋅0.1=01 - 10 \cdot 0.1 = 0). The flat coordinate shrinks by 0.90.9 per step: x2=(1.62,0)x_2 = (1.62, 0), f(x2)=1.3122f(x_2) = 1.3122. After that, only the slow factor 0.90.9 is left.

    (b) Step η=0.18\eta = 0.18 (close to the limit 0.2).

    x1=(2,1)−0.18 (2,10)=(2−0.36, 1−1.8)=(1.64, −0.8).x_1 = (2, 1) - 0.18\,(2, 10) = (2 - 0.36,\ 1 - 1.8) = (1.64,\ -0.8).

    Then f(x1)=12(1.642+10⋅0.82)=12(2.6896+6.4)=4.5448f(x_1) = \tfrac12(1.64^2 + 10 \cdot 0.8^2) = \tfrac12(2.6896 + 6.4) = 4.5448. Next, ∇f(x1)=(1.64,−8)\nabla f(x_1) = (1.64, -8) and

    x2=(1.64, −0.8)−0.18 (1.64, −8)=(1.3448, 0.64),f(x2)=12(1.8085+4.096)=2.9522.\begin{aligned} x_2 &= (1.64,\ -0.8) - 0.18\,(1.64,\ -8) = (1.3448,\ 0.64), \\ f(x_2) &= \tfrac12(1.8085 + 4.096) = 2.9522 . \end{aligned}

    x2x_2 changed sign twice (factor 1−1.8=−0.81 - 1.8 = -0.8): the zig-zag. x1x_1 shrinks by 0.820.82 per step.

    (c) Step η=0.21\eta = 0.21 (above the limit). x1=(2−0.42, 1−2.1)=(1.58, −1.1)x_1 = (2 - 0.42,\ 1 - 2.1) = (1.58,\ -1.1) and f(x1)=12(2.4964+12.1)=7.2982>7f(x_1) = \tfrac12(2.4964 + 12.1) = 7.2982 > 7. The loss went up. The factor for x2x_2 is 1−2.1=−1.11 - 2.1 = -1.1, so ∣x2∣|x_2| grows by 10% each step: x2=(1.2482, 1.21)x_2 = (1.2482,\ 1.21), f(x2)=8.0995f(x_2) = 8.0995.

    How many steps? The error shrinks at least by the slower factor ρ=max⁡(∣1−η∣,∣1−10η∣)\rho = \max(|1 - \eta|, |1 - 10\eta|) per step, so a reduction by 10610^6 needs about ln⁡(106)/ln⁡(1/ρ)\ln(10^6)/\ln(1/\rho) steps:

    η\eta factors 1−η1 - \eta, 1−10η1 - 10\eta ρ\rho steps for 10610^6
    0.01 0.99, 0.9 0.99 about 1,370
    0.1 0.9, 0 0.9 131
    0.18 0.82, −0.8-0.8 0.82 70
    2/11≈0.1822/11 \approx 0.182 0.8180.818, −0.818-0.818 9/119/11 69
    0.2 0.8, −1-1 1 never

    The code in section 5 counts the steps exactly (it gets 1,364 for η=0.01\eta = 0.01, because it starts from ∥x0∥=5\|x_0\| = \sqrt5, not from a point on the slow axis).

    Interactive figure: loading…

    Click the chart or move the slider to pick η\eta. The blue curve is the loss after 50 steps, f(x50)f(x_{50}), for every step size, from the same start (2,1)(2, 1). It is flat for tiny η\eta, has its lowest point near the best step 2/(μ+L)2/(\mu + L) (grey dashed line), and then rises sharply at the stability limit 2/L2/L (yellow line). The small contour plot shows the chosen run. Switch κ\kappa: the cliff moves with 2/L2/L, and the good region gets narrower as κ\kappa grows.

    5. In code #

    NumPy checks the worked example and counts the steps.

    import numpy as np
    
    lam = np.array([1.0, 10.0])                 # f(x) = 1/2 (x1^2 + 10 x2^2), minimizer x* = 0
    f = lambda x: 0.5 * np.sum(lam * x**2)
    grad = lambda x: lam * x
    
    def gd(x0, eta, steps):
        xs = [np.array(x0, dtype=float)]
        for _ in range(steps):
            xs.append(xs[-1] - eta * grad(xs[-1]))
        return np.array(xs)
    
    x0 = [2.0, 1.0]
    for eta in (0.1, 0.18, 0.21):
        xs = gd(x0, eta, 2)
        print(eta, xs[1].round(4), xs[2].round(4), [round(float(f(x)), 4) for x in xs])
    # 0.1 [1.8 0. ] [1.62 0.  ] [7.0, 1.62, 1.3122]
    # 0.18 [ 1.64 -0.8 ] [1.3448 0.64  ] [7.0, 4.5448, 2.9522]
    # 0.21 [ 1.58 -1.1 ] [1.2482 1.21  ] [7.0, 7.2982, 8.0995]
    
    def steps_to(eta, tol=1e-6, kmax=5000):
        """Steps until ||x_k|| <= tol * ||x_0||, or None if that never happens."""
        x = np.array(x0); n0 = np.linalg.norm(x)
        for k in range(kmax):
            if np.linalg.norm(x) <= tol * n0:
                return k
            if np.linalg.norm(x) > 1e6:          # diverged
                return None
            x = x - eta * grad(x)
        return None
    
    print([steps_to(eta) for eta in (0.01, 0.1, 0.18, 2 / 11, 0.2, 0.21)])
    # [1364, 131, 70, 69, None, None]
    print(2 / lam.max(), abs(1 - 0.2 * lam))   # stability limit and the two factors at eta = 0.2
    # 0.2 [0.8 1. ]
    

    The notebook adds a gradient check by finite differences, the four 1D regimes, a numerical search for the largest stable step, and gradient descent on a real regression dataset.

    6. Where it shows up #

    • Training neural networks. Every training step of SGD, momentum or Adam is a gradient step on the loss, with a gradient from backpropagation (calculus 06). The learning rate is usually the most important hyperparameter to tune.
    • Divergence and loss spikes. Near a minimum, the loss behaves like a quadratic whose largest curvature is the largest Hessian eigenvalue. A step above about 2/λmax⁡2/\lambda_{\max} makes the loss oscillate and grow, as in the worked example (c). Lessons 07 and 11 connect this to warmup and to the "edge of stability".
    • Linear and logistic regression. Their losses are convex, so gradient descent reaches the global minimum. Unscaled features (one in metres, one in millimetres) make a narrow valley and slow gradient descent down; standardizing them is the standard fix (lesson 02).
    • ML for science. Gradient-based optimization fits physical models to data: the parameters of an ODE model, the initial state in weather data assimilation (4D-Var), or the material model in full-waveform inversion. The gradient comes from automatic differentiation or an adjoint method, and the same step-size questions appear.

    7. Common mistakes #

    • Drawing the gradient along the valley. The gradient is perpendicular to the contour line. In a narrow valley it points mostly across the valley, not toward the minimum.
    • "A larger learning rate is always faster." Only up to 2/λmax⁡2/\lambda_{\max}. Close to the limit the steep direction zig-zags, and above it gradient descent diverges.
    • "ηλ>1\eta\lambda > 1 means divergence." Between 1 and 2 the iterates overshoot but still converge. Divergence starts at ηλ>2\eta\lambda > 2.
    • "The loss went up once, so the step is too large." On a quadratic with a stable step, ff decreases every step. But with noisy minibatch gradients (lesson 05) or on nonconvex losses, single increases are normal; look at the trend.
    • Stopping on a small change of the loss alone. With a small step or on a plateau, the change is small far from the minimum. Check the gradient norm and keep a step budget.
    • "Gradient descent finds the global minimum." Only for convex functions (lesson 02). On a nonconvex loss it finds a stationary point that depends on the start.

    8. Check yourself #

    1. f(x)=3x2f(x) = 3x^2. Which step sizes make gradient descent converge from every start? Which step reaches the minimum in one step?
      Answerf′(x)=6xf'(x) = 6x, so λ=6\lambda = 6 and xk+1=(1−6η)xkx_{k+1} = (1 - 6\eta)x_k. It converges for 0<η<2/6=1/30 < \eta < 2/6 = 1/3. The step η=1/6\eta = 1/6 gives factor 0: one step.
    2. Compute one gradient-descent step with η=0.5\eta = 0.5 on f(x)=x12+x1x2+x22f(x) = x_1^2 + x_1 x_2 + x_2^2 from (1,1)(1, 1).
      Answer∇f=(2x1+x2, x1+2x2)=(3,3)\nabla f = (2x_1 + x_2,\ x_1 + 2x_2) = (3, 3) at (1,1)(1, 1). The step gives (1,1)−0.5 (3,3)=(−0.5, −0.5)(1, 1) - 0.5\,(3, 3) = (-0.5,\ -0.5). The value goes from 33 to 0.750.75.
    3. At the point (1,1)(1, 1) of the level set x12+4x22=5x_1^2 + 4x_2^2 = 5, give a vector perpendicular to the level set and a vector tangent to it.
      AnswerWith f=x12+4x22f = x_1^2 + 4x_2^2, ∇f(1,1)=(2,8)\nabla f(1, 1) = (2, 8) is perpendicular. A tangent vector is perpendicular to it, for example (8,−2)(8, -2) or (4,−1)(4, -1): (2,8)⋅(4,−1)=0(2, 8)\cdot(4, -1) = 0.
    4. On f(x)=12(x12+100 x22)f(x) = \tfrac12(x_1^2 + 100\,x_2^2), what is the largest stable step, the best fixed step, and the factor per step with the best step?
      AnswerLargest stable: η<2/100=0.02\eta < 2/100 = 0.02. Best: η=2/101≈0.0198\eta = 2/101 \approx 0.0198. Factor: 99/101≈0.98099/101 \approx 0.980, so about ln⁡(106)/ln⁡(101/99)≈691\ln(10^6)/\ln(101/99) \approx 691 steps for a reduction by 10610^6.
    5. Gradient descent converges to a point xˉ\bar x. Must xˉ\bar x be a minimizer?
      AnswerNo. If ∇f\nabla f is continuous, xˉ\bar x is a stationary point, ∇f(xˉ)=0\nabla f(\bar x) = 0. It can be a saddle point, for example (0,0)(0, 0) on the double well when the start has x1=0x_1 = 0. For a convex ff, every stationary point is a global minimizer (lesson 02).
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. Write the gradient-descent update.

    2. Why is −∇f(x)-\nabla f(x) the steepest descent direction?

    3. Why is the gradient perpendicular to the level set?

    4. Gradient descent on f(x)=λ2x2f(x) = \tfrac{\lambda}{2}x^2: give xkx_k.

    5. For which step sizes does gradient descent converge on λ2x2\tfrac{\lambda}{2}x^2?

    6. On 12(x12+10x22)\tfrac12(x_1^2 + 10x_2^2), what is the largest stable step and the best fixed step?

    7. What causes the zig-zag of gradient descent in a narrow valley?

    8. Why is the gradient norm a better stopping test than a small change in ff?

    9. Gradient descent converges to xˉ\bar x, and ∇f\nabla f is continuous. What do you know about xˉ\bar x?

    Open the review →

    9. Interview angle #

    • "What happens if the learning rate is too large?" — The loss oscillates and then explodes. On a quadratic, the error along the steepest direction is multiplied by 1−ηλmax⁡1 - \eta\lambda_{\max}, which is below −1-1 once η>2/λmax⁡\eta > 2/\lambda_{\max}.
    • "Why does gradient descent zig-zag?" — The gradient is perpendicular to the contours, so in a narrow valley it points across the valley. The step that is safe for the steep wall is too small for the flat floor.
    • "Why do we standardize features?" — It makes the contours of a linear model's loss rounder (a smaller condition number), so one learning rate fits all directions (lesson 02).
    • "Does gradient descent find the global minimum?" — For a convex function, yes (with a suitable step). For a neural network it finds a stationary point, usually a good local minimum; the start and the step size matter.

    10. Practice #

    The notebook for this lesson runs in Colab. It has four exercises, each with a check cell and a folded solution:

    1. Write the gradients of 12x⊤Ax−b⊤x\tfrac12 x^\top A x - b^\top x and of least squares, and check them with a finite-difference gradient check.
    2. Write gradient descent that returns the whole path, and test the four 1D regimes.
    3. Find the largest stable step numerically by bisection and compare it with 2/λmax⁡2/\lambda_{\max}.
    4. Gradient descent with a gradient-norm stopping rule on the diabetes regression data, with raw and with standardized features: count the steps.

    11. Watch and read #

    The loss surface of a real network and why the negative gradient is the direction to move.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Gradient descent on a small regression problem, every number written out.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Strang solves gradient descent with exact line search on 12(x2+by2)\tfrac12(x^2 + by^2); the zig-zag factor (1−b)/(1+b)(1-b)/(1+b) is the factor of the best fixed step in section 3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    • Gabriel Goh, Why Momentum Really Works, Distill (2017): the first section, "First Steps: Gradient Descent", has an interactive version of the narrow valley.
    • Stanford CS231n, Optimization: stochastic gradient descent: loss surfaces of linear classifiers and the gradient check.
    • Boyd and Vandenberghe, Convex Optimization, free PDF: §9.2 (descent methods) and §9.3 (gradient descent, with the stopping rule on ∥∇f∥\|\nabla f\|).