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

    Start here: notation and Python · Lesson 7 · First looks at the main tracks

    Rates of change: slope, derivative and the gradient

    Intermediate 65 min 5 interactive figures 5 videos Colab notebook

    Before this lesson: lesson 04 (slope of a line, exe^x and log⁡\log), lesson 06 (vectors, the dot product and cos⁡θ\cos\theta) and lesson 03 (NumPy). Time: about 65 minutes, plus the notebook. This is the hardest lesson of the track; take a break after section 2.


    Why this matters #

    • Training is gradient descent. Every neural network, from a logistic regression to a large language model, is trained by moving the parameters θ\theta against the gradient of the loss: θ←θ−η∇L(θ)\theta \leftarrow \theta - \eta \nabla L(\theta). SGD, momentum and Adam are all variants of this step.
    • Backpropagation computes a gradient. It is the chain rule, applied to millions of parameters at once. PyTorch's loss.backward() fills param.grad with ∂L/∂θj\partial L / \partial \theta_j for every parameter.
    • The learning rate is the most important hyperparameter. Too small and training is slow; too large and the loss explodes. Section 3 shows exactly where the boundary is for the simplest loss.
    • Gradients answer "what if" questions. The gradient of a model output with respect to the input pixels is a saliency map. In physics, the force on an atom is minus the gradient of the energy; ML force fields for molecules are trained on such gradients.

    This lesson is a first look. The Calculus track proves the rules, and the Optimization track studies gradient descent in depth.

    1. Predict first #

    2. The picture #

    From a secant to a tangent #

    The average rate of change of ff between xx and x+hx + h is the change in output divided by the change in input:

    ΔfΔx=f(x+h)−f(x)h.\frac{\Delta f}{\Delta x} = \frac{f(x + h) - f(x)}{h}.

    In the picture it is the slope of the secant line, the straight line through the two points (x,f(x))(x, f(x)) and (x+h,f(x+h))(x + h, f(x + h)) of the graph. For f(x)=x2f(x) = x^2 from x=1x = 1 to x=3x = 3 (h=2h = 2):

    f(3)−f(1)3−1=9−12=4.\frac{f(3) - f(1)}{3 - 1} = \frac{9 - 1}{2} = 4.

    Now let the second point slide toward the first: hh gets smaller. The secant line turns, and it comes closer and closer to one line that just touches the curve at xx: the tangent line. The slope of the tangent line is the derivative f′(x)f'(x).

    Interactive figure: loading…

    Press Shrink h and watch the orange secant turn into the aqua tangent at the blue point. The panel computes the secant slope; its difference to the tangent slope f′(x0)f'(x_0) shrinks with hh. Try a negative hh: the secant now uses a point on the left, and the slopes approach the same value. At h=0h = 0 the quotient is 0/00/0, which is not defined: the derivative is a limit, not a division by zero.

    For x2x^2 at x0=1x_0 = 1 the secant slopes are 2+h2 + h (we show this in section 3): 3.53.5 for h=1.5h = 1.5, 2.12.1 for h=0.1h = 0.1, 2.012.01 for h=0.01h = 0.01. They approach f′(1)=2f'(1) = 2.

    Quick check

    What is the average rate of change of f(x)=x2f(x) = x^2 from x=1x = 1 to x=3x = 3?

    Zoom in: the curve looks like a line #

    Here is a second way to see the derivative. Zoom in on a smooth curve around a point. The more you zoom, the straighter the curve looks. In the end you cannot tell it from its tangent line. So near x0x_0:

    f(x0+h)≈f(x0)+f′(x0) h.f(x_0 + h) \approx f(x_0) + f'(x_0)\, h .

    This is the local linear approximation (or linearization). Example: estimate 4.1\sqrt{4.1}. Take f(x)=xf(x) = \sqrt x, x0=4x_0 = 4, h=0.1h = 0.1. We know f(4)=2f(4) = 2, and the slope of x\sqrt x at 4 is f′(4)=124=14f'(4) = \tfrac{1}{2\sqrt 4} = \tfrac14 (from the rules in section 3). So

    4.1≈2+14⋅0.1=2.025.\sqrt{4.1} \approx 2 + \tfrac14 \cdot 0.1 = 2.025 .

    The true value is 2.02485…2.02485\ldots; the error is 0.000150.00015.

    Interactive figure: loading…

    Move the zoom slider to the right. The window around x0x_0 gets up to 200 times narrower, and the blue curve and the aqua tangent line become one line. The magenta segment is the error of the linear approximation at the edge of the window. On the right, that error is plotted against hh on log–log axes. It follows the dashed line of slope 2: ten times smaller hh gives about 100 times smaller error.

    The error is not just small; it is small compared with hh. For a smooth ff it shrinks like h2h^2. This is the reason why the tangent is the best line through the point: any other slope mm leaves an error of about ∣f′(x0)−m∣ h|f'(x_0) - m|\,h, which is much larger than h2h^2 for small hh.

    Many inputs: slices of a surface #

    A function of two inputs, f(x,y)f(x, y), has a graph that is a surface: the height above the point (x,y)(x, y) is f(x,y)f(x, y). How steep is it? That depends on the direction. Start with the two simplest directions.

    • Hold yy fixed and change only xx. You walk on a slice of the surface. Its slope is the partial derivative ∂f/∂x\partial f / \partial x.
    • Hold xx fixed and change only yy. The slope of this slice is ∂f/∂y\partial f / \partial y.

    For f(x,y)=x2+2y2f(x, y) = x^2 + 2y^2: holding yy fixed, 2y22y^2 is a constant, so ∂f/∂x=2x\partial f/\partial x = 2x. Holding xx fixed, x2x^2 is a constant, so ∂f/∂y=4y\partial f/\partial y = 4y.

    Interactive figure: loading…

    Move the sliders x0x_0 and y0y_0, and drag the figure to rotate it. The orange curve is the slice "hold y=y0y = y_0"; the slope of its dashed tangent is ∂f/∂x\partial f/\partial x. The aqua curve is the slice "hold x=x0x = x_0", with slope ∂f/∂y\partial f/\partial y. The two slopes together form the gradient, the blue arrow on the floor. It lives in the input plane (x,y)(x, y), not on the surface.

    The gradient on a contour map #

    A surface is hard to draw. A contour map shows the same function in 2-D: each contour line (or level set) connects the points with the same value f(x,y)=cf(x, y) = c. The height lines of a hiking map are contour lines.

    The gradient is the vector of the partial derivatives:

    ∇f(x,y)=(∂f∂x, ∂f∂y).\nabla f(x, y) = \left( \frac{\partial f}{\partial x},\ \frac{\partial f}{\partial y} \right).

    It is an arrow in the input plane. On the map, it has three properties that you can test in the next figure:

    1. it points in the direction in which ff grows fastest (steepest ascent);
    2. its length ∥∇f∥\|\nabla f\| is that fastest rate of growth;
    3. it crosses the contour line at a right angle.
    Interactive figure: loading…

    Drag the orange tip of the unit direction uu around the dashed circle. The slope of ff in that direction is Duf=∇f⊤uD_u f = \nabla f^\top u; the chart plots it against the angle of uu. Find the largest value: it is reached when uu points along the blue gradient, and it equals ∥∇f∥\|\nabla f\| (the blue line in the chart). Press u along the contour: the slope is 0, and uu lies on the dashed tangent of the aqua contour line. Drag the black point to test other places.

    The chart is a cosine curve. This is lesson 06 again: ∇f⊤u=∥∇f∥ ∥u∥cos⁡θ\nabla f^\top u = \|\nabla f\|\,\|u\|\cos\theta, and cos⁡θ\cos\theta is largest at θ=0\theta = 0.

    Walking downhill: gradient descent #

    To make ff small, go against the gradient. Gradient descent repeats one step:

    x←x−η ∇f(x),x \leftarrow x - \eta\, \nabla f(x),

    where the learning rate η>0\eta > 0 sets the step size. For f(x)=x2f(x) = x^2 (one input) the gradient is f′(x)=2xf'(x) = 2x, so the step is x←x−2ηx=(1−2η) xx \leftarrow x - 2\eta x = (1 - 2\eta)\,x. Each step multiplies xx by the same factor 1−2η1 - 2\eta. Everything depends on the size of this factor.

    Interactive figure: loading…

    Choose a preset under Try and watch the orange iterates on the blue parabola. The panel shows the factor 1−2η1 - 2\eta. With zig-zag the factor is negative: the point jumps from side to side but still gets closer. At η=1\eta = 1 it is −1-1: the point flips between ±x0\pm x_0 forever. Above 1 it diverges. Switch to 2-D: on the aqua contours of x2+2y2x^2 + 2y^2, the steep yy direction starts to zig-zag first. The chart shows ff at each step on a log scale.

    Quick check

    Gradient descent on f(x)=x2f(x) = x^2 starts at x0=1x_0 = 1 with η=1.5\eta = 1.5. What happens?

    3. Definitions and main results #

    The derivative #

    Definition. The derivative of ff at xx is the limit of the secant slopes:

    f′(x)=lim⁡h→0f(x+h)−f(x)h.f'(x) = \lim_{h \to 0} \frac{f(x + h) - f(x)}{h}.

    If this limit exists (the same value for h→0h \to 0 from both sides), ff is differentiable at xx. Other notations: dfdx\dfrac{df}{dx}, ddxf(x)\dfrac{d}{dx} f(x); physicists write x˙\dot x for a derivative in time. "lim⁡h→0\lim_{h \to 0}" means: the value that the quotient approaches as hh gets closer and closer to 0, without being 0. The function f′f' that maps each xx to f′(x)f'(x) is the derivative function.

    Example: f(x)=x2f(x) = x^2. Every algebra step:

    1. f(x+h)=(x+h)2=x2+2xh+h2f(x + h) = (x + h)^2 = x^2 + 2xh + h^2.
    2. f(x+h)−f(x)=x2+2xh+h2−x2=2xh+h2f(x + h) - f(x) = x^2 + 2xh + h^2 - x^2 = 2xh + h^2.
    3. Divide by hh (allowed, since h≠0h \ne 0): 2xh+h2h=2x+h\dfrac{2xh + h^2}{h} = 2x + h.
    4. Let h→0h \to 0: 2x+h→2x2x + h \to 2x. So f′(x)=2xf'(x) = 2x.

    At x=1x = 1: the secant slope is 2+h2 + h and the derivative is 22, as in the first figure.

    Not every function has a derivative everywhere. f(x)=∣x∣f(x) = |x| at x=0x = 0: the secant slope is ∣h∣/h|h|/h, which is +1+1 for h>0h > 0 and −1-1 for h<0h < 0. The two sides disagree, so there is no limit. The graph has a corner. The ReLU activation max⁡(0,x)\max(0, x) has the same corner at 0; deep-learning libraries use the slope 0 there.

    Local linear approximation #

    Result. If ff is differentiable at xx, then

    f(x+h)=f(x)+f′(x) h+r(h),where r(h)h→0 as h→0.f(x + h) = f(x) + f'(x)\,h + r(h), \qquad \text{where } \frac{r(h)}{h} \to 0 \text{ as } h \to 0 .

    Why. Divide by hh: r(h)h=f(x+h)−f(x)h−f′(x)\dfrac{r(h)}{h} = \dfrac{f(x + h) - f(x)}{h} - f'(x). The first term tends to f′(x)f'(x) by definition, so the difference tends to 0. ■\blacksquare

    For f(x)=x2f(x) = x^2 the remainder is exact and easy: r(h)=(x+h)2−x2−2xh=h2r(h) = (x + h)^2 - x^2 - 2xh = h^2. In general, if ff has a second derivative, r(h)≈12f′′(x) h2r(h) \approx \tfrac12 f''(x)\,h^2; this is the start of the Taylor series (Calculus lesson 3).

    Rules for derivatives #

    These rules follow from the definition (the Calculus track proves them). cc is a constant.

    function derivative example
    cc 00 ddx 7=0\frac{d}{dx}\, 7 = 0
    xnx^n n xn−1n\,x^{n-1} (power rule) ddx x3=3x2\frac{d}{dx}\, x^3 = 3x^2; ddxx=ddxx1/2=12x−1/2\frac{d}{dx}\sqrt x = \frac{d}{dx} x^{1/2} = \tfrac12 x^{-1/2}
    exe^x exe^x the slope of exe^x equals its height
    log⁡x\log x (x>0x > 0) 1/x1/x at x=1x = 1 the slope is 1
    c f(x)c\,f(x) c f′(x)c\,f'(x) ddx 5x2=10x\frac{d}{dx}\, 5x^2 = 10x
    f(x)+g(x)f(x) + g(x) f′(x)+g′(x)f'(x) + g'(x) ddx(x2+3x)=2x+3\frac{d}{dx}(x^2 + 3x) = 2x + 3
    f(g(x))f(g(x)) f′(g(x)) g′(x)f'(g(x))\, g'(x) (chain rule) ddx e−x=e−x⋅(−1)\frac{d}{dx}\, e^{-x} = e^{-x} \cdot (-1)

    Why exe^x is its own derivative (the claim of lesson 04). ex+h−exh=ex⋅eh−1h\dfrac{e^{x+h} - e^x}{h} = e^x \cdot \dfrac{e^h - 1}{h}. The second factor is the secant slope of exe^x at 0, and it tends to 1: (e0.001−1)/0.001=1.0005(e^{0.001} - 1)/0.001 = 1.0005. So the derivative is ex⋅1e^x \cdot 1. That the slope at 0 is exactly 1 is what makes ee special.

    The chain rule says: if gg changes by a factor g′(x)g'(x), and ff changes by a factor f′f' at g(x)g(x), the two factors multiply. Example: the sigmoid σ(z)=(1+e−z)−1\sigma(z) = (1 + e^{-z})^{-1} of lesson 05. Outer function f(u)=u−1f(u) = u^{-1} with f′(u)=−u−2f'(u) = -u^{-2}; inner function u=1+e−zu = 1 + e^{-z} with u′=−e−zu' = -e^{-z}. So

    σ′(z)=−1(1+e−z)2⋅(−e−z)=11+e−z⋅e−z1+e−z=σ(z) (1−σ(z)),\sigma'(z) = -\frac{1}{(1 + e^{-z})^2} \cdot (-e^{-z}) = \frac{1}{1 + e^{-z}} \cdot \frac{e^{-z}}{1 + e^{-z}} = \sigma(z)\,\big(1 - \sigma(z)\big),

    because 1−σ(z)=1+e−z−11+e−z=e−z1+e−z1 - \sigma(z) = \dfrac{1 + e^{-z} - 1}{1 + e^{-z}} = \dfrac{e^{-z}}{1 + e^{-z}}. At z=0z = 0: σ′(0)=12⋅12=14\sigma'(0) = \tfrac12 \cdot \tfrac12 = \tfrac14; at z=2z = 2: 0.8808⋅0.1192=0.10500.8808 \cdot 0.1192 = 0.1050. The notebook checks the formula numerically. In a network, backpropagation applies the chain rule once per layer.

    What the derivative tells you #

    • If f′(x)>0f'(x) > 0, ff is increasing near xx; if f′(x)<0f'(x) < 0, it is decreasing.
    • Theorem. If ff is differentiable and has a minimum or a maximum at an inner point x∗x^* of an interval, then f′(x∗)=0f'(x^*) = 0.
    Proof for a minimum
    1. At a minimum, f(x∗+h)−f(x∗)≥0f(x^* + h) - f(x^*) \ge 0 for all small hh.
    2. For h>0h > 0 the secant slope f(x∗+h)−f(x∗)h\frac{f(x^* + h) - f(x^*)}{h} is ≥0\ge 0 (non-negative divided by positive). So its limit is f′(x∗)≥0f'(x^*) \ge 0.
    3. For h<0h < 0 the same quotient is ≤0\le 0 (non-negative divided by negative). So f′(x∗)≤0f'(x^*) \le 0.
    4. Both together: f′(x∗)=0f'(x^*) = 0. ■\blacksquare

    The converse is false. f(x)=x3f(x) = x^3 has f′(0)=0f'(0) = 0, but 0 is neither a minimum nor a maximum: x3<0x^3 < 0 on the left and >0> 0 on the right. A point with f′(x)=0f'(x) = 0 is a critical point (or stationary point); it may be a minimum, a maximum or neither.

    Example (a log-likelihood, as in lesson 04). Three heads and one tail have the log-likelihood ℓ(p)=3log⁡p+log⁡(1−p)\ell(p) = 3\log p + \log(1 - p) for 0<p<10 < p < 1. By the rules and the chain rule, ℓ′(p)=3p−11−p\ell'(p) = \dfrac{3}{p} - \dfrac{1}{1 - p}. Set it to 0: 3(1−p)=p3(1 - p) = p, so p=3/4p = 3/4, the fraction of heads. Since ℓ′(p)>0\ell'(p) > 0 for p<3/4p < 3/4 and <0< 0 for p>3/4p > 3/4, this is a maximum.

    Quick check

    f′(x∗)=0f'(x^*) = 0 at some point x∗x^*. What can you conclude?

    Numerical derivatives #

    A computer can estimate a derivative without any rules, from two function values:

    forward difference: f(x+h)−f(x)h,central difference: f(x+h)−f(x−h)2h.\text{forward difference: } \frac{f(x + h) - f(x)}{h}, \qquad \text{central difference: } \frac{f(x + h) - f(x - h)}{2h}.

    For f(x)=x2f(x) = x^2 at x=3x = 3 with h=0.1h = 0.1: forward 9.61−90.1=6.1\frac{9.61 - 9}{0.1} = 6.1, central 9.61−8.410.2=6.0\frac{9.61 - 8.41}{0.2} = 6.0. The true value is 6. The truncation error (the error from h>0h > 0) is about 12∣f′′∣ h\tfrac12 |f''|\,h for the forward difference and 16∣f′′′∣ h2\tfrac16 |f'''|\,h^2 for the central difference. So the central difference is much more accurate for the same hh.

    But hh cannot be tiny. A float64 number has about 16 correct significant digits, and floats are not exact (lesson 03). For a very small hh, f(x+h)f(x + h) and f(x)f(x) agree in almost all digits, and the subtraction loses them: this round-off error grows like 10−16/h10^{-16}/h. The total error is U-shaped in hh. For exe^x at x=1x = 1:

    hh forward error central error
    10−210^{-2} 1.4×10−21.4 \times 10^{-2} 4.5×10−54.5 \times 10^{-5}
    10−510^{-5} 1.4×10−51.4 \times 10^{-5} 5.9×10−115.9 \times 10^{-11}
    10−810^{-8} 6.6×10−96.6 \times 10^{-9} 6.6×10−96.6 \times 10^{-9}
    10−1110^{-11} 3.3×10−53.3 \times 10^{-5} 1.0×10−51.0 \times 10^{-5}

    Good default steps: h≈10−8h \approx 10^{-8} for the forward difference and h≈10−5h \approx 10^{-5} for the central difference (for values of xx and ff near 1).

    Where the error terms come from

    If ff has three derivatives, the Taylor expansion gives f(x±h)=f(x)±f′(x)h+12f′′(x)h2±16f′′′(x)h3+…f(x \pm h) = f(x) \pm f'(x)h + \tfrac12 f''(x)h^2 \pm \tfrac16 f'''(x)h^3 + \dots

    • Forward: f(x+h)−f(x)h=f′(x)+12f′′(x) h+…\frac{f(x+h) - f(x)}{h} = f'(x) + \tfrac12 f''(x)\,h + \dots, error of order hh.
    • Central: subtract the two expansions; the even terms cancel: f(x+h)−f(x−h)2h=f′(x)+16f′′′(x) h2+…\frac{f(x+h) - f(x-h)}{2h} = f'(x) + \tfrac16 f'''(x)\,h^2 + \dots, error of order h2h^2.

    Each function value has a relative round-off error of about ε=2.2×10−16\varepsilon = 2.2 \times 10^{-16} (machine epsilon). Dividing by hh turns it into an error of about ε∣f∣/h\varepsilon |f| / h. Balancing 12∣f′′∣h\tfrac12|f''|h against ε∣f∣/h\varepsilon|f|/h gives the best forward step h≈ε≈1.5×10−8h \approx \sqrt{\varepsilon} \approx 1.5 \times 10^{-8}; balancing h2h^2 against ε/h\varepsilon/h gives h≈ε1/3≈6×10−6h \approx \varepsilon^{1/3} \approx 6 \times 10^{-6} for the central difference. Calculus lesson 7 covers this in detail.

    Partial derivatives and the gradient #

    Definition. For f:Rn→Rf : \R^n \to \R, the partial derivative with respect to xjx_j is the derivative in xjx_j while all other inputs are held fixed:

    ∂f∂xj(x)=lim⁡h→0f(x+h ej)−f(x)h,\frac{\partial f}{\partial x_j}(x) = \lim_{h \to 0} \frac{f(x + h\,e_j) - f(x)}{h},

    where eje_j is the unit vector with a 1 in place jj and 0 elsewhere. In practice: treat every other variable as a constant and use the one-variable rules. The gradient is the vector of all partial derivatives:

    ∇f(x)=(∂f∂x1(x),…,∂f∂xn(x))∈Rn.\nabla f(x) = \left( \frac{\partial f}{\partial x_1}(x), \dots, \frac{\partial f}{\partial x_n}(x) \right) \in \R^n .

    It has the same size as the input xx; it lives in the input space. The symbol ∇\nabla is read "nabla" or "del".

    Example. f(x,y)=x2+3yf(x, y) = x^2 + 3y. Holding yy fixed, 3y3y is a constant: ∂f/∂x=2x\partial f/\partial x = 2x. Holding xx fixed, x2x^2 is a constant: ∂f/∂y=3\partial f/\partial y = 3. So ∇f(x,y)=(2x,3)\nabla f(x, y) = (2x, 3) and ∇f(1,2)=(2,3)\nabla f(1, 2) = (2, 3).

    Quick check

    What is the gradient of f(x,y)=x2yf(x, y) = x^2 y at (3,2)(3, 2)?

    The direction of steepest ascent #

    The partial derivatives are slopes along the axes. The slope in any other direction is a combination of them.

    Definition. For a unit vector uu (∥u∥=1\|u\| = 1), the directional derivative of ff at xx in the direction uu is

    Duf(x)=lim⁡t→0f(x+t u)−f(x)t.D_u f(x) = \lim_{t \to 0} \frac{f(x + t\,u) - f(x)}{t}.

    Theorem. If ff is differentiable at xx (for example, if all partial derivatives exist and are continuous near xx), then

    Duf(x)=∇f(x)⊤u=∂f∂x1u1+⋯+∂f∂xnun.D_u f(x) = \nabla f(x)^\top u = \frac{\partial f}{\partial x_1} u_1 + \dots + \frac{\partial f}{\partial x_n} u_n .

    Why this is true. The linear approximation works in many variables too: f(x+Δ)≈f(x)+∇f(x)⊤Δf(x + \Delta) \approx f(x) + \nabla f(x)^\top \Delta. In 2-D, a step Δ=(Δ1,Δ2)\Delta = (\Delta_1, \Delta_2) changes ff by about ∂f∂xΔ1\frac{\partial f}{\partial x}\Delta_1 (the xx-part of the step) plus ∂f∂yΔ2\frac{\partial f}{\partial y}\Delta_2 (the yy-part). Put Δ=t u\Delta = t\,u and divide by tt. (The Calculus track gives the full proof.)

    Theorem (steepest ascent). Let ∇f(x)≠0\nabla f(x) \ne 0. Among all unit vectors uu:

    1. Duf(x)D_u f(x) is largest for u=∇f(x)/∥∇f(x)∥u = \nabla f(x) / \|\nabla f(x)\|, and the largest value is ∥∇f(x)∥\|\nabla f(x)\|;
    2. Duf(x)D_u f(x) is smallest for u=−∇f(x)/∥∇f(x)∥u = -\nabla f(x) / \|\nabla f(x)\| (steepest descent), with value −∥∇f(x)∥-\|\nabla f(x)\|;
    3. Duf(x)=0D_u f(x) = 0 exactly for the uu that are orthogonal to ∇f(x)\nabla f(x).

    Proof. Let θ\theta be the angle between ∇f(x)\nabla f(x) and uu. By the geometric formula of the dot product (lesson 06):

    1. Duf(x)=∇f(x)⊤u=∥∇f(x)∥ ∥u∥cos⁡θ=∥∇f(x)∥cos⁡θD_u f(x) = \nabla f(x)^\top u = \|\nabla f(x)\|\,\|u\|\cos\theta = \|\nabla f(x)\| \cos\theta, since ∥u∥=1\|u\| = 1.
    2. cos⁡θ\cos\theta takes all values from −1-1 to 11. It is 1 only at θ=0\theta = 0 (uu points along ∇f\nabla f), −1-1 only at θ=180°\theta = 180°, and 0 only at θ=90°\theta = 90°.
    3. Multiply by the positive number ∥∇f(x)∥\|\nabla f(x)\|. This gives claims 1, 2 and 3. ■\blacksquare

    The gradient is perpendicular to the contour line. Along the contour line through xx, ff does not change. So for the direction uu of the contour line (its tangent), Duf(x)=0D_u f(x) = 0. By claim 3, uu is orthogonal to ∇f(x)\nabla f(x). (This is a sketch; it needs ∇f(x)≠0\nabla f(x) \ne 0, so that the contour is a smooth curve near xx.)

    Gradient descent and the learning rate #

    Gradient descent starts at 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

    Why a small step decreases ff. By the linear approximation with Δ=−η∇f(x)\Delta = -\eta \nabla f(x):

    f(x−η∇f(x))≈f(x)−η ∇f(x)⊤∇f(x)=f(x)−η ∥∇f(x)∥2.f(x - \eta \nabla f(x)) \approx f(x) - \eta\, \nabla f(x)^\top \nabla f(x) = f(x) - \eta\, \|\nabla f(x)\|^2 .

    If ∇f(x)≠0\nabla f(x) \ne 0, the decrease η∥∇f(x)∥2\eta\|\nabla f(x)\|^2 is positive. The approximation is only good for small steps, so a too large η\eta can increase ff.

    Exact analysis for f(x)=x2f(x) = x^2. The step is xk+1=xk−2ηxk=(1−2η) xkx_{k+1} = x_k - 2\eta x_k = (1 - 2\eta)\,x_k, so

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

    With r=1−2ηr = 1 - 2\eta and x0≠0x_0 \ne 0, for η>0\eta > 0:

    learning rate factor r=1−2ηr = 1 - 2\eta behaviour x20x_{20} from x0=1x_0 = 1
    0<η<0.50 < \eta < 0.5 0<r<10 < r < 1 converges, same sign each step η=0.1\eta = 0.1: 0.820=0.01150.8^{20} = 0.0115
    η=0.5\eta = 0.5 r=0r = 0 exact minimum after one step 00
    0.5<η<10.5 < \eta < 1 −1<r<0-1 < r < 0 converges with a zig-zag η=0.6\eta = 0.6: (−0.2)20=1.0×10−14(-0.2)^{20} = 1.0 \times 10^{-14}
    η=1\eta = 1 r=−1r = -1 flips between x0x_0 and −x0-x_0 11
    η>1\eta > 1 r<−1r < -1 diverges η=1.5\eta = 1.5: (−2)20=1 048 576(-2)^{20} = 1\,048\,576

    So gradient descent on x2x^2 converges exactly when ∣1−2η∣<1|1 - 2\eta| < 1, that is, 0<η<10 < \eta < 1. The bound depends on the curvature: for f(x)=a2x2f(x) = \tfrac{a}{2} x^2 the factor is 1−ηa1 - \eta a, and the condition is η<2/a\eta < 2/a. A steeper bowl needs a smaller learning rate. For x2+2y2x^2 + 2y^2 (the 2-D figure) the factors are 1−2η1 - 2\eta for xx and 1−4η1 - 4\eta for yy; the steep direction yy limits η\eta to below 0.50.5.

    Quick check

    You run gradient descent on f(x,y)=x2+2y2f(x, y) = x^2 + 2y^2 with η=0.4\eta = 0.4. What do you see?

    Answers to section 1. (1) The average speed is 120/2=60120 / 2 = 60 km/h: the slope of the secant over two hours. The speedometer shows the instantaneous speed, the derivative at 2 pm. The car can be faster at some times and slower at others. (2) Height grows most along the gradient of the height function (steepest ascent), at the rate ∥∇f∥\|\nabla f\|. It does not change (to first order) along the contour line, at a right angle to the gradient. (3) With η=0.1\eta = 0.1: xk=0.8kx_k = 0.8^k, so it converges slowly to 0 (0.01150.0115 after 20 steps). With η=1.5\eta = 1.5: xk=(−2)kx_k = (-2)^k, it diverges.

    4. Worked example #

    Take f(x,y)=x2+2y2f(x, y) = x^2 + 2y^2, the bowl of the figures, at the point p=(1,0.5)p = (1, 0.5).

    (a) Value. f(1,0.5)=12+2⋅0.52=1+2⋅0.25=1.5f(1, 0.5) = 1^2 + 2 \cdot 0.5^2 = 1 + 2 \cdot 0.25 = 1.5.

    (b) Partial derivatives. Hold yy fixed: ∂f/∂x=2x=2⋅1=2\partial f/\partial x = 2x = 2 \cdot 1 = 2. Hold xx fixed: ∂f/∂y=2⋅2y=4y=4⋅0.5=2\partial f/\partial y = 2 \cdot 2y = 4y = 4 \cdot 0.5 = 2.

    (c) Gradient and its length.

    ∇f(1,0.5)=(2,2),∥∇f∥=22+22=8=22≈2.828.\nabla f(1, 0.5) = (2, 2), \qquad \|\nabla f\| = \sqrt{2^2 + 2^2} = \sqrt 8 = 2\sqrt 2 \approx 2.828 .

    (d) Slopes in three directions.

    • Along the xx-axis, u=(1,0)u = (1, 0): Duf=2⋅1+2⋅0=2D_u f = 2 \cdot 1 + 2 \cdot 0 = 2. This is ∂f/∂x\partial f/\partial x.
    • Along u=(1,−1)/2u = (1, -1)/\sqrt 2: Duf=(2⋅1+2⋅(−1))/2=0D_u f = (2 \cdot 1 + 2 \cdot (-1))/\sqrt 2 = 0. This direction is orthogonal to ∇f\nabla f, so it is the direction of the contour line through pp.
    • Along the gradient, u=(2,2)/(22)=(1,1)/2u = (2, 2)/(2\sqrt 2) = (1, 1)/\sqrt 2: Duf=(2+2)/2=4/2=22≈2.828D_u f = (2 + 2)/\sqrt 2 = 4/\sqrt 2 = 2\sqrt 2 \approx 2.828. This is ∥∇f∥\|\nabla f\|, the largest possible slope.

    (e) Linear approximation. Estimate f(1.1,0.4)f(1.1, 0.4), a step Δ=(0.1,−0.1)\Delta = (0.1, -0.1):

    f(1.1,0.4)≈f(1,0.5)+∇f⊤Δ=1.5+(2⋅0.1+2⋅(−0.1))=1.5+0=1.5.f(1.1, 0.4) \approx f(1, 0.5) + \nabla f^\top \Delta = 1.5 + (2 \cdot 0.1 + 2 \cdot (-0.1)) = 1.5 + 0 = 1.5 .

    The true value is 1.12+2⋅0.42=1.21+0.32=1.531.1^2 + 2 \cdot 0.4^2 = 1.21 + 0.32 = 1.53. The step goes along the contour line, so the linear term is 0; the change of 0.030.03 comes from the curvature (the h2h^2 part).

    (f) One gradient descent step with η=0.1\eta = 0.1:

    p1=p−η ∇f(p)=(1,0.5)−0.1⋅(2,2)=(1−0.2, 0.5−0.2)=(0.8,0.3),p_1 = p - \eta\,\nabla f(p) = (1, 0.5) - 0.1 \cdot (2, 2) = (1 - 0.2,\ 0.5 - 0.2) = (0.8, 0.3),
    f(0.8,0.3)=0.64+2⋅0.09=0.64+0.18=0.82.f(0.8, 0.3) = 0.64 + 2 \cdot 0.09 = 0.64 + 0.18 = 0.82 .

    The value fell from 1.51.5 to 0.820.82. The linear approximation predicted 1.5−η∥∇f∥2=1.5−0.1⋅8=0.71.5 - \eta\|\nabla f\|^2 = 1.5 - 0.1 \cdot 8 = 0.7. The true value is a little higher: the bowl curves up, and the exact correction here is η2(22+2⋅22)=0.01⋅12=0.12\eta^2 (2^2 + 2 \cdot 2^2) = 0.01 \cdot 12 = 0.12, so 0.7+0.12=0.820.7 + 0.12 = 0.82. ✓

    5. In code #

    NumPy checks the worked example. The numerical gradient uses central differences, one coordinate at a time.

    import numpy as np
    
    f = lambda v: v[0]**2 + 2 * v[1]**2
    grad = lambda v: np.array([2 * v[0], 4 * v[1]])
    
    def num_grad(f, v, h=1e-5):
        e = np.eye(len(v))                       # rows are the unit vectors e_j
        return np.array([(f(v + h * e[j]) - f(v - h * e[j])) / (2 * h) for j in range(len(v))])
    
    p = np.array([1.0, 0.5])
    g = grad(p)
    print(f(p), g, np.linalg.norm(g))            # 1.5 [2. 2.] 2.8284271247461903
    print(num_grad(f, p))                        # [2. 2.]
    
    for u in [np.array([1., 0.]), np.array([1., -1.]) / np.sqrt(2), g / np.linalg.norm(g)]:
        print(g @ u)                             # 2.0, then 0.0, then 2.82842712474619
    
    d = np.array([0.1, -0.1])
    print(f(p) + g @ d, f(p + d))                # 1.5 1.5300000000000002
    
    q = p - 0.1 * g                              # one gradient descent step
    print(q, f(q))                               # [0.8 0.3] 0.8200000000000001
    
    s = lambda x: x**2                           # forward and central difference at 3
    print((s(3.1) - s(3)) / 0.1, (s(3.1) - s(2.9)) / 0.2)   # 6.100000000000012 6.000000000000005
    
    sig = lambda z: 1 / (1 + np.exp(-z))         # sigma' = sigma (1 - sigma) at z = 2
    print(sig(2) * (1 - sig(2)), (sig(2 + 1e-5) - sig(2 - 1e-5)) / 2e-5)   # 0.10499... 0.10499...
    

    The last digits such as ...0012 are round-off (lesson 03). Compare floats with np.isclose.

    6. Where it shows up #

    • Training neural networks. Every optimizer (SGD, momentum, Adam, AdamW) uses ∇L(θ)\nabla L(\theta), the gradient of the loss with respect to all parameters. Stochastic gradient descent estimates it on a small batch of data. See Optimization lesson 1.
    • Backpropagation and automatic differentiation. PyTorch and JAX apply the chain rule through the computation, and get the full gradient for the cost of a few function evaluations. Finite differences would need 2n2n evaluations for nn parameters, which is impossible for n=109n = 10^9.
    • Gradient checking. When you write a new layer by hand, you compare its gradient with central differences on a few random inputs, as in the notebook. A relative error near 10−710^{-7} is fine; 10−210^{-2} means a bug.
    • Learning-rate choice. Loss curves that explode or oscillate are the 2-D figure on a large scale: the learning rate is above the limit 2/a2/a of the steepest direction. Warmup and learning-rate schedules handle this.
    • Saliency and adversarial examples. The gradient of a class score with respect to the input pixels shows which pixels matter. The fast gradient sign method moves each pixel a tiny step along the sign of this gradient and can change the prediction.
    • ML for science. In molecular dynamics the force on each atom is F=−∇EF = -\nabla E, minus the gradient of the potential energy. Neural network potentials learn EE and get the forces by automatic differentiation. Sensitivity analysis of a simulation asks for the partial derivatives of an output with respect to its parameters.

    7. Common mistakes #

    • Dividing by h=0h = 0. The derivative is a limit as h→0h \to 0, not the quotient at h=0h = 0, which is 0/00/0. Simplify first (as in 2x+h2x + h), then let h→0h \to 0.
    • Thinking that f′(x)=0f'(x) = 0 means a minimum. It can be a maximum or neither (x3x^3 at 0). In many dimensions, ∇f=0\nabla f = 0 also happens at saddle points, which are common in neural network losses.
    • Drawing the gradient on the surface. ∇f(x)\nabla f(x) is a vector in the input space, with one entry per input. It points in the direction to move xx, not up the graph.
    • Going along +∇f+\nabla f to minimize. The gradient points uphill. To make a loss smaller, step along −∇f-\nabla f.
    • Choosing a tiny hh for numerical derivatives. h=10−15h = 10^{-15} gives a large round-off error. Use about 10−510^{-5} with central differences.
    • Thinking that a convex bowl is safe with any learning rate. Even on x2x^2, η>1\eta > 1 diverges. The limit is set by the steepest direction, not by the average one.
    • Mixing up partial derivatives. For ∂f/∂x\partial f/\partial x of x2yx^2 y, yy is a constant factor: the answer is 2xy2xy, not 2x2x.

    8. Check yourself #

    1. Compute the secant slope of f(x)=x3f(x) = x^3 between x=1x = 1 and x=2x = 2, and the derivative at x=1x = 1.
      AnswerSecant: (8−1)/(2−1)=7(8 - 1)/(2 - 1) = 7. Derivative: f′(x)=3x2f'(x) = 3x^2, so f′(1)=3f'(1) = 3. The secant slope is larger because the curve gets steeper between 1 and 2.
    2. Use the linear approximation of exe^x at 0 to estimate e0.05e^{0.05}. How large is the error, roughly?
      Answere0.05≈1+0.05=1.05e^{0.05} \approx 1 + 0.05 = 1.05. The error is about 12h2=12⋅0.0025=0.00125\tfrac12 h^2 = \tfrac12 \cdot 0.0025 = 0.00125; the true value is 1.0512711.051271, so the error is 0.001270.00127.
    3. Lesson 04 claimed that x−log⁡x\sqrt x - \log x is smallest at x=4x = 4. Check it with the derivative.
      Answerddx(x1/2−log⁡x)=12x−1x\frac{d}{dx}(x^{1/2} - \log x) = \frac{1}{2\sqrt x} - \frac1x. Set it to 0: 12x=1x\frac{1}{2\sqrt x} = \frac1x, so x=2xx = 2\sqrt x, so x=2\sqrt x = 2 and x=4x = 4. For x<4x < 4 the derivative is negative and for x>4x > 4 positive, so it is a minimum, with value 2−log⁡4≈0.6142 - \log 4 \approx 0.614.
    4. Find the gradient of f(x,y)=3x+xy2f(x, y) = 3x + xy^2 at (1,2)(1, 2). What is the largest slope of ff at that point, and in which direction?
      Answer∂f/∂x=3+y2=7\partial f/\partial x = 3 + y^2 = 7, ∂f/∂y=2xy=4\partial f/\partial y = 2xy = 4. So ∇f(1,2)=(7,4)\nabla f(1, 2) = (7, 4). The largest slope is ∥∇f∥=49+16=65≈8.06\|\nabla f\| = \sqrt{49 + 16} = \sqrt{65} \approx 8.06, in the direction (7,4)/65(7, 4)/\sqrt{65}.
    5. Give a unit direction in which f(x,y)=x2+3yf(x, y) = x^2 + 3y does not change (to first order) at (1,2)(1, 2).
      Answer∇f(1,2)=(2,3)\nabla f(1, 2) = (2, 3). A direction orthogonal to it is (3,−2)(3, -2) (dot product 6−6=06 - 6 = 0). As a unit vector: (3,−2)/13(3, -2)/\sqrt{13}, or the opposite (−3,2)/13(-3, 2)/\sqrt{13}.
    6. Gradient descent on f(x)=5x2f(x) = 5x^2. Which learning rates converge?
      Answerf′(x)=10xf'(x) = 10x, so x←(1−10η)xx \leftarrow (1 - 10\eta)x. Convergence needs ∣1−10η∣<1|1 - 10\eta| < 1, that is, 0<η<0.20 < \eta < 0.2. (With the rule η<2/a\eta < 2/a for a2x2\tfrac a2 x^2: a=10a = 10.)
    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. Define the derivative f′(x)f'(x) as a limit.

    2. What is the local linear approximation of ff near xx?

    3. Estimate 4.1\sqrt{4.1} with a linear approximation.

    4. What are the derivatives of xnx^n, exe^x and log⁡x\log x?

    5. What does the partial derivative ∂f/∂x\partial f / \partial x of f(x,y)f(x, y) measure?

    6. What is the gradient of f:Rn→Rf : \R^n \to \R?

    7. Why is the gradient the direction of steepest ascent, and what is the steepest slope?

    8. How is the gradient related to the contour line through a point?

    9. Write the gradient descent update. For f(x)=x2f(x) = x^2, which learning rates converge?

    10. Why is the central difference better than the forward difference?

    Open the review →

    9. Interview angle #

    • "Why do we step along the negative gradient?" — For a small step Δ\Delta, f(x+Δ)≈f(x)+∇f⊤Δf(x + \Delta) \approx f(x) + \nabla f^\top \Delta. Among steps of a fixed length, ∇f⊤Δ\nabla f^\top \Delta is most negative when Δ\Delta points along −∇f-\nabla f (Cauchy–Schwarz, or cos⁡θ=−1\cos\theta = -1). So −∇f-\nabla f gives the fastest first-order decrease.
    • "What happens if the learning rate is too large?" — The steps overshoot. On f(x)=a2x2f(x) = \frac a2 x^2 the update multiplies xx by 1−ηa1 - \eta a; for η>2/a\eta > 2/a this has size above 1 and the iterates diverge. In practice the loss oscillates or becomes nan.
    • "How do you check that your backward pass is correct?" — Gradient checking: compare the analytic gradient with central differences f(x+hej)−f(x−hej)2h\frac{f(x + he_j) - f(x - he_j)}{2h}, h≈10−5h \approx 10^{-5}, in float64, using the relative error.
    • "Why not train with finite differences?" — They need 2n2n function evaluations per gradient, one pair per parameter, and they are less accurate. Reverse-mode automatic differentiation (backpropagation) gets all nn partial derivatives for a small constant times the cost of one evaluation.
    • "The gradient is zero. Are you at a minimum?" — Not necessarily: it can be a maximum or a saddle point. In high dimensions, saddle points are much more common than poor local minima (Dauphin et al., 2014).

    10. Practice #

    The notebook for this lesson runs in Colab or in your browser. Five exercises, each with a check cell and a folded solution:

    1. Write the forward and central differences, and plot their errors against hh for exe^x at 1 (the U-shaped curves).
    2. Check σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) numerically on 201 points.
    3. Write a numerical gradient for any f:Rn→Rf : \R^n \to \R and compare it with analytic gradients.
    4. Run gradient descent on x2+5y2x^2 + 5y^2, plot the path on the contours, and find the largest stable learning rate.
    5. Show that the error of the linear approximation of exe^x at 0, divided by h2h^2, tends to 1/21/2.

    11. Watch and read #

    Why calculus thinks in tiny changes; a good first view before the formulas.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The derivative as the limit of Δf/Δx\Delta f / \Delta x, as in the secant figure, and the derivative of x2x^2 and x3x^3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The same argument as section 3: the directional derivative is a dot product with the gradient.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Gradient descent on the loss of a real network; the gradient as "which weights matter most".
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Derivatives of a simple function, computed numerically with a small h, then with several inputs (partial derivatives).
    Open on YouTube · the player loads from youtube-nocookie.com when you press play