Module contents
Lesson 7 of 20Core 100 min

The differential and the Jacobian matrix

Define the derivative of a map f: ℝⁿ → ℝᵐ as the linear map that best approximates it (Fréchet derivative), and the Jacobian matrix as its representation. Study the C¹ criterion, linearization, Jacobian determinant as a local volume factor and the mean value inequality, with applications to robot kinematics and neural-layer sensitivity.

After this lesson you can

  • Define Fréchet differentiability and distinguish it from existence of directional derivatives (Gâteaux).
  • Calculate Jacobians of vector maps, including polar coordinates, softmax and network layers.
  • Prove that continuous partial derivatives imply differentiability.
  • Interpret the Jacobian determinant as a local factor of volume change and orientation.
  • Use the mean value inequality to obtain Lipschitz constants of vector maps and small networks.

Before you start

Motivation: three functions that do not fit in one derivative

In the preceding lesson you differentiated functions f:Rn→Rf: \R^n \to \R: a loss, a height, a temperature. With the partial derivative, directional derivative and gradient you can measure how a number changes when you move a point. But almost everything you build returns several numbers:

  • A network layer x↦tanh⁡(Wx+b)\vb{x} \mapsto \tanh(\mat{W}\vb{x} + \vb{b}) goes from Rdin\R^{d_{\text{in}}} to Rdout\R^{d_{\text{out}}}. “How much does output move if I perturb input?” determines training stability, gradient explosion and robustness to adversarial examples.
  • A coordinate change such as polar coordinates, (r,θ)↦(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (r\cos\theta, r\sin\theta), goes from R2\R^2 to R2\R^2. To integrate in polar coordinates we must know how much it stretches area, and the answer (rr) is not visible in any isolated partial derivative.
  • A robot arm maps joint angles θ∈R2\theta \in \R^2 to gripper position p∈R2\vb{p} \in \R^2. The controller needs the relation between velocities p˙\dot{\vb{p}} and θ˙\dot\theta, and to know where that relation ceases to be invertible.

All three have mnmn partial derivatives ∂fi/∂xj\partial f_i / \partial x_j, and it is tempting to call that table “the derivative.” This lesson explains why the table is not fundamental. The fundamental object is a linear map: the one best approximating ff near a point. The table is only its matrix in the canonical bases, just as in the matrix of a linear map. Some functions have all partials and even all directional derivatives yet admit no linear approximation: their table exists and means nothing.

The idea can be seen before writing a definition. A nonlinear map bends the plane’s grid; under an increasingly powerful magnifier around a point, the curved grid straightens into a grid of parallelograms, the image of the grid under a matrix.

InteractiveThe grid becomes linear
Image of the grid under ff
Magnifier: f(Q)f(Q) rescaled by 1/ρ1/\rho
  • ff grid (curved)
  • linear grid Jh\mat{J}\vb{h}
  • Q=a+[−ρ,ρ]2Q = \vb{a} + [-\rho, \rho]^2 and its image
  • det⁡J>0\det \mat{J} > 0
  • det⁡J<0\det \mat{J} < 0
Map
0.60
0.90
J(a)=[1.000.790.561.00]\mat{J}(\vb{a}) = \begin{bmatrix} 1.00 & 0.79 \\ 0.56 & 1.00 \end{bmatrix}
a=(x,y)=(0.90,0.50)\vb{a} = (x, y) = (0.90, 0.50)
det⁡J(a)\det \mat{J}(\vb{a})0.558
signed area of f(Q)f(Q) / area of QQ0.609
magnified mismatch, max⁡∥φ−Js∥\max \norm{\varphi - \mat{J}\vb{s}}0.295
On the left, the image by ff of a domain grid; square Q=a+[−ρ,ρ]2Q = \vb{a} + [-\rho, \rho]^2 and its image are magenta. On the right, a magnifier enlarging f(Q)f(Q) by 1/ρ1/\rho. Reduce ρ\rho: the blue grid merges with the dashed orange grid, the image under matrix J\mat{J}, and the mismatch halves whenever ρ\rho halves. Signed area of f(Q)f(Q) divided by that of QQ tends to det⁡J\det\mat{J}. Raise ripple amplitude above 11: red cells appear where the grid folds and orientation reverses. Also try polar coordinates (local area is rr) and layer tanh⁡\tanh, whose saturated regions squash the grid.

Three observations guide the lesson:

  • Up close, everything is linear, except at exceptional points. What appears under the magnifier does not depend on curvature of ff: it is a linear object, a matrix 2×22 \times 2, and the discrepancy between curved and straight grids becomes small faster than the magnifier itself.
  • That matrix has meaningful columns. The first column, Je1\mat{J}\vb{e}_1, is the direction ff moves when you advance in the first coordinate; the second, when advancing in the second.
  • Its determinant is a signed area factor. Where negative, the grid is reflected; where zero, it folds.

The differential: the best linear approximation

In one variable, ff is differentiable at aa if there exists a number f′(a)f'(a) with f(a+h)=f(a)+f′(a) h+o(h)f(a + h) = f(a) + f'(a)\,h + o(h). The form with a bare number does not generalize well to several variables; the approximation form does: replace “multiply by a number” with “apply a linear map” and measure error with a norm. Notation o(⋅)o(\cdot) is Landau’s: r(h)=o(∥h∥)\vb{r}(\vb{h}) = o(\norm{\vb{h}}) means ∥r(h)∥/∥h∥→0\norm{\vb{r}(\vb{h})}/\norm{\vb{h}} \to 0 as h→0\vb{h} \to \vb{0}, with the multivariable limit from the preceding lesson, which must hold along all paths at once.

Three comments on the definition, because every word does work.

  • The remainder is compared with ∥h∥\norm{\vb{h}}, not a constant. Any linear map approximates ff with error tending to zero if ff is continuous; what distinguishes Df(a)Df(\vb{a}) is that the error tends to zero faster than h\vb{h}. Under the interactive’s magnifier, this is exactly the mismatch divided by ρ\rho tending to 00.
  • The limit is in Rn\R^n, in every direction at once. It is not enough for the quotient to tend to zero along each line through a\vb{a}; that difference is the Gâteaux versus Fréchet section and the lesson’s main trap.
  • The norm does not matter. In Rn\R^n all norms are equivalent (c∥⋅∥a≤∥⋅∥b≤C∥⋅∥ac\norm{\cdot}_a \le \norm{\cdot}_b \le C\norm{\cdot}_a), so “o(∥h∥)o(\norm{\vb{h}})” means the same under any norm. We use the Euclidean norm unless stated otherwise.
Proof

Suppose L1L_1 and L2L_2 satisfy the definition, with remainders r1\vb{r}_1 and r2\vb{r}_2. Subtracting, (L1−L2)h=r2(h)−r1(h)(L_1 - L_2)\vb{h} = \vb{r}_2(\vb{h}) - \vb{r}_1(\vb{h}) for every small h\vb{h}. Fix vector v≠0\vb{v} \ne \vb{0} and take h=tv\vb{h} = t\vb{v} with t>0t > 0. By linearity,

∥(L1−L2)v∥=∥(L1−L2)(tv)∥t=∥v∥ ∥r2(tv)−r1(tv)∥∥tv∥→t→0+0.\norm{(L_1 - L_2)\vb{v}} = \frac{\norm{(L_1 - L_2)(t\vb{v})}}{t} = \norm{\vb{v}}\,\frac{\norm{\vb{r}_2(t\vb{v}) - \vb{r}_1(t\vb{v})}}{\norm{t\vb{v}}} \xrightarrow[t \to 0^+]{} 0.

The left side does not depend on tt, so it equals 00: L1v=L2vL_1\vb{v} = L_2\vb{v} for every v\vb{v}.

∎

Uniqueness lets us speak of the differential. It has two immediate consequences worth proving now, because they are used constantly.

Proof
  1. ∥f(a+h)−f(a)∥≤∥Df(a)h∥+∥r(h)∥\norm{f(\vb{a} + \vb{h}) - f(\vb{a})} \le \norm{Df(\vb{a})\vb{h}} + \norm{\vb{r}(\vb{h})}. The first term tends to 00 because a linear map between finite-dimensional spaces is continuous; the second because ∥r(h)∥=∥h∥⋅o(1)\norm{\vb{r}(\vb{h})} = \norm{\vb{h}} \cdot o(1).
  2. For u≠0\vb{u} \ne \vb{0} and t≠0t \ne 0, with h=tu\vb{h} = t\vb{u}:
f(a+tu)−f(a)t=Df(a) u+r(tu)t,∥r(tu)t∥=∥u∥ ∥r(tu)∥∥tu∥→0.\frac{f(\vb{a} + t\vb{u}) - f(\vb{a})}{t} = Df(\vb{a})\,\vb{u} + \frac{\vb{r}(t\vb{u})}{t}, \qquad \norm{\frac{\vb{r}(t\vb{u})}{t}} = \norm{\vb{u}}\,\frac{\norm{\vb{r}(t\vb{u})}}{\norm{t\vb{u}}} \to 0.

For u=0\vb{u} = \vb{0} both equal 0\vb{0}. 3. This is point 2 with u=ej\vb{u} = \vb{e}_j.

∎

Point 2 settles unfinished business from the preceding lesson: there you used Duf=∇f⋅uD_{\vb{u}} f = \grad f \cdot \vb{u} “when ff is differentiable.” Now it has a three-line proof. Read backward it gives the most useful nondifferentiability test: if u↦Duf(a)\vb{u} \mapsto D_{\vb{u}}f(\vb{a}) is not linear, ff is not differentiable at a\vb{a}.

The Jacobian matrix

Since Df(a)Df(\vb{a}) is linear from Rn\R^n to Rm\R^m, it has a matrix m×nm \times n in canonical bases, and column jj is the image of ej\vb{e}_j. By point 3 of the proposition, that column is the vector of partials ∂f/∂xj\partial f / \partial x_j.

Notice the logical order. The Jacobian can be written whenever partial derivatives exist, but represents a differential only if ff is differentiable. The next section constructs functions with perfectly calculable Jacobians and no differential.

The matrix can be read two ways, like any matrix:

  • By rows: gradients. Row ii is ∇fi(a)⊤\grad f_i(\vb{a})\T, the differential of component fif_i. In particular, for m=1m = 1 the Jacobian is the gradient laid horizontally, a row vector 1×n1 \times n: Df(a)h=∇f(a)⊤hDf(\vb{a})\vb{h} = \grad f(\vb{a})\T\vb{h}.
  • By columns: velocities. Column jj is the velocity at t=0t = 0 of curve t↦f(a+tej)t \mapsto f(\vb{a} + t\vb{e}_j), the image of coordinate line jj. This is what arrows Je1\mat{J}\vb{e}_1 and Je2\mat{J}\vb{e}_2 under the magnifier drew: where and how fast ff moves as you advance along each axis.

Four Jacobians you will always use

InteractiveJacobian of a robot arm
  • link 1
  • link 2
  • ∂p/∂θ1\partial\vb{p}/\partial\theta_1
  • ∂p/∂θ2\partial\vb{p}/\partial\theta_2
  • ellipse {Jθ˙:∥θ˙∥=1}\{\mat{J}\dot\theta : \norm{\dot\theta} = 1\}
  • requested velocity
35°
70°
det⁡J=L1L2sin⁡θ2\det \mat{J} = L_1 L_2 \sin\theta_2 versus θ2\theta_2
J(θ)=[−2.60−1.451.25−0.39]\mat{J}(\theta) = \begin{bmatrix} -2.60 & -1.45 \\ 1.25 & -0.39 \end{bmatrix}
det⁡J=L1L2sin⁡θ2\det \mat{J} = L_1L_2\sin\theta_22.819
semiaxes σ1,σ2\sigma_1, \sigma_23.12, 0.903
requested velocity p˙\dot{\vb{p}}(0.90, 0.50)
θ˙=J−1p˙\dot{\theta} = \mat{J}^{-1}\dot{\vb{p}} (rad/s)(0.13, −0.86)
∥θ˙∥\norm{\dot{\theta}}0.87
Orange and aqua arrows are columns of J\mat{J}: gripper velocity if only the shoulder or only the elbow rotates, at 11 rad/s. The magenta ellipse is the image of circle ∥θ˙∥=1\norm{\dot\theta} = 1: all gripper velocities attainable with that joint ‘budget’. Drag the red tip to request velocity p˙\dot{\vb{p}} and see its cost, ∥J−1p˙∥\norm{\mat{J}^{-1}\dot{\vb{p}}}. Move θ2\theta_2 toward 0°0°: the ellipse flattens to a segment perpendicular to the arm, det⁡J→0\det\mat{J} \to 0 and a radial velocity requires joint velocities growing without bound. The panel graph shows det⁡J\det\mat{J} depends only on θ2\theta_2.

What you just saw is a kinematic singularity: a point where J(θ)\mat{J}(\theta) loses rank. There the SVD of J\mat{J} has σ2=0\sigma_2 = 0, the ellipse’s minor semiaxis, and near it joint velocity required to move the gripper at unit speed in direction u2\vb{u}_2 is 1/σ21/\sigma_2, growing without bound. Real controllers avoid those postures or use a damped inverse; the manipulator Jacobian and manipulability σ1σ2=∣det⁡J∣\sigma_1\sigma_2 = \abs{\det\mat{J}} are robotics-module tools.

Gâteaux versus Fréchet

ff is Gâteaux differentiable at a\vb{a} if all directional derivatives exist and u↦Duf(a)\vb{u} \mapsto D_{\vb{u}}f(\vb{a}) is linear; some authors do not require linearity. Fréchet implies Gâteaux by the preceding proposition. The converse is false, and the next two examples show why, each with a different failure: the first has all directional derivatives but they are nonlinear; the second has linear ones and is still not differentiable.

The lesson is the definition: Fréchet requires error to be small uniformly in all directions at once, and Gâteaux only along each line separately.

InteractiveTangent plane and error funnel
  • z=x3x2+y2z = \dfrac{x^3}{x^2 + y^2} (vertical scale ×0.75)
  • plane of partial derivatives at a\vb{a}
  • (a,f(a))(\vb{a}, f(\vb{a}))
Contour map: drag a\vb{a}
sup⁡∥h∥=rR(h)\sup_{\norm{\vb{h}} = r} R(\vb{h}) versus rr (log-log scale)
  • sup R
  • slope 1 (reference)
Function
View
1.000
a\vb{a}(0.00, 0.00)
partials (∂xf,∂yf)(a)(\partial_x f, \partial_y f)(\vb{a})(1.000, 0.000)
Duf(a)D_{\vb{u}} f(\vb{a}), u=(1,1)/2\vb{u} = (1, 1)/\sqrt{2}0.354
∇f(a)⋅u\nabla f(\vb{a}) \cdot \vb{u} (predicted by linearity)0.707
sup⁡∥h∥=ρR(h)\sup_{\norm{\vb{h}} = \rho} R(\vb{h})0.385
The funnel does not close: RR depends only on the direction of h\vb{h}. The directional derivatives exist, but u↦Duf\vb{u} \mapsto D_{\vb{u}} f is not linear.
In ‘Surface’ view, the orange plane is proposed by partial derivatives at a\vb{a}. In ‘Funnel’ view, R(h)=∣f(a+h)−f(a)−∇f(a)⋅h∣/∥h∥R(\vb{h}) = \abs{f(\vb{a} + \vb{h}) - f(\vb{a}) - \grad f(\vb{a}) \cdot \vb{h}}/\norm{\vb{h}} is drawn over disk ∥h∥≤ρ\norm{\vb{h}} \le \rho, always with the same screen radius. ff is differentiable at a\vb{a} exactly when the funnel closes as ρ\rho decreases. With x3/(x2+y2)x^3/(x^2 + y^2) at the origin, funnel shape does not change: RR depends only on direction. With x3y/(x6+y2)x^3y/(x^6 + y^2), a very thin ridge along y=x3y = x^3 grows like 1/(2ρ)1/(2\rho). Drag a\vb{a} away from the origin: both are C1C^1 there and the funnel closes. The log-log graph shows sup⁡∥h∥=rR\sup_{\norm{\vb{h}} = r} R: positive slope (closing), zero or negative.

Continuous partials: the C¹ criterion

Checking Fréchet’s definition by hand is cumbersome: guess LL and bound a multivariable limit. In practice this is almost never done, because a criterion can be checked by looking at the partial-derivative formulas.

This is the C¹ differentiability criterion, and thanks to it polynomials, polar coordinates, softmax, smooth-activation layers and the robot arm are differentiable throughout their domains: their partials are compositions of continuous functions. The proof uses the preceding lesson’s idea of moving one coordinate at a time, plus the single-variable mean value theorem. Build it yourself.

ProofContinuous partials imply differentiability
Prove: If partials of f:U→Rmf: U \to \R^m exist near a\vb{a} and are continuous at a\vb{a}, then f(a+h)=f(a)+Jf(a)h+o(∥h∥)f(\vb{a} + \vb{h}) = f(\vb{a}) + \mat{J}_f(\vb{a})\vb{h} + o(\norm{\vb{h}}).
0
Take δ>0\delta > 0 such that ball B(a,δ)B(\vb{a}, \delta) lies in that neighborhood, and ∥h∥<δ\norm{\vb{h}} < \delta. Call p0=a\vb{p}_0 = \vb{a} and pk=a+h1e1+⋯+hkek\vb{p}_k = \vb{a} + h_1\vb{e}_1 + \dots + h_k\vb{e}_k, so pn=a+h\vb{p}_n = \vb{a} + \vb{h} and all pk\vb{p}_k and segments between them lie in the ball.

Step 1 of 5. What does the problem reduce to?

The criterion is sufficient but not necessary. Function f(x,y)=(x2+y2)sin⁡(1/x2+y2)f(x, y) = (x^2 + y^2)\sin\big(1/\sqrt{x^2 + y^2}\big), with f(0)=0f(\vb{0}) = 0, satisfies ∣f(h)∣≤∥h∥2\abs{f(\vb{h})} \le \norm{\vb{h}}^2, so is differentiable at the origin with Df(0)=0Df(\vb{0}) = 0; but ∂xf(x,0)=2xsin⁡(1/∣x∣)−sgn⁡(x)cos⁡(1/∣x∣)\partial_x f(x, 0) = 2x\sin(1/\abs{x}) - \operatorname{sgn}(x)\cos(1/\abs{x}) oscillates without limit as x→0x \to 0. Conversely, the two functions in the preceding section have partials existing throughout R2\R^2 but discontinuous at the origin: the criterion does not apply, and they indeed fail.

The hierarchy is as follows, with strict implications:

C1  ⟹  diferenciable (Freˊchet)  ⟹  Gateaux con u↦Duf lineal  ⟹  existen las parciales.C^1 \;\Longrightarrow\; \text{diferenciable (Fréchet)} \;\Longrightarrow\; \text{Gateaux con } \vb{u} \mapsto D_{\vb{u}}f \text{ lineal} \;\Longrightarrow\; \text{existen las parciales}.

Linearization and tangent plane

The definition of differentiability says f−ℓaf - \ell_{\vb{a}} is o(∥x−a∥)o(\norm{\vb{x} - \vb{a}}). If ff has one more derivative, the error is quadratic, with an explicit constant.

Proof

Fix ii and define g(t)=fi(a+th)g(t) = f_i(\vb{a} + t\vb{h}) on [0,1][0, 1]. Since fif_i is differentiable (it is C1C^1), point 2 of the proposition applied at a+th\vb{a} + t\vb{h} gives g′(t)=∇fi(a+th)⋅h=∑jhj ∂jfi(a+th)g'(t) = \grad f_i(\vb{a} + t\vb{h}) \cdot \vb{h} = \sum_j h_j\,\partial_j f_i(\vb{a} + t\vb{h}). Each ∂jfi\partial_j f_i is itself C1C^1, and the same argument gives g′′(t)=∑j,khjhk ∂k∂jfi(a+th)=h⊤Hi(a+th) hg''(t) = \sum_{j,k} h_j h_k\,\partial_k\partial_j f_i(\vb{a} + t\vb{h}) = \vb{h}\T\mat{H}_i(\vb{a} + t\vb{h})\,\vb{h}. By single-variable Taylor with Lagrange remainder, g(1)=g(0)+g′(0)+12g′′(ξ)g(1) = g(0) + g'(0) + \tfrac{1}{2}g''(\xi) for some ξ∈(0,1)\xi \in (0, 1), that is,

fi(a+h)−fi(a)−∇fi(a)⋅h=12 h⊤Hi(a+ξh) h,f_i(\vb{a} + \vb{h}) - f_i(\vb{a}) - \grad f_i(\vb{a})\cdot\vb{h} = \tfrac{1}{2}\,\vb{h}\T\mat{H}_i(\vb{a} + \xi\vb{h})\,\vb{h},

whose absolute value is at most 12∥Hi∥2∥h∥2≤12Mi∥h∥2\tfrac{1}{2}\norm{\mat{H}_i}_2\norm{\vb{h}}^2 \le \tfrac{1}{2}M_i\norm{\vb{h}}^2. The vector bound follows by summing squares of components.

∎

Two practical readings. First: relative error under the first interactive’s magnifier, error divided by ρ\rho, behaves like ρ\rho, so halves whenever ρ\rho halves. Second, the basis of gradient checking: if you implement J\mat{J} and compare with f(a+h)−f(a)f(\vb{a} + \vb{h}) - f(\vb{a}), error should fall like ∥h∥2\norm{\vb{h}}^2. If it falls like ∥h∥\norm{\vb{h}}, your Jacobian is wrong. You will verify this in the lab.

The Jacobian determinant

For f:Rn→Rnf: \R^n \to \R^n the Jacobian is square, and its determinant has a geometric interpretation the first interactive already showed in the signed area readout.

Proof

Write J=Jf(a)\mat{J} = \mat{J}_f(\vb{a}) and ε(ρ)=sup⁡x∈Qρ∥Jf(x)−J∥2\eps(\rho) = \sup_{\vb{x} \in Q_\rho}\norm{\mat{J}_f(\vb{x}) - \mat{J}}_2, tending to 00 by continuity of partials. By the mean value inequality in the next section, applied to x↦f(x)−Jx\vb{x} \mapsto f(\vb{x}) - \mat{J}\vb{x} on convex QρQ_\rho, every point of f(Qρ)f(Q_\rho) is at distance at most ε(ρ)n ρ\eps(\rho)\sqrt{n}\,\rho from parallelepiped f(a)+J(Qρ−a)f(\vb{a}) + \mat{J}(Q_\rho - \vb{a}), whose volume is ∣det⁡J∣(2ρ)n\abs{\det\mat{J}}(2\rho)^n. The set of points at that distance from a parallelepiped of diameter O(ρ)O(\rho) has volume ∣det⁡J∣(2ρ)n+O(ε(ρ)) ρn\abs{\det\mat{J}}(2\rho)^n + O(\eps(\rho))\,\rho^n, and dividing by (2ρ)n(2\rho)^n gives the upper bound. Equality when det⁡J≠0\det\mat{J} \ne 0 also needs ff injective near a\vb{a} and f(Qρ)f(Q_\rho) to contain a shrunken parallelepiped; both follow from the inverse function theorem (lesson 10), and the integral version is the change-of-variables formula (lesson 11).

∎

The sign gives orientation. If det⁡J>0\det\mat{J} > 0, the magnifier shows a grid with the same orientation as the original: the rotation from Je1\mat{J}\vb{e}_1 to Je2\mat{J}\vb{e}_2 is counterclockwise. If det⁡J<0\det\mat{J} < 0, the grid is reflected. And the signed area of a small square’s image, measured by the shoelace formula, divided by the square’s area, tends to det⁡J\det\mat{J} with its sign; this is the first interactive’s magenta readout.

Where det⁡J\det\mat{J} changes sign, something no linear map does happens: the map folds. In ripple f(x,y)=(x+Asin⁡y,  y+Asin⁡x)f(x, y) = (x + A\sin y,\; y + A\sin x) the determinant is 1−A2cos⁡xcos⁡y1 - A^2\cos x\cos y. For A<1A < 1 it is always positive and ff is a smooth diffeomorphism of the plane (positive determinant only gives local injectivity; global injectivity follows because ff is the identity plus an AA-Lipschitz perturbation, and ∥f(p)−f(q)∥≥(1−A)∥p−q∥\norm{f(\vb{p}) - f(\vb{q})} \ge (1 - A)\norm{\vb{p} - \vb{q}}); for A>1A > 1 it is negative near points where cos⁡xcos⁡y\cos x \cos y is close to 11, and along curve det⁡J=0\det\mat{J} = 0 the grid folds over itself, so distinct points on either side map to the same image. In one variable this is what x↦x2x \mapsto x^2 does at the origin.

Some useful values to have at hand:

Mapdet⁡J\det\mat{J}Interpretation
polar (r,θ)↦(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (r\cos\theta, r\sin\theta)rr ⁣dx ⁣dy=r ⁣dr ⁣dθ\dd x\dd y = r \dd r\dd\theta
spherical (r,φ,θ)↦r(sin⁡φcos⁡θ,sin⁡φsin⁡θ,cos⁡φ)(r, \varphi, \theta) \mapsto r(\sin\varphi\cos\theta, \sin\varphi\sin\theta, \cos\varphi)r2sin⁡φr^2\sin\varphi ⁣dV=r2sin⁡φ ⁣dr ⁣dφ ⁣dθ\dd V = r^2\sin\varphi\dd r\dd\varphi\dd\theta
z↦z2z \mapsto z^2 in C≅R2\C \cong \R^24∣z∣24\abs{z}^2conformal: J\mat{J} is a rotation times a scaling
layer tanh⁡(Wx+b)\tanh(\mat{W}\vb{x} + \vb{b}) with square W\mat{W}det⁡W∏i(1−hi2)\det\mat{W}\prod_i(1 - h_i^2)saturation squashes volume
two-link armL1L2sin⁡θ2L_1L_2\sin\theta_2singular when extended or folded

The mean value inequality

In one variable, the mean value theorem gives f(y)−f(x)=f′(c)(y−x)f(y) - f(x) = f'(c)(y - x) for some intermediate cc, from which bound ∣f′∣≤M\abs{f'} \le M implies Lipschitz with constant MM. For vector functions the equality is false: f(t)=(cos⁡t,sin⁡t)f(t) = (\cos t, \sin t) satisfies f(2π)−f(0)=0f(2\pi) - f(0) = \vb{0}, while f′(t)=(−sin⁡t,cos⁡t)f'(t) = (-\sin t, \cos t) has norm 11 for every tt, so there is no cc with 0=2πf′(c)\vb{0} = 2\pi f'(c). What survives is the inequality, all that is needed for Lipschitz bounds.

This is the mean value inequality. The proof’s trick is to reduce to a scalar function by projecting onto the right direction, that of f(y)−f(x)f(\vb{y}) - f(\vb{x}).

ProofThe mean value inequality
Prove: If UU is convex and f:U→Rmf: U \to \R^m differentiable, ∥f(y)−f(x)∥≤M∥y−x∥\norm{f(\vb{y}) - f(\vb{x})} \le M\norm{\vb{y} - \vb{x}} with M=sup⁡z∈[x,y]∥Df(z)∥2M = \sup_{\vb{z} \in [\vb{x}, \vb{y}]}\norm{Df(\vb{z})}_2.
0
If f(y)=f(x)f(\vb{y}) = f(\vb{x}) there is nothing to prove. Otherwise let d=y−x\vb{d} = \vb{y} - \vb{x} and γ(t)=x+td\gamma(t) = \vb{x} + t\vb{d} for t∈[0,1]t \in [0, 1].

Step 1 of 5. To which single-variable function do you apply the mean value theorem?

For C1C^1 functions the constant is also best possible: the best Lipschitz constant on an open convex set is exactly sup⁡z∥Df(z)∥2\sup_{\vb{z}}\norm{Df(\vb{z})}_2, because near each z\vb{z} quotients ∥f(z+tu)−f(z)∥/t\norm{f(\vb{z} + t\vb{u}) - f(\vb{z})}/t tend to ∥Df(z)u∥\norm{Df(\vb{z})\vb{u}}, and choosing u\vb{u} as the principal right singular vector attains ∥Df(z)∥2\norm{Df(\vb{z})}_2.

Lipschitz bounds for a network

A second fact is even simpler: if ff is LfL_f-Lipschitz and gg is LgL_g-Lipschitz, g∘fg \circ f is LgLfL_gL_f-Lipschitz, because ∥g(f(x))−g(f(y))∥≤Lg∥f(x)−f(y)∥≤LgLf∥x−y∥\norm{g(f(\vb{x})) - g(f(\vb{y}))} \le L_g\norm{f(\vb{x}) - f(\vb{y})} \le L_gL_f\norm{\vb{x} - \vb{y}}. A layer x↦Wx+b\vb{x} \mapsto \mat{W}\vb{x} + \vb{b} is ∥W∥2\norm{\mat{W}}_2-Lipschitz and componentwise tanh⁡\tanh is 11-Lipschitz (each component is, and square and sum). Thus for a network

f=AL∘tanh⁡∘AL−1∘⋯∘tanh⁡∘A1,Lip⁡(f)≤∏ℓ=1L∥W(ℓ)∥2.f = A_L \circ \tanh \circ A_{L-1} \circ \dots \circ \tanh \circ A_1, \qquad \operatorname{Lip}(f) \le \prod_{\ell=1}^{L}\norm{\mat{W}^{(\ell)}}_2.

This is the bound used by GAN spectral normalization and Lipschitz robustness certificates: if the network is LL-Lipschitz and the winning class’s margin is mm, no perturbation of norm less than m/(2L)m/(\sqrt{2}L) changes the decision. The problem is that it is usually very pessimistic, because each factor ∥W(ℓ)∥2\norm{\mat{W}^{(\ell)}}_2 assumes layer ℓ\ell stretches maximally in exactly the direction most stretched by the preceding layer. The mean value inequality gives the exact value: Lip⁡(f)=sup⁡x∥Jf(x)∥2\operatorname{Lip}(f) = \sup_{\vb{x}}\norm{\mat{J}_f(\vb{x})}_2.

For network 2→2→22 \to 2 \to 2 with J(x)=W2 D(x) W1\mat{J}(\vb{x}) = \mat{W}_2\,\mat{D}(\vb{x})\,\mat{W}_1 and D=diag⁡(tanh⁡′(z))\mat{D} = \diag(\tanh'(\vb{z})) it can be calculated exactly. If W1\mat{W}_1 is invertible, z=W1x+b1\vb{z} = \mat{W}_1\vb{x} + \vb{b}_1 ranges over all R2\R^2 and diagonal (tanh⁡′(z1),tanh⁡′(z2))(\tanh'(z_1), \tanh'(z_2)) ranges over all (0,1]2(0, 1]^2. Function D↦∥W2DW1∥2\mat{D} \mapsto \norm{\mat{W}_2\mat{D}\mat{W}_1}_2 is convex (a norm of an affine function of D\mat{D}), so its supremum on the square occurs at a vertex:

Lip⁡(f)=max⁡(∥W2W1∥2,  ∥w1(2)∥ ∥w~1(1)∥,  ∥w2(2)∥ ∥w~2(1)∥),\operatorname{Lip}(f) = \max\Big(\norm{\mat{W}_2\mat{W}_1}_2,\;\norm{\vb{w}^{(2)}_1}\,\norm{\tilde{\vb{w}}^{(1)}_1},\;\norm{\vb{w}^{(2)}_2}\,\norm{\tilde{\vb{w}}^{(1)}_2}\Big),

where wk(2)\vb{w}^{(2)}_k is column kk of W2\mat{W}_2 and w~k(1)\tilde{\vb{w}}^{(1)}_k row kk of W1\mat{W}_1: vertices diag⁡(1,0)\diag(1, 0) and diag⁡(0,1)\diag(0, 1) correspond to leaving one neuron active, and then W2DW1\mat{W}_2\mat{D}\mat{W}_1 is rank one. The interactive shows all three quantities together.

InteractiveSensitivity of a small network
Input x∈[−3,3]2\vb{x} \in [-3, 3]^2, color =∥J(x)∥2/L= \norm{\mat{J}(\vb{x})}_2 / L
01
Image of unit circle under J(x)\mat{J}(\vb{x})
  • perturbations of x\vb{x} (their image under J\mat{J} is the ellipse)
  • J(x) S1\mat{J}(\vb{x})\,S^1
  • radius LL (actual)
  • radius ∥W2∥∥W1∥\norm{\mat{W}_2}\norm{\mat{W}_1} (bound)
  • unit circle
  • W1x+b1=0\mat{W}_1\vb{x} + \vb{b}_1 = \vb{0}
W1\mat{W}_1 (first layer)
W2\mat{W}_2 (second layer)
J(x)=W2diag⁡(tanh⁡′(z)) W1=[0.380.82−0.410.92]\mat{J}(\vb{x}) = \mat{W}_2 \diag(\tanh'(\vb{z}))\, \mat{W}_1 = \begin{bmatrix} 0.38 & 0.82 \\ -0.41 & 0.92 \end{bmatrix}
z=W1x+b1=(0.64,0.64)\vb{z} = \mat{W}_1\vb{x} + \vb{b}_1 = (0.64, 0.64), b1=(0.4,−0.3)\vb{b}_1 = (0.4, -0.3)
∥J(x)∥2\norm{\mat{J}(\vb{x})}_2 (major semiaxis)1.236
maximum ∥J∥2\norm{\mat{J}}_2 in view1.813
actual Lipschitz L=sup⁡x∥J(x)∥2L = \sup_{\vb{x}} \norm{\mat{J}(\vb{x})}_21.815
bound ∥W2∥2∥W1∥2\norm{\mat{W}_2}_2 \norm{\mat{W}_1}_23.020
overestimate (bound / LL)×1.66
∥W2W1∥2\norm{\mat{W}_2\mat{W}_1}_2 (network without activation)1.815
The supremum is attained where W1x+b1=0\mat{W}_1\vb{x} + \vb{b}_1 = \vb{0} (hollow point): both neurons are in their linear region.
The network is y=W2tanh⁡(W1x+b1)+b2\vb{y} = \mat{W}_2\tanh(\mat{W}_1\vb{x} + \vb{b}_1) + \vb{b}_2. On the left, the input plane colored by ∥J(x)∥2\norm{\mat{J}(\vb{x})}_2; drag x\vb{x}. On the right, ellipse J(x)S1\mat{J}(\vb{x})S^1, whose major semiaxis is maximum amplification of a small perturbation at x\vb{x}. The ellipse never leaves the blue circle (the actual Lipschitz constant), and that stays inside the dashed one (bound ∥W2∥2∥W1∥2\norm{\mat{W}_2}_2\norm{\mat{W}_1}_2). With ‘Neuron-by-neuron cancellation’ the bound exaggerates by 1010. With ‘Fragile cancellation’, ∥W2W1∥2≈0.90\norm{\mat{W}_2\mat{W}_1}_2 \approx 0.90 and yet L≈3.96L \approx 3.96: far from the origin, turning off one neuron breaks cancellation.

The “fragile” example deserves a moment. Without activation, the two layers would cancel: W2W1\mat{W}_2\mat{W}_1 has norm 0.900.90. But the real network is not W2W1\mat{W}_2\mat{W}_1. Where one neuron saturates and the other does not, the Jacobian is w1(2)(w~1(1))⊤\vb{w}^{(2)}_1(\tilde{\vb{w}}^{(1)}_1)\T, with norm ≈3.96\approx 3.96, and that value is attained at no specific point: it is a supremum approached by moving away along a line. In the interactive’s box [−3,3]2[-3, 3]^2, the sampled maximum remains 3.893.89; search in a bounded region approximates it only from below. In large networks the problem is much worse, because x↦∥J(x)∥2\vb{x} \mapsto \norm{\mat{J}(\vb{x})}_2 can have very many local maxima in high dimension, and computing the exact constant is already NP-hard for a two-layer ReLU MLP (Virmaux and Scaman, 2018): certificates therefore settle for upper bounds.

Implementation from scratch

The numerical Jacobian is built column by column, exactly its column interpretation: column jj is velocity of ff along ej\vb{e}_j, estimated by a central difference, (f(x+εej)−f(x−εej))/(2ε)\big(f(\vb{x} + \eps\vb{e}_j) - f(\vb{x} - \eps\vb{e}_j)\big)/(2\eps), with error O(ε2)O(\eps^2). It costs 2n2n evaluations of ff, one pair per input coordinate. Compare with the examples’ analytic Jacobians.

[ ]Numerical Jacobian column by columnBrowser
import numpy as np

def numerical_jacobian(f, x, eps=1e-6):
    """Jacobiano m×n de f en x por diferencias centradas: una columna por coordenada de entrada."""
    x = np.asarray(x, dtype=float)
    m = np.atleast_1d(f(x)).size
    J = np.empty((m, x.size))
    for j in range(x.size):
        e = np.zeros_like(x)
        e[j] = eps
        J[:, j] = (np.atleast_1d(f(x + e)) - np.atleast_1d(f(x - e))) / (2 * eps)
    return J

def polar(q):
    r, t = q
    return np.array([r * np.cos(t), r * np.sin(t)])

def polar_jac(q):
    r, t = q
    return np.array([[np.cos(t), -r * np.sin(t)], [np.sin(t), r * np.cos(t)]])

def softmax(z):
    w = np.exp(z - z.max())                  # versión estable: restar el máximo no cambia p
    return w / w.sum()

def softmax_jac(z):
    p = softmax(z)
    return np.diag(p) - np.outer(p, p)

rng = np.random.default_rng(0)
W, b = rng.standard_normal((3, 4)), rng.standard_normal(3)

def layer(x):
    return np.tanh(W @ x + b)

def layer_jac(x):
    h = layer(x)
    return (1 - h**2)[:, None] * W           # diag(1 − h²) W sin formar la matriz diagonal

casos = [("polares", polar, polar_jac, np.array([2.0, np.pi / 3])),
         ("softmax", softmax, softmax_jac, rng.standard_normal(5)),
         ("capa tanh", layer, layer_jac, rng.standard_normal(4))]
for nombre, f, Jf, x in casos:
    Ja, Jn = Jf(x), numerical_jacobian(f, x)
    print(f"{nombre:10s} forma {Ja.shape}   error máximo {np.abs(Ja - Jn).max():.1e}")

print("det J de polares en (2, π/3):", round(np.linalg.det(polar_jac([2.0, np.pi / 3])), 12))
Js = softmax_jac(casos[1][3])
print("softmax: filas suman", round(np.abs(Js.sum(axis=1)).max(), 15),
      "| simétrica", np.allclose(Js, Js.T), "| autovalores", np.linalg.eigvalsh(Js).round(4))

All three agree with errors of order 10−1010^{-10}, expected from central differences with ε=10−6\eps = 10^{-6}: truncation is of order ε2=10−12\eps^2 = 10^{-12}, and roundoff is machine precision divided by ε\eps, about 10−1010^{-10}. Softmax has, as predicted, rows summing to zero, is symmetric and has a zero eigenvalue; the others are positive.

Now the central statement of the linearization section: error ∥f(a+h)−ℓa(a+h)∥\norm{f(\vb{a} + \vb{h}) - \ell_{\vb{a}}(\vb{a} + \vb{h})} should decrease like ∥h∥2\norm{\vb{h}}^2, and its ratio to ∥h∥2\norm{\vb{h}}^2 should stabilize at 12∥D2f(a)[d,d]∥\tfrac{1}{2}\norm{D^2f(\vb{a})[\vb{d}, \vb{d}]}. For polar coordinates at (2,π/3)(2, \pi/3) and direction d=(0.6,0.8)\vb{d} = (0.6, 0.8) that value is exactly 0.80.8: second derivatives are ∂rθP=(−sin⁡θ,cos⁡θ)\partial_{r\theta}P = (-\sin\theta, \cos\theta) and ∂θθP=−r(cos⁡θ,sin⁡θ)\partial_{\theta\theta}P = -r(\cos\theta, \sin\theta), so

12∥D2P[d,d]∥=12∥2⋅0.48 (−sin⁡θ,cos⁡θ)−0.64⋅2 (cos⁡θ,sin⁡θ)∥=120.962+1.282=0.8,\tfrac{1}{2}\norm{D^2P[\vb{d}, \vb{d}]} = \tfrac{1}{2}\norm{2 \cdot 0.48\,(-\sin\theta, \cos\theta) - 0.64 \cdot 2\,(\cos\theta, \sin\theta)} = \tfrac{1}{2}\sqrt{0.96^2 + 1.28^2} = 0.8,

because the two vectors are orthogonal and unit. For the Gâteaux function, however, error divided by ∥h∥\norm{\vb{h}} does not decrease.

[ ]Linearization error decreases quadraticallyBrowser
def error_lineal(f, Jf, a, d, hs):
    fa, J = f(a), Jf(a)
    return np.array([np.linalg.norm(f(a + h * d) - fa - J @ (h * d)) for h in hs])

hs = np.array([1e-1, 1e-2, 1e-3, 1e-4])
a_pol, d_pol = np.array([2.0, np.pi / 3]), np.array([0.6, 0.8])
x0 = rng.standard_normal(4)
d4 = rng.standard_normal(4)
d4 /= np.linalg.norm(d4)
e_pol = error_lineal(polar, polar_jac, a_pol, d_pol, hs)
e_cap = error_lineal(layer, layer_jac, x0, d4, hs)
print("   ‖h‖    polares: error   error/‖h‖²    capa: error   error/‖h‖²")
for h, e1, e2 in zip(hs, e_pol, e_cap):
    print(f"{h:7.0e}   {e1:12.3e}   {e1 / h**2:9.4f}   {e2:12.3e}   {e2 / h**2:9.4f}")

def f_cubica(p):
    x, y = p
    return np.array([x**3 / (x**2 + y**2)])

u = np.array([1.0, 1.0]) / np.sqrt(2)
print("\nx³/(x² + y²) en el origen con el candidato L(h) = h₁, dirección (1, 1)/√2:")
for h in hs:
    e = abs(f_cubica(h * u)[0] - h * u[0])
    print(f"   ‖h‖ = {h:.0e}   error/‖h‖ = {e / h:.6f}")
print("valor teórico |u₁| u₂² =", round(abs(u[0]) * u[1]**2, 6))

The ratio columns stabilize: 0.80.8 for polar coordinates, as calculated, and a fixed value for the layer. With the cubic function, error divided by ∥h∥\norm{\vb{h}} is 0.3535530.353553 for all h\vb{h}, theoretical value ∣u1∣u22=1/(22)\abs{u_1}u_2^2 = 1/(2\sqrt{2}): no zoom fixes it.

Finally, determinant geometry. Draw the image of a grid by the ripple with A=1.4A = 1.4, coloring each cell by det⁡J\det\mat{J} at its center, and verify that signed area of each image cell, measured with the shoelace formula, agrees with det⁡J\det\mat{J} times cell area.

[ ]A folded grid colored by the Jacobian determinantBrowser
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection

A = 1.4
def onda(p):
    x, y = p
    return np.array([x + A * np.sin(y), y + A * np.sin(x)])

def onda_det(x, y):
    return 1 - A**2 * np.cos(x) * np.cos(y)

def cordon(P):
    """Área con signo de un polígono (fórmula del cordón de zapato)."""
    P = np.asarray(P)
    x, y = P[:, 0], P[:, 1]
    return 0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y)

n = 40
g = np.linspace(-3, 3, n + 1)
h = g[1] - g[0]
polys, dets, areas = [], [], []
for i in range(n):
    for j in range(n):
        # cada lado de la celda muestreado en 4 tramos para que la imagen curva se mida bien
        t = np.linspace(0, 1, 5)[:-1]
        borde = ([(g[i] + h * s, g[j]) for s in t] + [(g[i + 1], g[j] + h * s) for s in t]
                 + [(g[i + 1] - h * s, g[j + 1]) for s in t] + [(g[i], g[j + 1] - h * s) for s in t])
        P = [onda(np.array(c)) for c in borde]
        polys.append(P)
        dets.append(onda_det(g[i] + h / 2, g[j] + h / 2))
        areas.append(cordon(P) / h**2)
dets, areas = np.array(dets), np.array(areas)

fig, axes = plt.subplots(1, 2, figsize=(9.5, 4.4))
X, Y = np.meshgrid(np.linspace(-3, 3, 300), np.linspace(-3, 3, 300))
im = axes[0].pcolormesh(X, Y, onda_det(X, Y), cmap="RdBu", vmin=-3, vmax=3, shading="auto")
axes[0].contour(X, Y, onda_det(X, Y), levels=[0], colors="k", linewidths=1)
axes[0].set_title("det J en el dominio (negro: det J = 0)", fontsize=10)
axes[0].set_aspect("equal")
pc = PolyCollection(polys, array=dets, cmap="RdBu", clim=(-3, 3), edgecolors="k", linewidths=0.15, alpha=0.75)
axes[1].add_collection(pc)
axes[1].autoscale()
axes[1].set_aspect("equal")
axes[1].set_title("imagen de la malla: las celdas rojas salen del revés", fontsize=10)
fig.colorbar(im, ax=axes, shrink=0.8, label="det J")
plt.show()

print("máx |área con signo / área − det J en el centro|:", round(np.abs(areas - dets).max(), 4))
print("fracción de celdas con det J < 0:", round((dets < 0).mean(), 3))
print("¿signo del área = signo de det J en todas las celdas lejos del pliegue?",
      bool(np.all(np.sign(areas[np.abs(dets) > 0.1]) == np.sign(dets[np.abs(dets) > 0.1]))))

Far from the fold, red cells are exactly those whose shoelace area is negative: reversed orientation is a geometric fact visible in the image, not a formula artifact. The maximum discrepancy between relative area and det⁡J\det\mat{J} is small and due to det⁡J\det\mat{J} varying inside each cell: signed area of the image is the average of det⁡J\det\mat{J} over the cell, not its value at the center.

And a network’s Lipschitz bound. With width 1616 and increasing depth, compare the product of spectral norms with the maximum ∥J(x)∥2\norm{\mat{J}(\vb{x})}_2 over random inputs, a lower bound on the real constant: truth lies between them. The network Jacobian is accumulated layer by layer with the tanh⁡\tanh layer formula, J←diag⁡(1−h2) W J\mat{J} \leftarrow \diag(1 - \vb{h}^2)\,\mat{W}\,\mat{J}, the same seen for two layers and justified generally by the chain rule.

[ ]Product bound versus observed sensitivityBrowser
def jacobianos_red(Ws, bs, X):
    """Jacobianos de x ↦ W_L tanh(... tanh(W_1 x + b_1) ...) en un lote X (N × 2): forma N × 2 × 2."""
    N = X.shape[0]
    H = X
    J = np.broadcast_to(np.eye(X.shape[1]), (N, X.shape[1], X.shape[1]))
    for W, b in zip(Ws[:-1], bs):
        H = np.tanh(H @ W.T + b)
        J = (1 - H**2)[:, :, None] * np.einsum("ij,njk->nik", W, J)
    return np.einsum("ij,njk->nik", Ws[-1], J)

rng = np.random.default_rng(1)
d = 16
X = 2 * rng.standard_normal((600, 2))
print("capas ocultas   cota ∏‖W‖₂   máx observado ‖J‖₂   cociente")
for prof in [1, 2, 4, 8]:
    Ws = [1.5 * rng.standard_normal((d, 2)) / np.sqrt(2)]
    Ws += [1.5 * rng.standard_normal((d, d)) / np.sqrt(d) for _ in range(prof - 1)]
    Ws += [rng.standard_normal((2, d)) / np.sqrt(d)]
    bs = [0.1 * rng.standard_normal(d) for _ in range(prof)]
    cota = np.prod([np.linalg.norm(W, 2) for W in Ws])
    obs = np.linalg.norm(jacobianos_red(Ws, bs, X), ord=2, axis=(1, 2)).max()
    print(f"{prof:9d}   {cota:12.2f}   {obs:16.3f}   {cota / obs:10.1f}")

The ratio grows with depth: with one hidden layer the bound exaggerates by factor 22; with eight, by several hundred, almost three orders of magnitude. Part of the gap is that 600600 random inputs do not find the worst point, but most is real: careful search (a dense grid of [−8,8]2[-8, 8]^2 and gradient ascent on ∥J(x)∥2\norm{\mat{J}(\vb{x})}_2 from the best points) raises the eight-layer network’s maximum from 9.09.0 to about 16.516.5, and the bound still exaggerates by more than 300300. The product bound ignores that successive layers’ most-stretched directions do not align, and saturated neurons multiply by nearly zero.

With libraries

For symbolic Jacobians, sympy.Matrix.jacobian directly implements the definition. Use it to confirm the table’s determinants and the softmax matrix formula.

[ ]Symbolic Jacobians with sympyBrowser
import sympy as sp

r, th, ph = sp.symbols("r theta phi", positive=True)
polares = sp.Matrix([r * sp.cos(th), r * sp.sin(th)])
J_pol = polares.jacobian([r, th])
print("J polares =", J_pol, "  det =", sp.simplify(J_pol.det()))

esfericas = sp.Matrix([r * sp.sin(ph) * sp.cos(th), r * sp.sin(ph) * sp.sin(th), r * sp.cos(ph)])
print("det esféricas =", sp.simplify(esfericas.jacobian([r, ph, th]).det()))

x, y = sp.symbols("x y", real=True)
cuadrado = sp.Matrix([x**2 - y**2, 2 * x * y])
print("det de z ↦ z² =", sp.factor(cuadrado.jacobian([x, y]).det()))

z = sp.symbols("z1:4", real=True)
S = sum(sp.exp(zi) for zi in z)
p = sp.Matrix([sp.exp(zi) / S for zi in z])
dif = sp.simplify(p.jacobian(z) - (sp.diag(*p) - p * p.T))
print("J softmax − (diag(p) − p pᵀ) =", dif)

brazo = sp.Matrix([2 * sp.cos(x) + sp.Rational(3, 2) * sp.cos(x + y), 2 * sp.sin(x) + sp.Rational(3, 2) * sp.sin(x + y)])
print("det del brazo (L₁ = 2, L₂ = 3/2) =", sp.simplify(brazo.jacobian([x, y]).det()))

In PyTorch, automatic differentiation calculates exact Jacobians (up to rounding) without finite differences: torch.autograd.functional.jacobian(f, x) and torch.func.jacrev(f)(x), from the torch.func family, return a tensor of shape salida.shape + entrada.shape, numerator convention. The trap is batches: passing a batch of BB inputs at once makes jacobian differentiate each output with respect to every batch input and return an B×m×B×nB \times m \times B \times n tensor almost entirely zero. Usually one wants one Jacobian per example, B×m×nB \times m \times n, which vmap(jacrev(f)) gives.

[ ]Jacobians with PyTorch: shapes, batches and checksLocal GPU
import torch
from torch.autograd.functional import jacobian
from torch.func import jacrev, vmap

torch.manual_seed(0)

def polares_t(q):
    return torch.stack([q[0] * torch.cos(q[1]), q[0] * torch.sin(q[1])])

q = torch.tensor([2.0, torch.pi / 3], dtype=torch.float64)
J = jacobian(polares_t, q)
print("J polares:\n", J, "\ndet =", torch.linalg.det(J).item())

mlp = torch.nn.Sequential(torch.nn.Linear(3, 8), torch.nn.Tanh(), torch.nn.Linear(8, 2)).double()
x = torch.randn(3, dtype=torch.float64)
J1 = jacobian(mlp, x)
J2 = jacrev(mlp)(x)
print("forma (salida, entrada):", tuple(J1.shape), "| jacobian == jacrev:", torch.allclose(J1, J2))

with torch.no_grad():
    W1, b1, W2 = mlp[0].weight, mlp[0].bias, mlp[2].weight
    h = torch.tanh(W1 @ x + b1)
    print("J == W₂ diag(1 − h²) W₁:", torch.allclose(J1, W2 @ torch.diag(1 - h**2) @ W1))

X = torch.randn(5, 3, dtype=torch.float64)
J_lote = jacobian(mlp, X)
J_ej = vmap(jacrev(mlp))(X)
print("jacobian sobre el lote:", tuple(J_lote.shape), "| vmap(jacrev):", tuple(J_ej.shape))
diagonal = torch.stack([J_lote[i, :, i, :] for i in range(5)])
print("los bloques diagonales coinciden:", torch.allclose(diagonal, J_ej),
      "| resto nulo:", J_lote.abs().sum().item() - diagonal.abs().sum().item() < 1e-12)

z = torch.tensor([1000.0, 1001.0, 999.0], dtype=torch.float64)
p = torch.softmax(z, dim=0)
Jsm = jacobian(lambda v: torch.softmax(v, dim=0), z)
print("softmax con logits grandes: diag(p) − ppᵀ ==", torch.allclose(Jsm, torch.diag(p) - torch.outer(p, p)))

sigma = torch.linalg.matrix_norm(J_ej.detach(), ord=2)       # detach: no queremos derivar esto
print("‖J(x)‖₂ de cada ejemplo:", sigma.numpy().round(3))
with torch.no_grad():
    cota = torch.linalg.matrix_norm(mlp[0].weight, ord=2) * torch.linalg.matrix_norm(mlp[2].weight, ord=2)
print("cota ‖W₂‖‖W₁‖ =", round(cota.item(), 3))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Notice three things in the output. The polar Jacobian matches the analytic one and its determinant is 22. For the MLP, shape is (2,3)(2, 3), output by input, and matches W2diag⁡(1−h2)W1\mat{W}_2\diag(1 - \vb{h}^2)\mat{W}_1. And on the batch, jacobian returns shape (5,2,5,3)(5, 2, 5, 3), whose off-diagonal blocks are zero because each output depends only on its own input: vmap(jacrev(...)) directly computes the five useful blocks. The strategy for computing large Jacobians (by columns with JVPs or rows with VJPs) is the subject of the next lesson and the numerical methods module.

Common mistakes

Exercises

NumericPolar determinant
Calculate the Jacobian determinant of (r,θ)↦(rcos⁡θ,rsin⁡θ)(r, \theta) \mapsto (r\cos\theta, r\sin\theta) at r=2r = 2, θ=π/3\theta = \pi/3.
NumericAn entry of the softmax Jacobian
Let z=(0,ln⁡3)\vb{z} = (0, \ln 3) and p=softmax⁡(z)\vb{p} = \softmax(\vb{z}). Calculate Jacobian entry (1,2)(1, 2), ∂p1/∂z2\partial p_1/\partial z_2.
NumericAn arm's determinant
A planar arm has L1=2L_1 = 2, L2=1.5L_2 = 1.5, θ1=40°\theta_1 = 40° and θ2=30°\theta_2 = 30°. Calculate det⁡J(θ)\det\mat{J}(\theta), the Jacobian of gripper position with respect to (θ1,θ2)(\theta_1, \theta_2).
NumericEstimate with linearization
Use polar linearization at (r,θ)=(2,π/3)(r, \theta) = (2, \pi/3) to estimate coordinate xx of (rcos⁡θ,rsin⁡θ)(r\cos\theta, r\sin\theta) at (2.1,π/3+0.05)(2.1, \pi/3 + 0.05). Give the linear estimate, not the exact value.
QuizEvery direction
Let f(x,y)=x3/(x2+y2)f(x, y) = x^3/(x^2 + y^2) with f(0,0)=0f(0, 0) = 0. Which statements are true at the origin?

More than one answer may be correct.

QuizLinear directions, broken function
For g(x,y)=x3y/(x6+y2)g(x, y) = x^3y/(x^6 + y^2) with g(0,0)=0g(0, 0) = 0, all directional derivatives at the origin are 00, so u↦Dug(0)\vb{u} \mapsto D_{\vb{u}}g(\vb{0}) is linear. Is gg differentiable at the origin?
QuizWhat shape is it?
Let f be a PyTorch function mapping tensor x of shape (4,) to one of shape (3,). What shape does torch.autograd.functional.jacobian(f, x) have?
QuizA tenfold overestimate
Let f(x)=W2tanh⁡(W1x+b)f(\vb{x}) = \mat{W}_2\tanh(\mat{W}_1\vb{x} + \vb{b}) with W1=diag⁡(3,0.3)\mat{W}_1 = \diag(3, 0.3), W2=diag⁡(0.3,3)\mat{W}_2 = \diag(0.3, 3) and any b\vb{b}. What is the Euclidean Lipschitz constant of ff?
CodeThe stable softmax Jacobian
Implement softmax_jacobian(z), receiving a vector of logits z of length nn and returning matrix n×nn \times n with entries ∂pi/∂zj\partial p_i/\partial z_j, where p=softmax⁡(z)\vb{p} = \softmax(\vb{z}). Use analytic formula diag⁡(p)−pp⊤\diag(\vb{p}) - \vb{p}\vb{p}\T, not finite differences. The tests compare with finite differences and use logits of order 10001000, for which the naive softmax formula overflows.
import numpy as np

def softmax_jacobian(z):
  z = np.asarray(z, dtype=float)
  p = np.exp(z) / np.exp(z).sum()     # ¿qué pasa si z contiene 1000?
  # devuelve la matriz n×n de derivadas dp_i/dz_j
  pass
Shift+Enter to run

Summary

Key idea
The derivative of f:Rn→Rmf: \R^n \to \R^m at a point is a linear map, the unique one approximating ff with error o(∥h∥)o(\norm{\vb{h}}); the Jacobian is its matrix and only represents something if that map exists. Up close, a differentiable function is its Jacobian: it stretches according to singular values, multiplies volumes by ∣det⁡J∣\abs{\det\mat{J}} and, along a segment, cannot stretch more than the maximum of ∥J∥2\norm{\mat{J}}_2.
  • Fréchet: f(a+h)=f(a)+Df(a)h+o(∥h∥)f(\vb{a} + \vb{h}) = f(\vb{a}) + Df(\vb{a})\vb{h} + o(\norm{\vb{h}}), with Df(a)Df(\vb{a}) linear and unique. It implies continuity and Duf(a)=Df(a)uD_{\vb{u}}f(\vb{a}) = Df(\vb{a})\vb{u}, linear in u\vb{u}.
  • Jacobian: (Jf)ij=∂fi/∂xj(\mat{J}_f)_{ij} = \partial f_i/\partial x_j, shape m×nm \times n (output by input). Rows: component gradients. Columns: velocities along axes.
  • Gâteaux is not enough. x3/(x2+y2)x^3/(x^2+y^2) has every directional derivative but they are nonlinear in u\vb{u}; x3y/(x6+y2)x^3y/(x^6+y^2) has linear ones and is not even continuous.
  • C¹ criterion: continuous partials imply differentiability, by the mean value theorem coordinate by coordinate. Sufficient, not necessary.
  • Linearization: the tangent plane is the graph of f(a)+J(x−a)f(\vb{a}) + \mat{J}(\vb{x} - \vb{a}), with error ≤12M∥h∥2\le \tfrac{1}{2}M\norm{\vb{h}}^2 if ff is C2C^2.
  • Jacobian determinant: signed local volume factor; negative reverses orientation and a sign change marks a fold. Polar: rr; arm: L1L2sin⁡θ2L_1L_2\sin\theta_2.
  • Mean value: for vector functions only the inequality holds, ∥f(y)−f(x)∥≤sup⁡∥Df∥2∥y−x∥\norm{f(\vb{y}) - f(\vb{x})} \le \sup\norm{Df}_2\norm{\vb{y} - \vb{x}}. A network’s Lipschitz constant is sup⁡x∥J(x)∥2\sup_{\vb{x}}\norm{\mat{J}(\vb{x})}_2, and the product of spectral norms is only a bound, often very pessimistic.