Course contents 08 / 16

08 / 16 · Calculus

Gradients, Jacobians and Hessians

Derivatives of functions of many variables: the gradient as the direction of steepest ascent across the level sets, the Jacobian and the chain rule as a product of matrices, and the Hessian that tells minima from saddles.

On this page 9

Stand at the point (1,1)(1, 1) of the function

q(x)=x12+x1x2+2x22.q(x) = x_1^2 + x_1x_2 + 2x_2^2 .

Walking along the x1x_1-axis, qq rises at the rate 2x1+x2=32x_1 + x_2 = 3; along the x2x_2-axis, at the rate x1+4x2=5x_1 + 4x_2 = 5. These are the partial derivatives ∂1q\partial_1 q and ∂2q\partial_2 q: the ordinary derivatives of t↦q(x+tei)t \mapsto q(x + te_i) at t=0t = 0, where e1,e2e_1, e_2 are the standard basis vectors. But a loss is minimized by stepping in some direction, and almost never along an axis. How fast does qq change along (0.6,0.8)(0.6, 0.8)? Which direction is steepest?

A loss in machine learning is a function of a whole vector of weights, and a layer of a network maps a vector to a vector. The previous note approximated a function of one variable by its tangent line; the same idea, with vectors and matrices in place of numbers, answers these questions.

The gradient: the best linear approximation#

Partial derivatives alone do not describe a function near a point. The function g(x1,x2)=x1x2/(x12+x22)g(x_1, x_2) = x_1x_2/(x_1^2 + x_2^2), extended by g(0)=0g(0) = 0, vanishes on both axes, so both of its partial derivatives at the origin are 0. Yet on the diagonal x1=x2≠0x_1 = x_2 \ne 0 it equals 12\tfrac12: gg is not even continuous at the origin, and no plane approximates it there.

The definition that works is the one of the previous note, with the increment hh now a vector. A function f:Rn→Rf: \mathbb R^n \to \mathbb R is differentiable at xx when, near xx, it equals a linear function of hh plus an error small compared with the length ∥h∥\lVert h\rVert. A linear function ℓ\ell of hh is an inner product ⟨a,h⟩=a⊤h\langle a, h\rangle = a^\top h with a fixed vector aa: by linearity ℓ(h)=∑ihi ℓ(ei)\ell(h) = \sum_i h_i\,\ell(e_i), so ai=ℓ(ei)a_i = \ell(e_i). That vector is the gradient ∇f(x)\nabla f(x):

f(x+h)=f(x)+⟨∇f(x),h⟩+r(h),r(h)∥h∥→0as h→0.\begin{aligned} f(x + h) &= f(x) + \langle \nabla f(x), h\rangle + r(h), \\ \frac{r(h)}{\lVert h\rVert} &\to 0 \quad \text{as } h \to 0 . \end{aligned}

We write r(h)=o(∥h∥)r(h) = o(\lVert h\rVert). Taking h=teih = te_i shows that the ii-th entry of ∇f(x)\nabla f(x) is ∂if(x)\partial_i f(x), so the gradient is the column of partial derivatives, ∇f=(∂1f,…,∂nf)\nabla f = (\partial_1 f, \dots, \partial_n f). For the quadratic qq, ∇q(1,1)=(3,5)\nabla q(1, 1) = (3, 5).

Differentiability asks for more than the existence of the partial derivatives, as gg shows. A convenient sufficient condition is that all partial derivatives exist near xx and are continuous at xx. Every polynomial in this note, and every smooth loss, meets it.

Proof: continuous partial derivatives give differentiability

Change one coordinate at a time. With h(i)=(h1,…,hi,0,…,0)h^{(i)} = (h_1, \dots, h_i, 0, \dots, 0) and h(0)=0h^{(0)} = 0, the one-variable mean value theorem gives, for some θi∈(0,1)\theta_i \in (0, 1),

f(x+h)−f(x)=∑i(f(x+h(i))−f(x+h(i−1)))=∑i∂if(x+h(i−1)+θihiei) hi.\begin{aligned} f(x + h) - f(x) &= \textstyle\sum_i \big(f(x + h^{(i)}) - f(x + h^{(i-1)})\big) \\ &= \textstyle\sum_i \partial_if(x + h^{(i-1)} + \theta_ih_ie_i)\,h_i . \end{aligned}

Each evaluation point is within ∥h∥\lVert h\rVert of xx, so by continuity at xx each ∂if\partial_if there differs from ∂if(x)\partial_if(x) by at most any ϵ>0\epsilon > 0 once hh is small. The error against ⟨∇f(x),h⟩\langle\nabla f(x), h\rangle is then at most ϵ∑i∣hi∣≤ϵn ∥h∥\epsilon\sum_i\lvert h_i\rvert \le \epsilon\sqrt n\,\lVert h\rVert, which is o(∥h∥)o(\lVert h\rVert).

Directional derivatives#

The directional derivative along a unit vector uu is the rate of change of ff when walking from xx along uu, Duf(x)=lim⁡t→0(f(x+tu)−f(x))/tD_uf(x) = \lim_{t \to 0}\big(f(x + tu) - f(x)\big)/t. Put h=tuh = tu into the definition of differentiability and divide by tt:

f(x+tu)−f(x)t=⟨∇f(x),u⟩+r(tu)t→⟨∇f(x),u⟩.\begin{aligned} \frac{f(x + tu) - f(x)}{t} &= \langle \nabla f(x), u\rangle + \frac{r(tu)}{t} \\ &\to \langle \nabla f(x), u\rangle . \end{aligned}

The remainder term vanishes because ∣r(tu)/t∣=∣r(tu)∣/∥tu∥\lvert r(tu)/t\rvert = \lvert r(tu)\rvert/\lVert tu\rVert for a unit uu. So

Duf(x)=⟨∇f(x),u⟩.D_uf(x) = \langle \nabla f(x), u\rangle .

Example. For qq at (1,1)(1, 1) and u=(0.6,0.8)u = (0.6, 0.8), Duq=3⋅0.6+5⋅0.8=5.8D_uq = 3 \cdot 0.6 + 5 \cdot 0.8 = 5.8. A central difference with t=10−3t = 10^{-3}, (q(x+tu)−q(x−tu))/(2t)\big(q(x + tu) - q(x - tu)\big)/(2t), gives 5.85.8 to twelve digits. For a quadratic the central difference is exact up to rounding: t↦q(x+tu)t \mapsto q(x + tu) is a quadratic in tt, its third derivative is 0, and so is the error term 16f′′′(ξ)h2\tfrac16 f'''(\xi)h^2 of the central difference.

The gradient points uphill, across the level sets#

Two geometric facts make the gradient the central object of optimization, and both come from the formula Duf=⟨∇f,u⟩D_uf = \langle \nabla f, u\rangle: an inner product with a fixed vector is largest along that vector and zero across it.

Steepest ascent. Assume ∇f(x)≠0\nabla f(x) \ne 0. For every unit vector uu, by Cauchy–Schwarz,

Duf(x)=⟨∇f(x),u⟩≤∥∇f(x)∥ ∥u∥=∥∇f(x)∥.\begin{aligned} D_uf(x) &= \langle \nabla f(x), u\rangle \\ &\le \lVert \nabla f(x)\rVert\, \lVert u\rVert = \lVert \nabla f(x)\rVert . \end{aligned}

Equality in Cauchy–Schwarz needs u=t ∇f(x)u = t\,\nabla f(x); then ⟨∇f,u⟩=t∥∇f∥2\langle\nabla f, u\rangle = t\lVert\nabla f\rVert^2 equals +∥∇f∥+\lVert\nabla f\rVert only for t>0t > 0, which for a unit vector means u=∇f/∥∇f∥u = \nabla f/\lVert \nabla f\rVert. So the gradient points in the direction of steepest ascent, and its length is the rate of ascent. The same argument with −u-u shows that the steepest descent is along −∇f-\nabla f, at rate −∥∇f∥-\lVert \nabla f\rVert: the step direction of gradient descent.

Perpendicular to the level sets. A level set of ff is {x:f(x)=c}\{x : f(x) = c\}, a contour line in two dimensions. Let γ(t)\gamma(t) be a differentiable curve that stays in the level set, with γ(0)=x\gamma(0) = x and velocity γ′(0)=v\gamma'(0) = v, a tangent vector of the level set at xx. Since ff is constant along the curve,

0=f(γ(t))−f(x)t=⟨∇f(x),γ(t)−xt⟩+r(γ(t)−x)t→⟨∇f(x),v⟩.\begin{aligned} 0 &= \frac{f(\gamma(t)) - f(x)}{t} \\ &= \Big\langle \nabla f(x), \frac{\gamma(t) - x}{t}\Big\rangle + \frac{r(\gamma(t) - x)}{t} \\ &\to \langle \nabla f(x), v\rangle . \end{aligned}

The second line is differentiability with h=γ(t)−xh = \gamma(t) - x. In the limit the difference quotient of γ\gamma tends to vv, and the remainder term tends to 0, because ∥γ(t)−x∥/∣t∣\lVert \gamma(t) - x\rVert/\lvert t\rvert stays bounded while r(h)/∥h∥→0r(h)/\lVert h\rVert \to 0. So the gradient is orthogonal to every tangent direction of the level set.

Example. The level set q=4q = 4 passes through (1,1)(1, 1). The gradient there is (3,5)(3, 5), with length 34=5.831\sqrt{34} = 5.831, the largest rate of increase in any direction; the direction (0.6,0.8)(0.6, 0.8) of the previous example, close to the gradient’s direction (0.514,0.857)(0.514, 0.857), gave a little less, 5.85.8. The tangent direction (5,−3)/34(5, -3)/\sqrt{34} gives D=(15−15)/34=0D = (15 - 15)/\sqrt{34} = 0: to first order qq does not change along the contour.

Figure

Level sets and gradients

Elliptical level sets with gradients perpendicular to themFour nested tilted ellipses around the origin. On the third ellipse arrows point outward at right angles to the curve; at (1, 1) a red gradient arrow and a dashed tangent are highlighted.q = 1q = 2q = 4q = 7minimum∇q(1, 1) = (3, 5)tangent: D = 0Arrows: gradients on the line q = 4,each perpendicular to it.Dotted: the direction to the minimum.Elliptical level sets with gradients perpendicular to themFour nested tilted ellipses around the origin. On the third ellipse arrows point outward at right angles to the curve; at (1, 1) a red gradient arrow and a dashed tangent are highlighted.q = 1q = 2q = 4q = 7minimum∇qD = 0Arrows: gradients on the line q = 4,each perpendicular to it.Dotted: the direction to the minimum.
Level sets of q(x) = x₁² + x₁x₂ + 2x₂² for q = 1, 2, 4, 7. Grey arrows: gradients at points of the level q = 4, each perpendicular to the curve and pointing uphill. At (1, 1) the gradient is (3, 5); the descent direction −∇q misses the minimum at the origin by 14°.

The figure also shows why plain gradient descent can be slow. The descent direction at (1,1)(1, 1) points across the elongated ellipse and misses the minimum at the origin: −(3,5)-(3, 5) is 14°14° away from −(1,1)-(1, 1). The more elongated the level sets, the larger that angle can be; the gradient descent note shows how the eigenvalues of the Hessian govern the resulting zigzag.

The Jacobian of a vector function#

A vector function f:Rn→Rmf: \mathbb R^n \to \mathbb R^m, with components f1,…,fmf_1, \dots, f_m, is differentiable at xx when it is approximated by a linear map, now an m×nm \times n matrix Jf(x)J_f(x):

f(x+h)=f(x)+Jf(x) h+o(∥h∥),(Jf(x))ij=∂fi∂xj(x).\begin{aligned} f(x + h) &= f(x) + J_f(x)\, h + o(\lVert h\rVert), \\ \big(J_f(x)\big)_{ij} &= \frac{\partial f_i}{\partial x_j}(x) . \end{aligned}

Row ii of the Jacobian is ∇fi⊤\nabla f_i^\top, the gradient of the ii-th output; column jj says how all outputs respond to the jj-th input. The shape is outputs × inputs, as for the matrix of any linear map in the linear maps note. For a scalar function the Jacobian is the 1×n1 \times n row ∇f⊤\nabla f^\top.

Two Jacobians make up a neural network. A linear layer z=Wh+bz = Wh + b has Jacobian WW with respect to hh, and an elementwise activation φ\varphi has the diagonal Jacobian diag⁡(φ′(z))\operatorname{diag}\big(\varphi'(z)\big).

Example. The map F(x1,x2)=(x12−x22, 2x1x2)F(x_1, x_2) = (x_1^2 - x_2^2,\ 2x_1x_2), the squaring of the complex number x1+ix2x_1 + ix_2, has

JF(x)=(2x1−2x22x22x1),JF(1,0.5)=(2−112).\begin{aligned} J_F(x) &= \begin{pmatrix} 2x_1 & -2x_2 \\ 2x_2 & 2x_1 \end{pmatrix}, \\ J_F(1, 0.5) &= \begin{pmatrix} 2 & -1 \\ 1 & 2 \end{pmatrix} . \end{aligned}

The second matrix is 5\sqrt5 times a rotation by arctan⁡(1/2)=26.6°\arctan(1/2) = 26.6°, with determinant 5. Near (1,0.5)(1, 0.5), FF therefore turns a small square by 26.6°26.6°, stretches it by 5=2.236\sqrt5 = 2.236 and multiplies its area by 5, the factor of the determinant as volume.

For the square of side 0.20.2 centred at (1,0.5)(1, 0.5) the exact area of the curved image is 0.20110.2011, against 5⋅0.04=0.25 \cdot 0.04 = 0.2 for the linear map. The exact area is the integral of ∣det⁡JF∣=4(x12+x22)\lvert\det J_F\rvert = 4(x_1^2 + x_2^2) over the square, by the change of variables for the map FF, one-to-one there. For side 0.10.1 the ratio of areas is 5.0075.007. It is the average of the continuous ∣det⁡JF∣\lvert\det J_F\rvert over the square, so it tends to ∣det⁡JF(1,0.5)∣=5\lvert\det J_F(1, 0.5)\rvert = 5 as the square shrinks. This local area factor is the ∣det⁡J∣\lvert\det J\rvert of the change of variables in the multiple integrals note.

Figure

The Jacobian as the local linear map

A small square and its image under a nonlinear map and under the JacobianLeft, a square with a 4 by 4 grid. Right, its image: a slightly curved rotated square that nearly coincides with the dashed rotated square of the linear approximation.Fsquare of side 0.2 at (1, 0.5)area 0.04image: area 0.2011J·square: 5 · 0.04 = 0.2A small square and its image under a nonlinear map and under the JacobianLeft, a square with a 4 by 4 grid. Right, its image: a slightly curved rotated square that nearly coincides with the dashed rotated square of the linear approximation.Farea 0.04area 0.2011dashed: J
The map F(x) = (x₁² − x₂², 2x₁x₂) takes a square of side 0.2 centred at (1, 0.5) (left) to a curved quadrilateral (right, solid). Dashed: its image under the Jacobian J = [[2, −1], [1, 2]], rotated by 26.6° and stretched by √5. The areas are 0.2011 and |det J| · 0.04 = 0.2.

The chain rule: a product of Jacobians#

Composing two maps composes their linear approximations, and the composition of linear maps is the product of their matrices. For f:Rn→Rmf: \mathbb R^n \to \mathbb R^m differentiable at xx and g:Rm→Rpg: \mathbb R^m \to \mathbb R^p differentiable at y=f(x)y = f(x):

Jg∘f(x)=Jg(f(x)) Jf(x),(p×n)=(p×m)(m×n).\begin{aligned} J_{g \circ f}(x) &= J_g\big(f(x)\big)\, J_f(x), \\ (p \times n) &= (p \times m)(m \times n) . \end{aligned}

To prove it, let k=f(x+h)−f(x)=Jfh+rf(h)k = f(x + h) - f(x) = J_fh + r_f(h) be the step that hh causes in the input of gg, with both Jacobians at their points. Differentiability of gg at yy, then the substitution of kk, give

g(f(x+h))−g(f(x))=Jgk+rg(k)=JgJfh+Jgrf(h)+rg(k).\begin{aligned} g(f(x + h)) - g(f(x)) &= J_gk + r_g(k) \\ &= J_gJ_fh + J_gr_f(h) + r_g(k) . \end{aligned}

The first term is linear in hh, and the other two are o(∥h∥)o(\lVert h\rVert). The second is at most ∥Jg∥ ∥rf(h)∥\lVert J_g\rVert\, \lVert r_f(h)\rVert, where ∥Jg∥\lVert J_g\rVert is the largest stretch of the matrix, its spectral norm. For the third, ∥k∥≤∥Jf∥ ∥h∥+∥rf(h)∥\lVert k\rVert \le \lVert J_f\rVert\, \lVert h\rVert + \lVert r_f(h)\rVert, so ∥k∥/∥h∥\lVert k\rVert/\lVert h\rVert stays bounded and k→0k \to 0, while rg(k)/∥k∥→0r_g(k)/\lVert k\rVert \to 0 (the term is 0 when k=0k = 0). The linear part of the composition is therefore JgJfJ_gJ_f.

When the last function is a scalar loss ℓ:Rm→R\ell: \mathbb R^m \to \mathbb R, its Jacobian is the row ∇ℓ⊤\nabla\ell^\top, and transposing the chain rule gives

∇(ℓ∘f)(x)=Jf(x)⊤ ∇ℓ(f(x)).\nabla(\ell \circ f)(x) = J_f(x)^\top\, \nabla\ell\big(f(x)\big) .

For a network, a chain of layers, the gradient of the loss is the gradient at the output multiplied by the transposed Jacobians of the layers, from the last to the first. Multiplying in that order keeps every intermediate result a vector and never forms a Jacobian as a matrix; this is reverse-mode differentiation. The backpropagation note writes it out for linear layers and activations, with shapes, and explains why it costs about one forward pass; autograd in PyTorch records the chain as a graph and runs it automatically.

Example. Take FF from the previous section and ℓ(v)=v1+v22\ell(v) = v_1 + v_2^2. At x=(1,0.5)x = (1, 0.5), v=F(x)=(0.75,1)v = F(x) = (0.75, 1) and ∇ℓ(v)=(1,2v2)=(1,2)\nabla\ell(v) = (1, 2v_2) = (1, 2), so

∇(ℓ∘F)(1,0.5)=(21−12)(12)=(43).\nabla(\ell \circ F)(1, 0.5) = \begin{pmatrix} 2 & 1 \\ -1 & 2 \end{pmatrix}\begin{pmatrix} 1 \\ 2 \end{pmatrix} = \begin{pmatrix} 4 \\ 3 \end{pmatrix} .

The direct route agrees. The composition is x12−x22+4x12x22x_1^2 - x_2^2 + 4x_1^2x_2^2, with partial derivatives 2x1+8x1x22=42x_1 + 8x_1x_2^2 = 4 and −2x2+8x12x2=3-2x_2 + 8x_1^2x_2 = 3.

The Hessian and the second-order Taylor expansion#

The Hessian ∇2f(x)\nabla^2 f(x) collects the second partial derivatives, (∇2f)ij=∂2f/∂xi∂xj\big(\nabla^2 f\big)_{ij} = \partial^2 f/\partial x_i\partial x_j; it is the Jacobian of the gradient. When the second partial derivatives are continuous, the order of differentiation does not matter (Schwarz’s theorem), and the Hessian is symmetric. Continuity is needed. For f=x1x2(x12−x22)/(x12+x22)f = x_1x_2(x_1^2 - x_2^2)/(x_1^2 + x_2^2), extended by 0 at the origin, ∂1f(0,x2)=lim⁡hf(h,x2)/h=−x2\partial_1 f(0, x_2) = \lim_h f(h, x_2)/h = -x_2 and ∂2f(x1,0)=x1\partial_2 f(x_1, 0) = x_1, so the two mixed partial derivatives at the origin are −1-1 and 11 (Merkulov, 2024, lecture 2).

Proof: Schwarz’s theorem

Fix all coordinates but xi=ax_i = a and xj=bx_j = b, write f(a,b)f(a, b), and take the double difference

Δ(t)=f(a+t,b+t)−f(a+t,b)−f(a,b+t)+f(a,b).\Delta(t) = f(a + t, b + t) - f(a + t, b) - f(a, b + t) + f(a, b) .

With φ(s)=f(s,b+t)−f(s,b)\varphi(s) = f(s, b + t) - f(s, b), Δ=φ(a+t)−φ(a)\Delta = \varphi(a + t) - \varphi(a). The mean value theorem in ss, then in the second argument, gives Δ=t(∂1f(ξ,b+t)−∂1f(ξ,b))=t2 ∂2∂1f(ξ,η)\Delta = t\big(\partial_1f(\xi, b + t) - \partial_1f(\xi, b)\big) = t^2\,\partial_2\partial_1f(\xi, \eta), with (ξ,η)(\xi, \eta) within tt of (a,b)(a, b) in each coordinate. Grouping the four terms the other way, with ψ(s)=f(a+t,s)−f(a,s)\psi(s) = f(a + t, s) - f(a, s), gives Δ=t2 ∂1∂2f(ξ′,η′)\Delta = t^2\,\partial_1\partial_2f(\xi', \eta'). Dividing by t2t^2 and letting t→0t \to 0, continuity of both mixed derivatives makes them equal at (a,b)(a, b).

For ff with continuous second derivatives, the expansion adds a quadratic form to the linear approximation:

f(x+h)=f(x)+⟨∇f(x),h⟩+12 h⊤∇2f(x) h+o(∥h∥2).\begin{aligned} f(x + h) = f(x) &+ \langle \nabla f(x), h\rangle \\ &+ \tfrac12\, h^\top \nabla^2 f(x)\, h + o\big(\lVert h\rVert^2\big) . \end{aligned}

To see why, restrict ff to the segment from xx to x+hx + h, ϕ(t)=f(x+th)\phi(t) = f(x + th), and use the one-variable theorem. The chain rule gives ϕ′(t)=∑i∂if(x+th) hi\phi'(t) = \sum_i \partial_i f(x + th)\, h_i, and applied once more to each ∂if\partial_i f,

ϕ′′(t)=h⊤∇2f(x+th) h.\phi''(t) = h^\top \nabla^2 f(x + th)\, h .

Taylor with n=1n = 1 gives ϕ(1)=ϕ(0)+ϕ′(0)+12ϕ′′(τ)\phi(1) = \phi(0) + \phi'(0) + \tfrac12\phi''(\tau) for some τ∈(0,1)\tau \in (0, 1), that is,

f(x+h)=f(x)+⟨∇f(x),h⟩+12 h⊤∇2f(x+τh) h.\begin{aligned} f(x + h) = f(x) &+ \langle \nabla f(x), h\rangle \\ &+ \tfrac12\, h^\top \nabla^2 f(x + \tau h)\, h . \end{aligned}

Replacing the Hessian at x+τhx + \tau h by the one at xx changes the last term by at most 12∥∇2f(x+τh)−∇2f(x)∥ ∥h∥2\tfrac12 \lVert \nabla^2 f(x + \tau h) - \nabla^2 f(x)\rVert\, \lVert h\rVert^2, and the norm of the difference tends to 0 with hh because ∇2f\nabla^2 f is continuous. That error is o(∥h∥2)o(\lVert h\rVert^2).

A quadratic f(x)=12x⊤Ax+b⊤xf(x) = \tfrac12 x^\top Ax + b^\top x with symmetric AA has ∇f=Ax+b\nabla f = Ax + b and the constant Hessian AA, and its expansion is exact. Multiplying out, with x⊤Ah=h⊤Axx^\top Ah = h^\top Ax because a number equals its transpose and A=A⊤A = A^\top:

f(x+h)=12x⊤Ax+x⊤Ah+12h⊤Ah+b⊤x+b⊤h=f(x)+(Ax+b)⊤h+12h⊤Ah.\begin{aligned} f(x + h) &= \tfrac12x^\top Ax + x^\top Ah + \tfrac12h^\top Ah + b^\top x + b^\top h \\ &= f(x) + (Ax + b)^\top h + \tfrac12h^\top Ah . \end{aligned}

The Hessians of the two standard losses are of this kind or close to it: 2X⊤X2X^\top X for least squares and X⊤SXX^\top SX for logistic regression; the matrix calculus note derives both.

Example. The cubic c(x)=x13−3x1+x22c(x) = x_1^3 - 3x_1 + x_2^2 has

∇c(x)=(3x12−32x2),∇2c(x)=(6x1002).\begin{aligned} \nabla c(x) &= \begin{pmatrix} 3x_1^2 - 3 \\ 2x_2 \end{pmatrix}, \\ \nabla^2 c(x) &= \begin{pmatrix} 6x_1 & 0 \\ 0 & 2 \end{pmatrix} . \end{aligned}

At x=(1.2,0.5)x = (1.2, 0.5), take the step h=(0.1,−0.2)h = (0.1, -0.2):

quantityvalue
c(x)c(x)−1.622-1.622
∇c(x)\nabla c(x) and ∇2c(x)\nabla^2 c(x)(1.32,1)(1.32, 1) and diag⁡(7.2,2)\operatorname{diag}(7.2, 2)
linear approximation c(x)+⟨∇c,h⟩c(x) + \langle \nabla c, h\rangle−1.690-1.690
quadratic term 12h⊤∇2c h\tfrac12 h^\top \nabla^2 c\, h0.0760.076
second-order approximation−1.614-1.614
exact c(1.3,0.3)c(1.3, 0.3)−1.613-1.613

The linear approximation is off by 0.0770.077, the quadratic one by 0.0010.001, which is h13h_1^3: expanding (x1+h1)3(x_1 + h_1)^3 leaves exactly that term beyond the second order.

Classifying critical points by the Hessian’s eigenvalues#

At a critical point x∗x^*, where ∇f(x∗)=0\nabla f(x^*) = 0, the linear term vanishes and the quadratic form h⊤∇2f hh^\top \nabla^2 f\, h decides what ff does nearby. By the spectral theorem, the symmetric Hessian is QΛQ⊤Q\Lambda Q^\top with orthonormal eigenvectors qiq_i and real eigenvalues λi\lambda_i, so

h⊤∇2f(x∗) h=∑iλi (qi⊤h)2.h^\top \nabla^2 f(x^*)\, h = \textstyle\sum_i \lambda_i\, (q_i^\top h)^2 .

Along each eigenvector, ff curves up or down according to the sign of its eigenvalue. The signs classify the point:

eigenvalues of ∇2f(x∗)\nabla^2 f(x^*)x∗x^* is
all positivea strict local minimum
all negativea strict local maximum
some positive, some negativea saddle point
some zero, the others of one signundecided by this test

For the minimum, let λmin⁡>0\lambda_{\min} > 0 be the smallest eigenvalue. The second-order expansion at x∗x^*, the spectral decomposition, and ∑i(qi⊤h)2=∥h∥2\sum_i(q_i^\top h)^2 = \lVert h\rVert^2 for an orthogonal QQ give

f(x∗+h)−f(x∗)=12∑iλi(qi⊤h)2+o(∥h∥2)≥12λmin⁡∥h∥2+o(∥h∥2).\begin{aligned} f(x^* + h) - f(x^*) &= \tfrac12 \textstyle\sum_i \lambda_i (q_i^\top h)^2 + o\big(\lVert h\rVert^2\big) \\ &\ge \tfrac12 \lambda_{\min} \lVert h\rVert^2 + o\big(\lVert h\rVert^2\big) . \end{aligned}

For small h≠0h \ne 0 the remainder is below 14λmin⁡∥h∥2\tfrac14\lambda_{\min}\lVert h\rVert^2, so the difference is positive. The maximum is the same argument for −f-f. At a saddle, the step h=tq+h = tq_+ along an eigenvector with λ+>0\lambda_+ > 0 changes ff by 12λ+t2+o(t2)>0\tfrac12\lambda_+t^2 + o(t^2) > 0, and a step along an eigenvector with a negative eigenvalue changes it by a negative amount, so x∗x^* is neither a minimum nor a maximum.

With a zero eigenvalue the quadratic term is flat in some direction and higher-order terms decide: x14+x22x_1^4 + x_2^2 and −x14+x22-x_1^4 + x_2^2 both have the Hessian diag⁡(0,2)\operatorname{diag}(0, 2) at the origin, and the first has a minimum there, the second a saddle.

Example. The cubic cc has ∇c=0\nabla c = 0 where x12=1x_1^2 = 1 and x2=0x_2 = 0: at (1,0)(1, 0) and (−1,0)(-1, 0). At (1,0)(1, 0) the Hessian is diag⁡(6,2)\operatorname{diag}(6, 2), both eigenvalues positive: a strict local minimum, with c=−2c = -2. At (−1,0)(-1, 0) it is diag⁡(−6,2)\operatorname{diag}(-6, 2): a saddle with c=2c = 2, a maximum along x1x_1 and a minimum along x2x_2. The minimum is only local, since c→−∞c \to -\infty as x1→−∞x_1 \to -\infty.

Figure

A bowl and a saddle of one function

Level sets of a cubic function with a minimum and a saddleOn the right, nested ovals around the minimum; on the left, curves bending around the saddle and one level set crossing itself there in an X. Arrows show the eigenvector directions of the Hessian.λ = 6λ = 2λ = −6λ = 2minimum at (1, 0): ∇²c = diag(6, 2)both eigenvalues > 0: a bowlsaddle at (−1, 0): ∇²c = diag(−6, 2)mixed signs: up along x₂, down along x₁amber: the level c = 2 through the saddleLevel sets of a cubic function with a minimum and a saddleOn the right, nested ovals around the minimum; on the left, curves bending around the saddle and one level set crossing itself there in an X. Arrows show the eigenvector directions of the Hessian.λ = 6λ = 2λ = −6λ = 2minimum: diag(6, 2), a bowlsaddle: diag(−6, 2)amber: the level c = 2
Level sets of c(x) = x₁³ − 3x₁ + x₂² for c = −1.5, −0.75, 0.25, 1.25, 2, 3. At (1, 0) the Hessian diag(6, 2) is positive definite: ovals around the minimum c = −2. At (−1, 0) the Hessian diag(−6, 2) has mixed signs, and the level c = 2 (amber) crosses itself at the saddle.

A Hessian that is positive semidefinite everywhere makes the loss convex (second-order condition), and then every critical point is a global minimum: the tangent plane lies below a convex function (first-order condition), and at a critical point that plane is flat. The logistic loss, with Hessian X⊤SXX^\top SX, is the standard example. The eigenvalues also set the speed of first-order methods. On a quadratic, gradient descent needs a step below 2/λmax⁡2/\lambda_{\max} and converges at a rate set by λmax⁡/λmin⁡\lambda_{\max}/\lambda_{\min}, and Newton’s method rescales by the inverse Hessian, as the unconstrained optimization note shows.

The losses of neural networks are not convex. Dauphin et al. (2014) argue, from statistical physics, random matrix theory and experiments, that the main difficulty of local methods in high dimension is the proliferation of saddle points, which create plateaus that slow training and can look like minima.

Where it breaks: flat directions#

The second-order test is silent exactly where overparameterized models live. Take the smallest such model, a product of two weights fitted to one target: L(a,b)=(ab−1)2L(a, b) = (ab - 1)^2. Every point of the hyperbola ab=1ab = 1 is a global minimum, with L=0L = 0. The Hessian is

∇2L(a,b)=(2b22(2ab−1)2(2ab−1)2a2).\nabla^2 L(a, b) = \begin{pmatrix} 2b^2 & 2(2ab - 1) \\ 2(2ab - 1) & 2a^2 \end{pmatrix} .

At (1,1)(1, 1) it is (2222)\begin{pmatrix} 2 & 2 \\ 2 & 2 \end{pmatrix}, with eigenvalues 4 and 0. The zero eigenvalue points along (1,−1)(1, -1), the direction of the hyperbola, where rescaling a→caa \to ca, b→b/cb \to b/c leaves the product, and the loss, unchanged. At (2,0.5)(2, 0.5) the eigenvalues are 8.58.5 and 0. On the whole hyperbola 2ab−1=12ab - 1 = 1, and the determinant is 4a2b2−4=04a^2b^2 - 4 = 0: the test says “undecided” at every minimum. A ReLU network has the same symmetry. Since max⁡(0,cz)=cmax⁡(0,z)\max(0, cz) = c\max(0, z) for c>0c > 0, scaling the weights and the bias into a unit by cc and the weights out of it by 1/c1/c leaves the function unchanged, so its minima come in flat families and are never strict.

The Hessian is also too big to use directly. A network with 10610^6 weights has a Hessian with 101210^{12} entries, 8 terabytes in double precision. Second-order methods work with Hessian–vector products instead, which cost about as much as a few gradients (Pearlmutter, 1994). The Hessian is the Jacobian of ∇f\nabla f, so ∇2f(x) v\nabla^2 f(x)\,v is the directional derivative of ∇f\nabla f along vv, and a central difference of two gradients approximates it; the Code section computes one. And at a kink of a ReLU, a hinge loss or an ℓ1\ell_1 norm, the gradient does not exist at all; the convexity note handles such points with subgradients.

What you should remember#

  • f(x+h)=f(x)+⟨∇f(x),h⟩+o(∥h∥)f(x + h) = f(x) + \langle \nabla f(x), h\rangle + o(\lVert h\rVert); partial derivatives alone do not guarantee differentiability.
  • Duf=⟨∇f,u⟩D_uf = \langle \nabla f, u\rangle: the gradient points uphill most steeply, with rate ∥∇f∥\lVert \nabla f\rVert, and is perpendicular to the level sets.
  • The Jacobian is outputs × inputs; ∣det⁡J∣\lvert\det J\rvert is the local factor by which the map scales volume.
  • Chain rule: Jg∘f=JgJfJ_{g \circ f} = J_gJ_f; for a scalar loss, ∇(ℓ∘f)=Jf⊤∇ℓ\nabla(\ell \circ f) = J_f^\top\nabla\ell, evaluated from the loss backwards.
  • f(x+h)≈f(x)+⟨∇f,h⟩+12h⊤∇2f hf(x + h) \approx f(x) + \langle \nabla f, h\rangle + \tfrac12 h^\top\nabla^2 f\, h; at a critical point the signs of the Hessian’s eigenvalues tell minimum, maximum or saddle.
  • A zero eigenvalue leaves the test undecided, and overparameterized models have such flat directions at every minimum.

Code#

Every derivative of the note is checked against central differences: the gradient and the directional derivative of qq, the Jacobian and the chain rule for FF, the area of the image of a small square, the second-order expansion and the critical points of cc, the flat minimum of (ab−1)2(ab - 1)^2, and a Hessian–vector product from two gradients. Digits in the last places may vary across platforms.

import numpy as np
from scipy import integrate

def num_grad(f, x, h=1e-6):
    """Central differences, one coordinate at a time."""
    E = np.eye(len(x))
    return np.array([(f(x + h * e) - f(x - h * e)) / (2 * h) for e in E])

def num_jac(F, x, h=1e-6):
    """Column j is the central difference of F along e_j."""
    return np.column_stack([(F(x + h * e) - F(x - h * e)) / (2 * h) for e in np.eye(len(x))])

# the quadratic q: gradient, directional derivative, steepest ascent, the tangent of the level set
q = lambda x: x[0] ** 2 + x[0] * x[1] + 2 * x[1] ** 2
grad_q = lambda x: np.array([2 * x[0] + x[1], x[0] + 4 * x[1]])
x = np.array([1.0, 1.0])
u = np.array([0.6, 0.8]); tangent = np.array([5.0, -3.0]) / np.sqrt(34)
print(q(x), grad_q(x), num_grad(q, x).round(8), round(grad_q(x) @ u, 6), round(np.linalg.norm(grad_q(x)), 3), grad_q(x) @ tangent)
# 4.0 [3. 5.] [3. 5.] 5.8 5.831 0.0
angle = np.degrees(np.arccos(grad_q(x) @ x / np.linalg.norm(grad_q(x)) / np.linalg.norm(x)))
print(round(angle, 1))   # 14.0: the descent direction does not point at the minimum

# the Jacobian of F(x) = (x1^2 - x2^2, 2 x1 x2) and the chain rule with l(v) = v1 + v2^2
F = lambda x: np.array([x[0] ** 2 - x[1] ** 2, 2 * x[0] * x[1]])
J_F = lambda x: np.array([[2 * x[0], -2 * x[1]], [2 * x[1], 2 * x[0]]])
ell = lambda v: v[0] + v[1] ** 2
p = np.array([1.0, 0.5])
print(J_F(p).tolist(), np.abs(num_jac(F, p) - J_F(p)).max() < 1e-8, round(np.linalg.det(J_F(p)), 6))   # [[2.0, -1.0], [1.0, 2.0]] True 5.0
print(J_F(p).T @ np.array([1, 2 * F(p)[1]]), num_grad(lambda x: ell(F(x)), p).round(8))   # [4. 3.] [4. 3.]

# the image of a square of side s centred at p has area integral of |det J| = 4(x1^2 + x2^2) over the square
for s in (0.2, 0.1):
    area = integrate.dblquad(lambda y, x: 4 * (x * x + y * y), 1 - s / 2, 1 + s / 2, 0.5 - s / 2, 0.5 + s / 2)[0]
    print(s, round(area, 4), round(area / s ** 2, 3))   # 0.2 0.2011 5.027 | 0.1 0.0501 5.007

# the cubic c: second-order Taylor at (1.2, 0.5) with step (0.1, -0.2), then its critical points
c = lambda x: x[0] ** 3 - 3 * x[0] + x[1] ** 2
grad_c = lambda x: np.array([3 * x[0] ** 2 - 3, 2 * x[1]])
hess_c = lambda x: np.array([[6 * x[0], 0.0], [0.0, 2.0]])
x0, h = np.array([1.2, 0.5]), np.array([0.1, -0.2])
lin = c(x0) + grad_c(x0) @ h; quad = lin + 0.5 * h @ hess_c(x0) @ h
print(round(c(x0), 3), round(lin, 3), round(quad, 3), round(c(x0 + h), 3), round(c(x0 + h) - lin, 3), round(c(x0 + h) - quad, 6))
# -1.622 -1.69 -1.614 -1.613 0.077 0.001
print(np.abs(num_jac(grad_c, x0) - hess_c(x0)).max() < 1e-6)   # True: the Hessian is the Jacobian of the gradient
for xs in (np.array([1.0, 0.0]), np.array([-1.0, 0.0])):
    lam = np.linalg.eigvalsh(hess_c(xs))
    kind = 'minimum' if lam.min() > 0 else 'maximum' if lam.max() < 0 else 'saddle' if lam.min() < 0 < lam.max() else 'undecided'
    print(xs, grad_c(xs), lam, c(xs), kind)
# [1. 0.] [0. 0.] [2. 6.] -2.0 minimum | [-1.  0.] [0. 0.] [-6.  2.] 2.0 saddle

# a flat minimum: L(a, b) = (ab - 1)^2 has a zero Hessian eigenvalue along the hyperbola ab = 1
L = lambda w: (w[0] * w[1] - 1) ** 2
grad_L = lambda w: np.array([2 * (w[0] * w[1] - 1) * w[1], 2 * (w[0] * w[1] - 1) * w[0]])
for w in (np.array([1.0, 1.0]), np.array([2.0, 0.5])):
    H = num_jac(grad_L, w)
    print(w, L(w), np.linalg.eigvalsh(H).round(6) + 0.0)
# [1. 1.] 0.0 [0. 4.] | [2.  0.5] 0.0 [0.  8.5]

# a Hessian-vector product from two gradients, without forming the Hessian
v = np.array([0.3, -0.7]); eps = 1e-6
print(((grad_c(x0 + eps * v) - grad_c(x0 - eps * v)) / (2 * eps)).round(6), hess_c(x0) @ v)   # [ 2.16 -1.4 ] [ 2.16 -1.4 ]

Next#

The examples so far were differentiated coordinate by coordinate. That stops working for the expressions of machine learning, which are written in whole vectors and matrices: ∥Xw−y∥2\lVert Xw - y\rVert^2, log⁡det⁡Σ\log\det\Sigma, softmax⁡(Wx)\operatorname{softmax}(Wx). The next note fixes a layout convention and introduces the differential, a way to differentiate such expressions without writing an index, and uses it to derive the gradients that the machine learning notes quote.

References#