TExcelTAD
Home › Calculus Essentials › Jacobian and Hessian

Jacobian and Hessian

Two matrices organise the derivatives of multivariable functions. The Jacobian holds the first derivatives of a function with several outputs; it is the best linear approximation of that function and the object that backpropagation passes through every layer. The Hessian holds the second derivatives of a function with one output; it describes curvature and powers Newton's method.

The Jacobian matrix

A function F:Rn→RmF: \mathbb{R}^n \to \mathbb{R}^m has mm output components F1,…,FmF_1, \ldots, F_m, each depending on nn inputs. Its Jacobian is the m×nm \times n matrix of all first partials, one row per output:

J=[∂F1∂x1⋯∂F1∂xn⋮⋮∂Fm∂x1⋯∂Fm∂xn]Jij=∂Fi∂xjJ = \begin{bmatrix} \dfrac{\partial F_1}{\partial x_1} & \cdots & \dfrac{\partial F_1}{\partial x_n} \\ \vdots & & \vdots \\ \dfrac{\partial F_m}{\partial x_1} & \cdots & \dfrac{\partial F_m}{\partial x_n} \end{bmatrix} \qquad J_{ij} = \frac{\partial F_i}{\partial x_j}

It plays the role of the derivative: near a point p\mathbf{p},

F(p+h)≈F(p)+J(p)⋅hF(\mathbf{p} + \mathbf{h}) \approx F(\mathbf{p}) + J(\mathbf{p}) \cdot \mathbf{h}

so locally FF behaves like the matrix JJ. Row ii of JJ is the gradient of FiF_i; for a single output (m=1m = 1) the Jacobian is just the gradient written as a row.

The Jacobian determinant

For a map from R2\mathbb{R}^2 to R2\mathbb{R}^2 (or R3\mathbb{R}^3 to R3\mathbb{R}^3), JJ is square and ∣det⁡J∣\lvert \det J \rvert is the local area (volume) scale factor: a tiny square of area dAdA near p\mathbf{p} is mapped to a tiny parallelogram of area ∣det⁡J(p)∣⋅dA\lvert \det J(\mathbf{p}) \rvert \cdot dA. The polar-coordinate map (r,θ)↦(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (r\cos\theta, r\sin\theta) has det⁡J=r\det J = r, which is why dA=r dr dθdA = r \, dr \, d\theta in double integrals.

python · try it yourself
import sympy as sp

r, th = sp.symbols('r theta', positive=True)
F = sp.Matrix([r * sp.cos(th), r * sp.sin(th)])
J = F.jacobian([r, th])
print("J =", J.tolist())
print("det J =", sp.simplify(J.det()))

# spherical coordinates (rho, phi, theta)
rho, phi = sp.symbols('rho phi', positive=True)
S = sp.Matrix([rho*sp.sin(phi)*sp.cos(th), rho*sp.sin(phi)*sp.sin(th), rho*sp.cos(phi)])
print("spherical det J =", sp.simplify(S.jacobian([rho, phi, th]).det()))
J = [[cos(theta), -r*sin(theta)], [sin(theta), r*cos(theta)]]
det J = r
spherical det J = rho**2*sin(phi)

The Jacobian in backpropagation

A neural-network layer y=σ(Wx+b)\mathbf{y} = \sigma(W\mathbf{x} + \mathbf{b}), with σ\sigma applied element by element, is a function from Rn\mathbb{R}^n to Rm\mathbb{R}^m. Writing u=Wx+b\mathbf{u} = W\mathbf{x} + \mathbf{b}, the chain rule in matrix form gives

∂y∂x=diag⁡(σ′(u))⋅W(an m×n Jacobian)\frac{\partial \mathbf{y}}{\partial \mathbf{x}} = \operatorname{diag}(\sigma'(\mathbf{u})) \cdot W \qquad (\text{an } m \times n \text{ Jacobian})

Composing layers multiplies their Jacobians, the multivariable chain rule written with matrices. Backpropagation never builds these matrices in full. It starts from the gradient of the scalar loss, a row vector g=∂L/∂y\mathbf{g} = \partial L/\partial \mathbf{y}, and computes the vector-Jacobian product g⋅J\mathbf{g} \cdot J, layer by layer from the output back to the input. That costs about as much as one forward pass, whatever the size of the network. See Backpropagation Is the Chain Rule.

python · try it yourself
import numpy as np

rng = np.random.default_rng(7)
W = rng.normal(size=(3, 4))
b = rng.normal(size=3)
x = rng.normal(size=4)

layer = lambda x: np.tanh(W @ x + b)
u = W @ x + b
J = np.diag(1 - np.tanh(u) ** 2) @ W          # tanh'(u) = 1 - tanh(u)^2

h = 1e-6
J_num = np.column_stack([(layer(x + h * e) - layer(x - h * e)) / (2 * h) for e in np.eye(4)])
print("Jacobian shape:", J.shape)
print("max |J - J_num|:", f"{np.max(np.abs(J - J_num)):.1e}")

g = np.array([1.0, -2.0, 0.5])                # dL/dy from the layer above
print("vector-Jacobian product g·J:", np.round(g @ J, 4))
Jacobian shape: (3, 4)
max |J - J_num|: 4.3e-11
vector-Jacobian product g·J: [-0.1791 -0.1515  0.1522 -0.0792]

The Hessian matrix

For a scalar function f:Rn→Rf: \mathbb{R}^n \to \mathbb{R}, the Hessian is the n×nn \times n matrix of second partials, Hij=∂2f/∂xi∂xjH_{ij} = \partial^2 f/\partial x_i \partial x_j. By Clairaut's theorem it is symmetric. It is the Jacobian of the gradient, and it gives the second-order (quadratic) approximation

f(p+h)≈f(p)+∇f(p)⋅h+12hTH(p)hf(\mathbf{p} + \mathbf{h}) \approx f(\mathbf{p}) + \nabla f(\mathbf{p}) \cdot \mathbf{h} + \tfrac{1}{2} \mathbf{h}^T H(\mathbf{p}) \mathbf{h}

At a critical point (∇f=0\nabla f = \mathbf{0}) the quadratic term decides everything, and the eigenvalues of HH say how the surface curves along its principal directions:

Eigenvalues of HH Critical point
all positive (HH positive definite) local minimum
all negative local maximum
mixed signs saddle point
some zero inconclusive

In two variables, det⁡H=fxxfyy−fxy2\det H = f_{xx} f_{yy} - f_{xy}^2 is the discriminant DD of the second-derivative test. A large ratio between the biggest and smallest eigenvalue (the condition number) means a long narrow valley, the shape that makes gradient descent zig-zag.

Newton's method in several variables

Newton's method for minimisation jumps to the minimum of the local quadratic model:

p←p−H(p)−1∇f(p)(in code: solve H⋅s=∇f, then p←p−s)\mathbf{p} \leftarrow \mathbf{p} - H(\mathbf{p})^{-1} \nabla f(\mathbf{p}) \qquad (\text{in code: solve } H \cdot \mathbf{s} = \nabla f, \text{ then } \mathbf{p} \leftarrow \mathbf{p} - \mathbf{s})

On an exact quadratic this lands on the minimum in one step, whatever the condition number. Near a minimum of a general smooth function it converges quadratically (the number of correct digits roughly doubles each step). The price is computing and solving with an n×nn \times n matrix, too much for a network with millions of weights. Quasi-Newton methods (BFGS, L-BFGS) build an approximate Hessian from gradients instead, and Adam's per-weight scaling is a cheap diagonal stand-in.

python · try it yourself
import numpy as np

f = lambda p: (1 - p[0])**2 + 10 * (p[1] - p[0]**2)**2      # a curved valley, min at (1, 1)
grad = lambda p: np.array([-2*(1 - p[0]) - 40*p[0]*(p[1] - p[0]**2), 20*(p[1] - p[0]**2)])
hess = lambda p: np.array([[2 - 40*p[1] + 120*p[0]**2, -40*p[0]],
                           [-40*p[0], 20.0]])

p = np.array([-1.0, 2.0])
print("eigenvalues of H at the minimum:", np.round(np.linalg.eigvalsh(hess(np.array([1.0, 1.0]))), 3))
for k in range(6):
    p = p - np.linalg.solve(hess(p), grad(p))
    print(f"Newton step {k + 1}: p = {np.round(p, 6)}, f = {f(p):.2e}")
eigenvalues of H at the minimum: [  0.394 101.606]
Newton step 1: p = [-1.105263  1.210526], f = 4.43e+00
Newton step 2: p = [ 0.618093 -2.587917], f = 8.84e+01
Newton step 3: p = [0.624416 0.389855], f = 1.41e-01
Newton step 4: p = [0.9997   0.858562], f = 1.98e-01
Newton step 5: p = [0.999779 0.999557], f = 4.90e-08
Newton step 6: p = [1. 1.], f = 2.41e-14

Both eigenvalues at (1,1)(1, 1) are positive, so it is a minimum, and their ratio of about 250 shows how narrow the valley is. Far from the minimum pure Newton can wander (step 2 even makes ff worse, which is why practical solvers add a line search or trust region), but once it is close the error collapses: ff is about 0.2 after step 4, 5⋅10−85 \cdot 10^{-8} after step 5 and 2⋅10−142 \cdot 10^{-14} after step 6.

Exercises

Exercise 1: A Jacobian by hand

Find the Jacobian of F(x,y)=(x2y,x+sin⁡y)F(x, y) = (x^2y, x + \sin y) and evaluate it at (1,0)(1, 0).

Answer

J=[2xyx21cos⁡y]=[0111]J = \begin{bmatrix} 2xy & x^2 \\ 1 & \cos y \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix} at (1,0)(1, 0).

Solution
Row 1 (F1=x2y):∂∂x=2xy,∂∂y=x2Row 2 (F2=x+sin⁡y):∂∂x=1,∂∂y=cos⁡yAt (1,0):[0111]\begin{aligned} &\text{Row 1 } (F_1 = x^2y){:} && \frac{\partial}{\partial x} = 2xy, && \frac{\partial}{\partial y} = x^2 \\ &\text{Row 2 } (F_2 = x + \sin y){:} && \frac{\partial}{\partial x} = 1, && \frac{\partial}{\partial y} = \cos y \\ &\text{At } (1, 0){:} && \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix} \end{aligned}

Exercise 2: Area scaling

The map (u,v)↦(2u+v,u−3v)(u, v) \mapsto (2u + v, u - 3v) is applied to the unit square. What is the area of the image?

Answer
Solution

J=[211−3]J = \begin{bmatrix} 2 & 1 \\ 1 & -3 \end{bmatrix} everywhere, det⁡J=−6−1=−7\det J = -6 - 1 = -7, and the area scale factor is ∣−7∣=7\lvert -7 \rvert = 7. The negative sign means the map flips orientation.

Exercise 3: Classify with the Hessian

f(x,y,z)=x2+2y2+3z2+2xyf(x, y, z) = x^2 + 2y^2 + 3z^2 + 2xy. Show that the origin is a critical point and classify it using the Hessian's eigenvalues.

Answer

H=[220240006]H = \begin{bmatrix} 2 & 2 & 0 \\ 2 & 4 & 0 \\ 0 & 0 & 6 \end{bmatrix}, eigenvalues 3−5≈0.7643 - \sqrt{5} \approx 0.764, 3+5≈5.2363 + \sqrt{5} \approx 5.236 and 6, all positive: a minimum.

Solution

∇f=⟨2x+2y,4y+2x,6z⟩=0\nabla f = \langle 2x + 2y, 4y + 2x, 6z \rangle = \mathbf{0} at the origin. The Hessian is constant. The z-block gives eigenvalue 6; the 2×22 \times 2 block [2224]\begin{bmatrix} 2 & 2 \\ 2 & 4 \end{bmatrix} has trace 6 and determinant 4, so λ2−6λ+4=0\lambda^2 - 6\lambda + 4 = 0, λ=3±5\lambda = 3 \pm \sqrt{5}.

python · try it yourself
import numpy as np
H = np.array([[2.0, 2.0, 0.0], [2.0, 4.0, 0.0], [0.0, 0.0, 6.0]])
print(np.round(np.linalg.eigvalsh(H), 4))
[0.7639 5.2361 6.    ]

Exercise 4: Newton on a quadratic (code)

For f(x,y)=3x2+2xy+y2−4xf(x, y) = 3x^2 + 2xy + y^2 - 4x, take a single Newton step from (10,−7)(10, -7). Where do you land, and is it the minimum?

Answer

(1,−1)(1, -1), which is the exact minimum (the gradient there is zero).

Solution

∇f=⟨6x+2y−4,2x+2y⟩\nabla f = \langle 6x + 2y - 4, 2x + 2y \rangle, H=[6222]H = \begin{bmatrix} 6 & 2 \\ 2 & 2 \end{bmatrix}. Setting ∇f=0\nabla f = \mathbf{0} gives x=−yx = -y and 6x−2x=46x - 2x = 4, so x=1x = 1, y=−1y = -1. Newton's step reaches it immediately because ff is exactly quadratic.

python · try it yourself
import numpy as np
grad = lambda p: np.array([6*p[0] + 2*p[1] - 4, 2*p[0] + 2*p[1]])
H = np.array([[6.0, 2.0], [2.0, 2.0]])
p = np.array([10.0, -7.0])
p = p - np.linalg.solve(H, grad(p))
print(np.round(p, 10), "gradient ≈ 0:", bool(np.max(np.abs(grad(p))) < 1e-12))
[ 1. -1.] gradient ≈ 0: True

Test yourself

What is the shape of the Jacobian of F:R5→R2F: \mathbb{R}^5 \to \mathbb{R}^2?

  1. 5×25 \times 2
  2. 2×52 \times 5
  3. 5×55 \times 5
  4. 2×22 \times 2

The Hessian at a critical point has eigenvalues 4 and −1. The point is…

  1. a minimum
  2. a maximum
  3. a saddle point
  4. impossible to classify

Why is ∣det⁡J∣=r\lvert \det J \rvert = r in polar coordinates important?

  1. It makes rr always positive
  2. It is the area scale factor, so dA=r dr dθdA = r \, dr \, d\theta
  3. It shows polar coordinates are linear
  4. It is the gradient of rr