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

    Calculus for ML · Lesson 3 · Derivatives in one and many variables

    The derivative as a linear map: Jacobians, Hessians and Taylor's theorem

    Intermediate 75 min 5 interactive figures 6 videos Colab notebook

    Before this lesson: lesson 02 (partial derivatives, the gradient, Dvf=∇f⊤vD_vf = \nabla f^\top v). From linear algebra: a matrix as a map (lesson 01), the spectral theorem and the Rayleigh quotient (lesson 06), positive definite matrices (lesson 07). Time: about 75 minutes, plus the notebook.


    Why this matters #

    Almost every algorithm in ML uses a derivative. The gradient tells an optimizer which way to move. The Hessian tells how the gradient changes: it gives curvature, conditioning, saddle points, Newton and Gauss–Newton steps, and the Laplace approximation. The Jacobian is the object that backpropagation multiplies, layer by layer (lesson 04). One tool is behind all of these: Taylor's theorem. Near a point, a smooth function is a constant, plus a linear term, plus a quadratic term, plus an error that you can bound.

    In ML for science the same objects have other names. The Jacobian of a weather model with respect to its initial state is its tangent linear model. The Taylor test is the standard check of the adjoint gradient of a PDE solver.

    1. Predict first #

    2. The picture #

    One dimension first. For f:R→Rf:\R\to\R, the derivative f′(x)f'(x) is the slope of the tangent line (lesson 01):

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

    The error r(h)r(h) goes to zero faster than hh. We write this as r(h)=o(∣h∣)r(h) = o(|h|), read "small-o of hh". If you zoom in on the graph near xx, it looks like a straight line.

    Many dimensions. Now take a map f:Rn→Rmf:\R^n\to\R^m, for example a layer of a network. Zoom in near a point xx. A small input change h∈Rnh \in \R^n gives an output change that is almost a matrix times hh. That matrix is the derivative. It has one row per output and one column per input, so it is m×nm \times n. It is called the Jacobian Df(x)Df(x).

    The figure shows this for maps of the plane. A small square around x0x_0 goes to a curved shape. The linear map Df(x0)Df(x_0) sends the same square to a parallelogram. When the square is small, the two shapes are the same.

    Interactive figure: loading…

    Make the square smaller with the δ slider. The image of the square under ff (solid) and its image under the linear map f(x0)+Df(x0)hf(x_0) + Df(x_0)h (dashed) become the same shape. The right panel is magnified so that the image always fills it. Drag the point x0x_0 and try the other maps. For polar coordinates, move x0x_0 to r=0r = 0: det⁡Df=r\det Df = r becomes 0, and the parallelogram becomes flat.

    Read the readout: the largest relative error ∥r(h)∥/∥h∥\|r(h)\|/\|h\| on the square is roughly proportional to δ\delta. Make δ\delta ten times smaller, and the relative error becomes ten times smaller. This is what "r(h)=o(∥h∥)r(h) = o(\|h\|)" means in practice.

    Scalar functions. When m=1m = 1 (a loss), the linear map is h↦∇f(x)⊤hh \mapsto \nabla f(x)^\top h, a dot product with the gradient ∇f(x)∈Rn\nabla f(x) \in \R^n. Its graph is the tangent plane. The gradient is orthogonal to the level set {f=f(x)}\{f = f(x)\} and points uphill (lesson 2).

    Second order. Zoom out a little. Now the tangent plane is not good enough; the function looks like a quadratic: a bowl, a dome or a saddle. The Hessian ∇2f(x)\nabla^2 f(x), the n×nn \times n matrix of second derivatives, describes this shape. Its eigenvectors are the principal axes of the shape, and its eigenvalues are the curvatures along these axes.

    Interactive figure: loading…

    Switch between the tangent plane and the quadratic model, and move x0x_0. The tangent plane (order 1) and the quadratic model (order 2) touch the surface at x0x_0. The magenta segments show the error at the corners of the patch. Halve the patch size ρ\rho (from 0.6 to 0.3): the largest error falls by about 4 for the plane and by about 8 for the quadratic model. On the bump, find a point where the model is a dome and one where it is a saddle; on the cubic, find a bowl.

    Quick check

    f:R3→R2f:\R^3\to\R^2 is differentiable at xx. What is the shape of the Jacobian Df(x)Df(x), and where does Df(x) vDf(x)\,v live?

    3. Definitions and main results #

    The derivative is a linear map #

    Definition. f:Rn→Rmf:\R^n\to\R^m is differentiable at xx if there is an m×nm\times n matrix Df(x)Df(x) with

    f(x+h)=f(x)+Df(x) h+r(h),∥r(h)∥∥h∥→0 as h→0.f(x+h) = f(x) + Df(x)\,h + r(h), \qquad \frac{\|r(h)\|}{\|h\|} \to 0 \text{ as } h \to 0 .

    Df(x)Df(x) is the Jacobian (the derivative) of ff at xx. In words: the error of the linear model is small even compared with the step ∥h∥\|h\|. We write r(h)=o(∥h∥)r(h) = o(\|h\|).

    The entries are partial derivatives. Take h=tejh = t e_j, where eje_j is the jj-th unit vector, and divide by tt:

    f(x+tej)−f(x)t=Df(x) ej+r(tej)t  ⟶  Df(x) ej(t→0).\frac{f(x + te_j) - f(x)}{t} = Df(x)\,e_j + \frac{r(te_j)}{t} \;\longrightarrow\; Df(x)\,e_j \quad (t \to 0).

    The left side tends to ∂f/∂xj\partial f/\partial x_j (one partial derivative per output). And Df(x)ejDf(x)e_j is column jj of Df(x)Df(x) (linear algebra lesson 1). So column jj of the Jacobian is ∂f/∂xj\partial f/\partial x_j, and

    [Df(x)]ij=∂fi∂xj(x).[Df(x)]_{ij} = \frac{\partial f_i}{\partial x_j}(x).

    This also shows that the matrix is unique: every entry is fixed by a limit. Lesson 2 showed that partial derivatives can exist at a point where ff is not differentiable. The definition above is what "differentiable" means; continuous partial derivatives are enough to have it.

    Object For Shape Entries
    Jacobian Df(x)Df(x) f:Rn→Rmf:\R^n\to\R^m m×nm\times n (outputs × inputs) ∂fi/∂xj\partial f_i/\partial x_j; row ii is ∇fi⊤\nabla f_i^\top
    gradient ∇f(x)\nabla f(x) f:Rn→Rf:\R^n\to\R nn (a column) ∂f/∂xi\partial f/\partial x_i; ∇f=Df⊤\nabla f = Df^\top
    Hessian ∇2f(x)\nabla^2 f(x) f:Rn→Rf:\R^n\to\R n×nn\times n ∂2f/∂xi∂xj\partial^2 f/\partial x_i\partial x_j; it is D(∇f)D(\nabla f)

    Jacobians you will use in every backward pass #

    A linear map. f(x)=Wxf(x) = Wx with W∈Rm×nW \in \R^{m\times n}. Then f(x+h)=Wx+Whf(x+h) = Wx + Wh exactly, so r(h)=0r(h) = 0 and

    Df(x)=Wfor every x.Df(x) = W \quad \text{for every } x.

    An elementwise map. f(x)=(φ(x1),…,φ(xn))f(x) = (\varphi(x_1), \dots, \varphi(x_n)), for example tanh⁡\tanh or the sigmoid applied to each entry. Output ii depends only on input ii, so ∂fi/∂xj=0\partial f_i/\partial x_j = 0 for i≠ji \ne j, and

    Df(x)=diag⁡(φ′(x1),…,φ′(xn)).Df(x) = \operatorname{diag}\big(\varphi'(x_1), \dots, \varphi'(x_n)\big).

    A layer. f(x)=tanh⁡(Wx+b)f(x) = \tanh(Wx + b). Write z=Wx+bz = Wx + b. Output ii is tanh⁡(zi)\tanh(z_i) with zi=∑jWijxj+biz_i = \sum_j W_{ij}x_j + b_i. By the 1-D chain rule, ∂fi/∂xj=(1−tanh⁡2zi) Wij\partial f_i/\partial x_j = (1 - \tanh^2 z_i)\,W_{ij}. In matrix form:

    Df(x)=diag⁡(1−tanh⁡2(z)) W.Df(x) = \operatorname{diag}\big(1 - \tanh^2(z)\big)\, W .

    It is the Jacobian of the activation times the Jacobian of the linear map. Lesson 04 proves that this is always true: the Jacobian of a composition is the product of the Jacobians.

    Polar coordinates. f(r,θ)=(rcos⁡θ, rsin⁡θ)f(r, \theta) = (r\cos\theta,\ r\sin\theta). The columns are the partial derivatives with respect to rr and θ\theta:

    Df(r,θ)=(cos⁡θ−rsin⁡θsin⁡θrcos⁡θ),det⁡Df=rcos⁡2θ+rsin⁡2θ=r.Df(r,\theta) = \begin{pmatrix} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{pmatrix}, \qquad \det Df = r\cos^2\theta + r\sin^2\theta = r .

    A small rectangle dr×dθdr \times d\theta goes to a region of area about r dr dθr\,dr\,d\theta (linear algebra lesson 3: ∣det⁡∣|\det| is the area scale). Lesson 10 uses this for integrals.

    Quick check

    W∈R3×2W \in \R^{3\times 2} and f(x)=tanh⁡(Wx)f(x) = \tanh(Wx) for x∈R2x \in \R^2. What is Df(x)Df(x)?

    The Hessian and when it is symmetric #

    For a scalar ff, the Hessian is the Jacobian of the gradient: ∇2f(x)=D(∇f)(x)\nabla^2 f(x) = D(\nabla f)(x), with entries [∇2f]ij=∂2f/∂xi ∂xj[\nabla^2 f]_{ij} = \partial^2 f/\partial x_i\,\partial x_j. We write f∈Ckf \in C^k when all partial derivatives up to order kk exist and are continuous.

    Theorem (Schwarz, also called Clairaut). If ff is C2C^2 near xx, then ∂2f∂xi∂xj(x)=∂2f∂xj∂xi(x)\dfrac{\partial^2 f}{\partial x_i \partial x_j}(x) = \dfrac{\partial^2 f}{\partial x_j \partial x_i}(x). So ∇2f(x)\nabla^2 f(x) is symmetric.

    Why you care: a symmetric matrix has real eigenvalues and an orthonormal basis of eigenvectors (spectral theorem). Everything below uses this: curvature along eigenvectors, the minimum/maximum/saddle test, the quadratic model.

    Example: a quadratic. f(x)=12x⊤Ax−b⊤xf(x) = \tfrac12 x^\top A x - b^\top x with any square AA. Expand:

    f(x+h)=f(x)+12(x⊤Ah+h⊤Ax)−b⊤h+12h⊤Ah.f(x+h) = f(x) + \tfrac12 (x^\top A h + h^\top A x) - b^\top h + \tfrac12 h^\top A h .

    The linear term is (12(A+A⊤)x−b)⊤h\big(\tfrac12(A + A^\top)x - b\big)^\top h, because x⊤Ah=(A⊤x)⊤hx^\top A h = (A^\top x)^\top h. So

    ∇f(x)=12(A+A⊤) x−b,∇2f=12(A+A⊤).\nabla f(x) = \tfrac12 (A + A^\top)\,x - b, \qquad \nabla^2 f = \tfrac12 (A + A^\top).

    Only the symmetric part of AA matters. "∇(12x⊤Ax)=Ax\nabla(\tfrac12 x^\top Ax) = Ax" is true only when AA is symmetric.

    When the mixed partials differ

    Without continuity of the second derivatives, the order can matter. Take f(x,y)=xy(x2−y2)/(x2+y2)f(x,y) = xy(x^2-y^2)/(x^2+y^2) with f(0,0)=0f(0,0) = 0. Then ∂xf(0,y)=−y\partial_x f(0, y) = -y for all yy, so ∂y∂xf(0,0)=−1\partial_y \partial_x f(0,0) = -1. And ∂yf(x,0)=x\partial_y f(x, 0) = x, so ∂x∂yf(0,0)=+1\partial_x \partial_y f(0,0) = +1. The second partial derivatives exist but are not continuous at 00.

    In ML: smooth losses are C2C^2, and autodiff Hessians are symmetric up to rounding. At the kinks of a ReLU network the Hessian does not exist.

    Taylor's theorem #

    In one dimension. If gg is C2C^2 near 00, then for each tt there is a τ\tau between 00 and tt with

    g(t)=g(0)+g′(0) t+12g′′(τ) t2.g(t) = g(0) + g'(0)\,t + \tfrac12 g''(\tau)\,t^2 .

    So g(t)=g(0)+g′(0)t+12g′′(0)t2+o(t2)g(t) = g(0) + g'(0)t + \tfrac12 g''(0)t^2 + o(t^2). If gg is C3C^3, the error is O(t3)O(t^3): it equals 16g′′′(ξ) t3\tfrac16 g'''(\xi)\,t^3 for some ξ\xi between 00 and tt (the Lagrange form of the remainder). Here O(t3)O(t^3), "big-O", means "at most a constant times ∣t∣3|t|^3 for small tt".

    In nn dimensions: reduce to a line. Fix a point xx and a direction hh, and look at ff along the line through xx in direction hh:

    g(t)=f(x+th).g(t) = f(x + th).
    1. The derivative of gg is a directional derivative of ff: g′(t)=Dhf(x+th)=∇f(x+th)⊤hg'(t) = D_h f(x+th) = \nabla f(x+th)^\top h (lesson 2).
    2. Apply the same rule to each entry of ∇f\nabla f: g′′(t)=h⊤∇2f(x+th) hg''(t) = h^\top \nabla^2 f(x+th)\, h.
    3. At t=0t = 0: g(0)=f(x)g(0) = f(x), g′(0)=∇f(x)⊤hg'(0) = \nabla f(x)^\top h, g′′(0)=h⊤∇2f(x) hg''(0) = h^\top \nabla^2 f(x)\, h.

    Theorem (Taylor, second order). If ff is C2C^2 near xx, then

    f(x+h)=f(x)+∇f(x)⊤h+12h⊤∇2f(x) h+o(∥h∥2).f(x+h) = f(x) + \nabla f(x)^\top h + \tfrac12 h^\top \nabla^2 f(x)\, h + o(\|h\|^2).

    If ff is C3C^3, the error is O(∥h∥3)O(\|h\|^3).

    Proof of the error term
    1. Apply the 1-D result to g(t)=f(x+th)g(t) = f(x+th) at t=1t = 1: there is a τ∈(0,1)\tau \in (0, 1) with f(x+h)=f(x)+∇f(x)⊤h+12h⊤∇2f(x+τh) hf(x+h) = f(x) + \nabla f(x)^\top h + \tfrac12 h^\top \nabla^2 f(x+\tau h)\, h.
    2. Subtract the model with ∇2f(x)\nabla^2 f(x). The error is 12h⊤(∇2f(x+τh)−∇2f(x))h\tfrac12 h^\top \big(\nabla^2 f(x+\tau h) - \nabla^2 f(x)\big) h.
    3. Its size is at most 12∥∇2f(x+τh)−∇2f(x)∥2 ∥h∥2\tfrac12 \|\nabla^2 f(x+\tau h) - \nabla^2 f(x)\|_2\, \|h\|^2.
    4. ∇2f\nabla^2 f is continuous, so the matrix norm tends to 00 as h→0h \to 0. So the error divided by ∥h∥2\|h\|^2 tends to 0: it is o(∥h∥2)o(\|h\|^2). ■\blacksquare

    The three terms have the sizes 11, ∥h∥\|h\| and ∥h∥2\|h\|^2. The Taylor test at the end of this section measures exactly these orders.

    The quadratic model and the Newton step #

    Write g=∇f(x)g = \nabla f(x) and H=∇2f(x)H = \nabla^2 f(x). The quadratic model of ff at xx is

    m(h)=f(x)+g⊤h+12h⊤Hh.m(h) = f(x) + g^\top h + \tfrac12 h^\top H h .

    Minimize the model. Its gradient is ∇m(h)=g+Hh\nabla m(h) = g + Hh (the example above, with A=HA = H symmetric). If H≻0H \succ 0 (positive definite), mm is a strictly convex bowl, and its minimum is where ∇m=0\nabla m = 0:

    hN=−H−1g(compute it by solving Hh=−g; never form H−1).h_N = -H^{-1} g \qquad (\text{compute it by solving } Hh = -g;\ \text{never form } H^{-1}).

    This is the Newton step. On a quadratic ff with H≻0H \succ 0, the model is exact, so one Newton step lands on the minimum.

    Gradient descent is a cruder model. Replace HH by 1ηI\tfrac1\eta I. The minimizer of f(x)+g⊤h+12η∥h∥2f(x) + g^\top h + \tfrac{1}{2\eta}\|h\|^2 is h=−ηgh = -\eta g: the gradient step. It uses the same curvature 1/η1/\eta in every direction. In a stretched bowl this is wrong in most directions, so gradient descent zig-zags.

    When HH is not positive definite. If HH is indefinite, the model is a saddle and has no minimum. Then hNh_N is the saddle point of the model, and it can point uphill. Practical methods add damping (H+λIH + \lambda I with λ>0\lambda > 0) or a line search.

    Interactive figure: loading…

    Press "One step" a few times, then switch to the cubic. On the stretched bowl, the Newton step (dashed arrow) goes straight to the minimum, and gradient descent zig-zags. Change η\eta above 0.1=2/200.1 = 2/20: gradient descent diverges along yy. On the cubic, drag the start point near the saddle at (0,0)(0, 0) (for example to (0.3,−0.3)(0.3, -0.3)): Newton goes to the saddle, not to the minimum. The readout says when HH is indefinite.

    Second-order conditions for a minimum #

    A critical point (stationary point) is a point x∗x^* with ∇f(x∗)=0\nabla f(x^*) = 0.

    Theorem (second-order conditions). Let ff be C2C^2 near x∗x^*, with g=∇f(x∗)g = \nabla f(x^*) and H=∇2f(x∗)H = \nabla^2 f(x^*).

    • (a) Necessary. If x∗x^* is a local minimum, then g=0g = 0 and H⪰0H \succeq 0.
    • (b) Sufficient. If g=0g = 0 and H≻0H \succ 0, then x∗x^* is a strict local minimum.

    Why this is true (intuition). Near x∗x^*, ff is its quadratic model plus a small error. If the gradient were not 0, a small step against it would go down. If some direction had negative curvature, a small step along it would go down. If every direction has positive curvature, the model is a bowl, and the small error cannot cancel a bowl near its bottom.

    Proof.

    1. Taylor: f(x∗+h)=f(x∗)+g⊤h+12h⊤Hh+r(h)f(x^*+h) = f(x^*) + g^\top h + \tfrac12 h^\top H h + r(h) with r(h)/∥h∥2→0r(h)/\|h\|^2 \to 0.
    2. (a), gradient. Suppose g≠0g \ne 0. Take h=−tgh = -tg with t>0t > 0. Then f(x∗+h)=f(x∗)−t∥g∥2+O(t2)f(x^*+h) = f(x^*) - t\|g\|^2 + O(t^2), which is below f(x∗)f(x^*) for small tt. This contradicts the local minimum, so g=0g = 0.
    3. (a), Hessian. Suppose HH has an eigenvalue λ<0\lambda < 0 with unit eigenvector vv. Since g=0g = 0, f(x∗+tv)=f(x∗)+12λt2+o(t2)f(x^*+tv) = f(x^*) + \tfrac12\lambda t^2 + o(t^2), which is <f(x∗)< f(x^*) for small t≠0t \ne 0. Contradiction. So all eigenvalues are ≥0\ge 0: H⪰0H \succeq 0.
    4. (b). Let μ=λmin⁡(H)>0\mu = \lambda_{\min}(H) > 0. By the Rayleigh quotient, h⊤Hh≥μ∥h∥2h^\top H h \ge \mu\|h\|^2 for every hh. Because r(h)/∥h∥2→0r(h)/\|h\|^2 \to 0, there is a δ>0\delta > 0 with ∣r(h)∣≤μ4∥h∥2|r(h)| \le \tfrac{\mu}{4}\|h\|^2 for ∥h∥<δ\|h\| < \delta.
    5. Then for 0<∥h∥<δ0 < \|h\| < \delta: f(x∗+h)−f(x∗)≥μ2∥h∥2−μ4∥h∥2>0f(x^*+h) - f(x^*) \ge \tfrac{\mu}{2}\|h\|^2 - \tfrac{\mu}{4}\|h\|^2 > 0. So x∗x^* is a strict local minimum. ■\blacksquare

    The gap. g=0g = 0 and H⪰0H \succeq 0 is not sufficient. f(x,y)=x2+y3f(x,y) = x^2 + y^3 at 00 has ∇2f=diag⁡(2,0)\nabla^2 f = \operatorname{diag}(2, 0), but f(0,−t)=−t3<0f(0, -t) = -t^3 < 0 for t>0t > 0. Step 3 only rules out negative curvature. Along a direction with zero curvature, the higher-order terms decide.

    Classifying a critical point (∇f(x∗)=0\nabla f(x^*) = 0, f∈C2f \in C^2) from the eigenvalues of HH:

    Eigenvalues of HH Type
    all >0> 0 strict local minimum
    all <0< 0 strict local maximum
    some >0> 0 and some <0< 0 saddle point: ff goes up along one eigenvector and down along another
    all ≥0\ge 0 (or all ≤0\le 0), some =0= 0 degenerate: the test cannot decide

    In 2-D there is a shortcut: det⁡H=λ1λ2\det H = \lambda_1\lambda_2. So det⁡H<0\det H < 0 means a saddle, and det⁡H>0\det H > 0 means a minimum (tr⁡H>0\operatorname{tr} H > 0) or a maximum (tr⁡H<0\operatorname{tr} H < 0).

    Interactive figure: loading…

    Move the eigenvalue sliders through 0. The contours are solid where ff is above f(0)f(0) and dashed where it is below. The arrows are the eigenvectors q1,q2q_1, q_2 of HH. A minimum has only solid contours, a saddle has both kinds. Choose "λ₂ = 0" and then each extra term along q2q_2: the Hessian is the same, but you get a minimum, a saddle, or neither. This is why the test cannot decide.

    Quick check

    At a critical point, H=(1221)H = \begin{pmatrix} 1 & 2 \\ 2 & 1 \end{pmatrix}. What kind of point is it?

    Quick check

    At a critical point, ∇f=0\nabla f = 0 and H=diag⁡(2,0)H = \operatorname{diag}(2, 0). Which statement is true?

    Answers to section 1. (1) No. ∇f(1,1)=(2,20)\nabla f(1,1) = (2, 20), so −∇f=(−2,−20)-\nabla f = (-2, -20) points almost straight down along −y-y. The minimum lies in the direction (−1,−1)(-1,-1). The angle between the two is arccos⁡(22/(4042))≈39.3°\arccos\big(22/(\sqrt{404}\sqrt2)\big) \approx 39.3°. This is why gradient descent zig-zags in stretched bowls. The Newton step is −H−1∇f=−(2/2, 20/20)=(−1,−1)-H^{-1}\nabla f = -(2/2,\ 20/20) = (-1,-1): it lands exactly on the minimum, because a quadratic is its own quadratic model. (2) The test cannot decide (second quiz above).

    The Taylor test: check a gradient with remainder orders #

    You have ff and code for a claimed gradient g~(x)\tilde g(x). You want to know if g~=∇f\tilde g = \nabla f. Pick a random direction dd and steps t=10−1,10−2,…t = 10^{-1}, 10^{-2}, \dots. Compute

    r0(t)=∣f(x+td)−f(x)∣,r1(t)=∣f(x+td)−f(x)−t g~(x)⊤d∣.r_0(t) = |f(x+td) - f(x)|, \qquad r_1(t) = |f(x+td) - f(x) - t\,\tilde g(x)^\top d|.
    • By Taylor, r0(t)=O(t)r_0(t) = O(t): order 1.
    • If g~=∇f\tilde g = \nabla f, then r1(t)=O(t2)r_1(t) = O(t^2): order 2. Each 10× smaller tt makes r1r_1 100× smaller.
    • If g~\tilde g is wrong, then r1(t)≈t ∣(∇f−g~)⊤d∣r_1(t) \approx t\,|(\nabla f - \tilde g)^\top d|: order 1 only.
    • With a claimed Hessian H~\tilde H (or a Hessian-vector product), also subtract 12t2d⊤H~d\tfrac12 t^2 d^\top \tilde H d. The remainder r2(t)r_2(t) has order 3 when both are correct (f∈C3f \in C^3).

    The observed order between two steps is

    p=log⁡(r(tk)/r(tk+1))log⁡(tk/tk+1),p = \frac{\log\big(r(t_k)/r(t_{k+1})\big)}{\log(t_k/t_{k+1})},

    the slope of the line on a log–log plot.

    Interactive figure: loading…

    Switch the gradient to "buggy", then the direction to (1,0)(1, 0). With the correct gradient, r1r_1 has slope 2 and r2r_2 has slope 3. With the buggy gradient, r1r_1 has slope 1. With d=(1,0)d = (1, 0) the bug is invisible, because the error g~−∇f=(0,1)\tilde g - \nabla f = (0, 1) is orthogonal to dd. At small tt all curves stop at the rounding level of ff; switch to float32 to see this floor rise.

    Three rules.

    1. Use float64. In float32 the rounding floor is so high that the slope-2 range is short.
    2. Read the order in the middle range of tt. At very small tt, the rounding error of ff (about ε∣f∣\varepsilon|f|, with ε≈2.2⋅10−16\varepsilon \approx 2.2\cdot10^{-16} in float64) stops the decrease. That region says nothing about the gradient.
    3. Use a random dd, so that a bug is not hidden by (∇f−g~)⊤d=0(\nabla f - \tilde g)^\top d = 0.

    The test needs no tolerance and no "right" step size: the order is 2 or it is not. Lesson 07 covers finite-difference checks and the best step size.

    Quick check

    In a Taylor test, the observed order of r1r_1 is about 1.01.0 for tt from 10−110^{-1} to 10−510^{-5}. What does this tell you?

    4. Worked example #

    f(x,y)=x3+y3−3xy.f(x, y) = x^3 + y^3 - 3xy .

    Derivatives.

    ∇f=(3x2−3y3y2−3x),∇2f=(6x−3−36y).\nabla f = \begin{pmatrix} 3x^2 - 3y \\ 3y^2 - 3x \end{pmatrix}, \qquad \nabla^2 f = \begin{pmatrix} 6x & -3 \\ -3 & 6y \end{pmatrix}.

    The Hessian is symmetric, as Schwarz's theorem says (a polynomial is C∞C^\infty).

    Critical points. ∇f=0\nabla f = 0 gives 3x2=3y3x^2 = 3y and 3y2=3x3y^2 = 3x, so y=x2y = x^2 and x=y2=x4x = y^2 = x^4. Then x(x3−1)=0x(x^3 - 1) = 0. The real solutions are x=0x = 0 and x=1x = 1, with y=x2y = x^2.

    • (0,0)(0,0): H=(0−3−30)H = \begin{pmatrix} 0 & -3 \\ -3 & 0\end{pmatrix}. The eigenvalues are −3-3 (eigenvector (1,1)(1,1)) and +3+3 (eigenvector (1,−1)(1,-1)): a saddle. Check along the eigenvectors: f(t,t)=2t3−3t2<0f(t,t) = 2t^3 - 3t^2 < 0 and f(t,−t)=3t2>0f(t,-t) = 3t^2 > 0 for small t≠0t \ne 0.
    • (1,1)(1,1): H=(6−3−36)H = \begin{pmatrix} 6 & -3 \\ -3 & 6\end{pmatrix}, with eigenvalues 6±3=36 \pm 3 = 3 and 99. Both positive: a strict local minimum, with f(1,1)=1+1−3=−1f(1,1) = 1 + 1 - 3 = -1.

    At the point x0=(2,1)x_0 = (2, 1).

    • f(x0)=8+1−6=3f(x_0) = 8 + 1 - 6 = 3.
    • ∇f(x0)=(3⋅4−3, 3⋅1−6)=(9,−3)\nabla f(x_0) = (3\cdot4 - 3,\ 3\cdot1 - 6) = (9, -3).
    • H0=(12−3−36)H_0 = \begin{pmatrix} 12 & -3 \\ -3 & 6\end{pmatrix}. Trace 1818, determinant 72−9=6372 - 9 = 63. The eigenvalues solve λ2−18λ+63=0\lambda^2 - 18\lambda + 63 = 0: λ=9±18=9±32≈13.24\lambda = 9 \pm \sqrt{18} = 9 \pm 3\sqrt2 \approx 13.24 and 4.764.76. Both positive: H0H_0 is positive definite.
    • Directional derivative along u=(1,1)/2u = (1,1)/\sqrt2: ∇f⊤u=(9−3)/2=32≈4.243\nabla f^\top u = (9 - 3)/\sqrt2 = 3\sqrt2 \approx 4.243.
    • Steepest descent: ∥∇f∥=81+9=310\|\nabla f\| = \sqrt{81 + 9} = 3\sqrt{10}, so the direction is −∇f/∥∇f∥=(−3,1)/10-\nabla f/\|\nabla f\| = (-3, 1)/\sqrt{10}, with rate −310≈−9.487-3\sqrt{10} \approx -9.487.

    Newton step. Solve H0h=−∇f(x0)H_0 h = -\nabla f(x_0):

    12h1−3h2=−9,−3h1+6h2=3.\begin{aligned} 12h_1 - 3h_2 &= -9, \\ -3h_1 + 6h_2 &= 3. \end{aligned}

    Multiply the first line by 2 and add the second: 21h1=−1521 h_1 = -15, so h1=−5/7h_1 = -5/7. Then 6h2=3+3h1=3−15/7=6/76h_2 = 3 + 3h_1 = 3 - 15/7 = 6/7, so h2=1/7h_2 = 1/7. The step is h=(−5/7, 1/7)h = (-5/7,\ 1/7).

    • The new point is x0+h=(9/7, 8/7)≈(1.286, 1.143)x_0 + h = (9/7,\ 8/7) \approx (1.286,\ 1.143).
    • There
    f=729343+512343−3⋅7249=729+512−1512343=−271343≈−0.790.f = \frac{729}{343} + \frac{512}{343} - 3\cdot\frac{72}{49} = \frac{729 + 512 - 1512}{343} = -\frac{271}{343} \approx -0.790 .
    • The model predicted m(h)=3+g⊤h+12h⊤H0hm(h) = 3 + g^\top h + \tfrac12 h^\top H_0 h. At the Newton step H0h=−gH_0 h = -g, so 12h⊤H0h=−12g⊤h\tfrac12 h^\top H_0 h = -\tfrac12 g^\top h, and
    m(h)=3+12g⊤h=3+12(−457−37)=3−247≈−0.429.m(h) = 3 + \tfrac12 g^\top h = 3 + \tfrac12\Big(-\frac{45}{7} - \frac{3}{7}\Big) = 3 - \frac{24}{7} \approx -0.429 .

    One step went from f=3f = 3 to −0.790-0.790, near the minimum value −1-1. The model was too pessimistic here because ff is not quadratic.

    Taylor test at x0x_0 along d=(1,1)d = (1, 1). Expand the cubic exactly:

    f(2+t,1+t)=(2+t)3+(1+t)3−3(2+t)(1+t)=3+6t+6t2+2t3.f(2 + t, 1 + t) = (2+t)^3 + (1+t)^3 - 3(2+t)(1+t) = 3 + 6t + 6t^2 + 2t^3 .

    The coefficients match the theory: f(x0)=3f(x_0) = 3, ∇f⊤d=9−3=6\nabla f^\top d = 9 - 3 = 6, 12d⊤H0d=12(12−3−3+6)=6\tfrac12 d^\top H_0 d = \tfrac12 (12 - 3 - 3 + 6) = 6, and the cubic rest 2t32t^3. Compare the correct gradient with a buggy one, g~=(9,−2)\tilde g = (9, -2), for which g~⊤d=7\tilde g^\top d = 7:

    tt r0r_0 r1r_1, correct gg r1r_1, buggy g~\tilde g r2r_2 (with H0H_0)
    10−110^{-1} 0.6620.662 0.0620.062 0.0380.038 2⋅10−32\cdot10^{-3}
    10−210^{-2} 0.06060.0606 6.02⋅10−46.02\cdot10^{-4} 9.40⋅10−39.40\cdot10^{-3} 2⋅10−62\cdot10^{-6}
    10−310^{-3} 6.01⋅10−36.01\cdot10^{-3} 6.00⋅10−66.00\cdot10^{-6} 9.94⋅10−49.94\cdot10^{-4} 2⋅10−92\cdot10^{-9}
    observed order (last two rows) 1.001.00 2.002.00 0.980.98 3.003.00

    The buggy gradient shows at once: its order is 1, not 2. For it, r1=∣−t+6t2+2t3∣r_1 = |-t + 6t^2 + 2t^3|: the −t-t term is the bug. Here r2=2t3r_2 = 2t^3 exactly, because ff is a cubic.

    5. In code #

    NumPy checks the worked example. The notebook has these cells and the exercises.

    import numpy as np
    np.set_printoptions(precision=3)
    
    def f(z):
        x, y = z
        return x**3 + y**3 - 3*x*y
    
    def grad(z):
        x, y = z
        return np.array([3*x**2 - 3*y, 3*y**2 - 3*x])
    
    def hess(z):
        x, y = z
        return np.array([[6*x, -3.], [-3., 6*y]])
    
    # critical points: classify by the eigenvalues of the Hessian
    for c in ([0., 0.], [1., 1.]):
        print(c, np.linalg.eigvalsh(hess(np.array(c))))  # [-3.  3.] saddle, then [3. 9.] minimum
    
    x0 = np.array([2., 1.])
    g, H = grad(x0), hess(x0)
    print(f(x0), g, np.linalg.eigvalsh(H))      # 3.0 [ 9. -3.] [ 4.757 13.243]
    
    h = np.linalg.solve(H, -g)                  # Newton step: solve, never invert
    print(7 * h, round(f(x0 + h), 4))           # [-5.  1.] -0.7901
    
    # Taylor test along d = (1, 1): observed order of r1 for the true and a buggy gradient
    d = np.array([1., 1.])
    for g_claim in (g, np.array([9., -2.])):
        r1 = [abs(f(x0 + t*d) - f(x0) - t * g_claim @ d) for t in (1e-2, 1e-3)]
        print(round(np.log10(r1[0] / r1[1]), 3))   # 2.001 (correct), then 0.976 (buggy)
    
    # a Jacobian by central differences, checked against the hand formula (polar coordinates)
    def polar(p):
        r, th = p
        return np.array([r*np.cos(th), r*np.sin(th)])
    
    p0, eps = np.array([2., 0.5]), 1e-6
    J_fd = np.column_stack([(polar(p0 + eps*e) - polar(p0 - eps*e)) / (2*eps) for e in np.eye(2)])
    J = np.array([[np.cos(0.5), -2*np.sin(0.5)], [np.sin(0.5), 2*np.cos(0.5)]])
    print(np.abs(J_fd - J).max() < 1e-8, round(np.linalg.det(J), 12))   # True 2.0 (det = r)
    

    Automatic differentiation computes the same gradient and Hessian exactly up to rounding (lesson 05); finite differences, as in the last cell, are only approximations (lesson 07).

    6. Where it shows up #

    • Training and the learning rate. A gradient step minimizes a linear model plus a proximity term. On a quadratic with Hessian H≻0H \succ 0, gradient descent converges only for step sizes η<2/λmax⁡(H)\eta < 2/\lambda_{\max}(H): the top Hessian eigenvalue (the "sharpness") limits the learning rate (see the optimization track).
    • Saddles and flat directions. The Hessians of large networks have many eigenvalues near zero and some negative ones. Degenerate critical points are normal there, so "∇f=0\nabla f = 0 and H⪰0H \succeq 0" does not certify a minimum.
    • Second-order methods. Newton, Gauss–Newton, natural gradient and K-FAC all minimize a quadratic model with some curvature matrix in place of HH. Hessian-vector products give HvHv without forming HH (lesson 08).
    • Backpropagation. Every layer has a Jacobian: WW for a linear map, diag⁡(φ′)\operatorname{diag}(\varphi') for an activation. Backprop multiplies their transposes with a vector (lesson 04, lesson 06).
    • Bayesian deep learning. The Laplace approximation is the second-order Taylor expansion of the log posterior at its mode (lesson 11).
    • ML for science. In 4D-Var data assimilation (weather forecasting), the Jacobian of the forecast model with respect to the initial state is the tangent linear model, and its transpose is the adjoint model. A physics-informed network u(x)u(x) puts derivatives with respect to the input coordinates into the PDE residual, for example the Laplacian Δu=tr⁡∇x2u\Delta u = \operatorname{tr} \nabla^2_x u. Adjoint gradients of PDE solvers are verified with the Taylor test (for example in dolfin-adjoint).

    7. Common mistakes #

    • Row or column? MML's gradient is a row; here it is a column. A Jacobian is always outputs × inputs. Check shapes before you trust a formula.
    • "All partial derivatives exist, so ff is differentiable." False (lesson 2). You need the definition, or continuous partial derivatives.
    • ∇(x⊤Ax)=2Ax\nabla(x^\top A x) = 2Ax for every AA. Only for symmetric AA. In general the gradient is (A+A⊤)x(A + A^\top)x and the Hessian is A+A⊤A + A^\top.
    • Classifying from the entries of HH. (1221)\begin{pmatrix} 1 & 2 \\ 2 & 1\end{pmatrix} has positive entries, but its eigenvalues are 33 and −1-1: a saddle. Use the eigenvalues (in 2-D, det⁡H<0\det H < 0 already means a saddle).
    • Treating H⪰0H \succeq 0 with a zero eigenvalue as a minimum. The test cannot decide.
    • A Newton step with an indefinite HH. It goes to the saddle of the model and can increase ff. Check H≻0H \succ 0, or add damping (H+λIH + \lambda I with λ>0\lambda > 0).
    • Computing H−1H^{-1}. Solve Hh=−gHh = -g instead; it is cheaper and more accurate.
    • Taylor-test traps: float32 (the rounding floor hides order 2), reading the order where rounding dominates, or a direction dd that hides the bug.

    8. Check yourself #

    1. f:R10→R3f:\R^{10}\to\R^3 and ℓ:R10→R\ell:\R^{10}\to\R. Give the shapes of Df(x)Df(x), ∇ℓ(x)\nabla \ell(x) and ∇2ℓ(x)\nabla^2\ell(x). In which spaces do Df(x) vDf(x)\,v and Df(x)⊤uDf(x)^\top u live?
      AnswerDfDf: 3×103\times10; ∇ℓ\nabla\ell: a vector in R10\R^{10}; ∇2ℓ\nabla^2\ell: 10×1010\times10. Df(x) v∈R3Df(x)\,v \in \R^3 (the output space; v∈R10v \in \R^{10}). Df(x)⊤u∈R10Df(x)^\top u \in \R^{10} (the input space; u∈R3u \in \R^3).
    2. Find the Jacobian of f(x,y)=(xy, x+y2, sin⁡x)f(x, y) = (xy,\ x + y^2,\ \sin x) at (0,1)(0, 1).
      AnswerRows are the gradients of the three outputs: (y,x)(y, x), (1,2y)(1, 2y), (cos⁡x,0)(\cos x, 0). At (0,1)(0,1): Df=(101210)Df = \begin{pmatrix} 1 & 0 \\ 1 & 2 \\ 1 & 0 \end{pmatrix}, a 3×23 \times 2 matrix.
    3. For a,b∈Rna, b \in \R^n, find the gradient and the Hessian of f(x)=(a⊤x)(b⊤x)f(x) = (a^\top x)(b^\top x).
      AnswerProduct rule: ∇f=(b⊤x) a+(a⊤x) b\nabla f = (b^\top x)\,a + (a^\top x)\,b and ∇2f=ab⊤+ba⊤\nabla^2 f = ab^\top + ba^\top, which is symmetric, as it must be for a polynomial. A common slip is to write only ab⊤ab^\top, which is not symmetric.
    4. Classify the critical point 00 of f(x,y)=x2+4xy+y2f(x,y) = x^2 + 4xy + y^2 and give a direction in which ff decreases.
      AnswerH=(2442)H = \begin{pmatrix}2&4\\4&2\end{pmatrix} has eigenvalues 66 and −2-2: a saddle. Along the eigenvector (1,−1)(1,-1) of −2-2: f(t,−t)=t2−4t2+t2=−2t2<0f(t,-t) = t^2 - 4t^2 + t^2 = -2t^2 < 0.
    5. For g=∇f(x)≠0g = \nabla f(x) \ne 0, when is the Newton direction −H−1g-H^{-1}g a descent direction?
      AnswerWhen H≻0H \succ 0: then H−1≻0H^{-1} \succ 0, and the directional derivative along it is g⊤(−H−1g)<0g^\top(-H^{-1}g) < 0. For an indefinite HH, g⊤H−1gg^\top H^{-1} g can be negative, and then the Newton direction points uphill.
    6. In a Taylor test, the observed orders of r1r_1 are about 2 for tt from 10−110^{-1} to 10−610^{-6}, then fall to about 0 and become noisy for smaller tt. Is the gradient correct?
      AnswerYes. Order 2 in the middle range means r1=O(t2)r_1 = O(t^2). At small tt the rounding error of ff (about ε∣f∣\varepsilon|f|) is larger than the t2t^2 term, so r1r_1 stops decreasing. That region says nothing about the gradient.
    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 (Jacobian) of f:Rn→Rmf:\R^n\to\R^m at xx.

    2. What are the entries and the shape of the Jacobian Df(x)Df(x) for f:Rn→Rmf:\R^n\to\R^m?

    3. What is the Jacobian of an elementwise map x↦φ(x)x \mapsto \varphi(x)?

    4. Compute det⁡Df\det Df for polar coordinates f(r,θ)=(rcos⁡θ,rsin⁡θ)f(r,\theta) = (r\cos\theta, r\sin\theta).

    5. When is the Hessian symmetric?

    6. Write the second-order Taylor expansion of f:Rn→Rf:\R^n\to\R at xx.

    7. What is the Newton step, and how do you compute it?

    8. State the second-order necessary and sufficient conditions for a local minimum.

    9. At a critical point the Hessian has eigenvalues 44 and −1-1. What kind of point is it?

    10. In the Taylor test, which orders do r1r_1 and r2r_2 have when the gradient and Hessian are correct?

    Open the review →

    9. Interview angle #

    • "Why does the gradient point in the direction of steepest ascent?" — Dvf=∇f⊤vD_v f = \nabla f^\top v, then Cauchy–Schwarz (lesson 2).
    • "What is the Jacobian of a linear layer followed by an activation?" — diag⁡(φ′(z)) W\operatorname{diag}(\varphi'(z))\,W with z=Wx+bz = Wx + b; outputs × inputs.
    • "How do you tell a minimum from a saddle? And for a network with 10810^8 parameters?" — The signs of the Hessian eigenvalues. At scale, estimate the extreme eigenvalues with Hessian-vector products and power iteration or Lanczos (lesson 08).
    • "Derive the Newton step. When does it fail?" — Minimize the quadratic model: g+Hh=0g + Hh = 0. It fails when HH is not positive definite, or when the model is poor far from the minimum.
    • "Is the Hessian always symmetric?" — Yes when ff is C2C^2 (Schwarz). It does not exist at the kinks of a ReLU network.
    • "How do you test a hand-written gradient?" — The Taylor test (order 2), or a finite-difference check in float64 with a relative error (lesson 07).

    10. Practice #

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

    1. jacobian_fd: a finite-difference Jacobian, compared with the hand Jacobians of polar coordinates and of tanh⁡(Wx+b)\tanh(Wx + b).
    2. quadratic_gradient_hessian: gradient and Hessian of 12x⊤Ax−b⊤x\tfrac12 x^\top A x - b^\top x for a non-symmetric AA.
    3. classify_critical_point: minimum, maximum, saddle or degenerate, from the Hessian.
    4. newton_step: Newton's method against gradient descent on the Rosenbrock function.
    5. taylor_orders: the Taylor test; find which of three gradient functions has a planted bug.

    11. Watch and read #

    A map of the plane looks linear when you zoom in; this is the first figure of this lesson.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    How the partial derivatives become the columns of the matrix of the local linear map.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The second-order Taylor expansion written with the gradient and the Hessian, as in section 3.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The 2-D test with det⁡H\det H; this lesson states it with eigenvalues, which works in any dimension.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    The derivative as a linear operator, the view of this lesson, for vectors and matrices.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    • Deisenroth, Faisal, Ong, Mathematics for Machine Learning (free PDF): §5.2 (partial derivatives and gradients), §5.3 (Jacobians), §5.7 (the Hessian), §5.8 (linearization and multivariate Taylor series). Note its row-gradient convention.
    • Bright, Edelman, Johnson, Matrix Calculus (for Machine Learning and Beyond) (arXiv): §2 "Derivatives as linear operators" and §12 "Second derivatives, bilinear maps, and Hessian matrices".
    • Nocedal and Wright, Numerical Optimization, 2nd ed. (Springer, 2006): §2.1 (Taylor's theorem and the second-order conditions) and §3.3–3.4 (Newton's method and Hessian modification).
    • dolfin-adjoint, Verification: the Taylor remainder convergence test in practice.