The Hessian, multivariable Taylor and local geometry
The Hessian is the Jacobian of the gradient and describes a function's curvature in each direction. This lesson proves Schwarz symmetry, second-order Taylor expansion with remainder, critical-point classification and directional curvature as a Rayleigh quotient, and introduces the Hessian–vector product, enabling curvature calculations for models with millions of parameters without forming the Hessian.
After this lesson you can
- Calculate Hessians and justify symmetry with Schwarz's theorem, knowing the counterexample when continuity fails.
- Write and prove the second-order Taylor expansion in ℝⁿ with Peano and Lagrange remainders.
- Classify critical points using Hessian eigenvalues, including degenerate cases.
- Relate directional curvature, Rayleigh quotient and condition number to gradient-descent behavior.
- Calculate Hessian–vector products without forming the Hessian and estimate the largest eigenvalue of a loss Hessian.
Before you start
- 03GradientJacobian matrixMultivariable chain ruleJacobian-vector productTaylor polynomialTaylor remainderC1 differentiability criterionLinearization and tangent planeLevel sets
- 02Spectral theoremPositive definite matrixRayleigh quotientCourant-Fischer min-max theorem
- 00PyTorch tensorautograd dynamic graphHigher-order gradients and torch.func
Motivation: what the gradient does not say
The gradient gives the best linear approximation to a function at a point and the steepest ascent direction. This is first-order information, and almost everything is trained with it. But no tangent line can answer some questions that arise repeatedly in real work:
- What step size is safe? If the function curves little, long steps are possible; if it curves sharply in some direction, a large step sends you across the valley. Gradient descent’s stability limit is , where is the loss’s largest curvature. If grew during training, a step that worked stops working (the root of the so-called edge of stability).
- Which way should we really go? Newton’s method minimizes a quadratic model of the function at each step and jumps directly to its minimum, . It needs curvature at each point.
- How uncertain is an estimate? The Laplace approximation replaces a posterior with a Gaussian centered at its mode, with covariance the inverse of minus the curvature of the log density. Curvature again.
- How sharp is this minimum? Two minima with the same loss can be wide and narrow. Sharpness is measured by the largest curvature eigenvalue, and its connection with generalization is debated (flatness and generalization).
- Is this a minimum or saddle? A zero gradient is insufficient. Curvature decides what happens around it.
All this is summarized by one object: the matrix of second derivatives, the Hessian. This lesson builds it rigorously. It is the Jacobian of the gradient; symmetric (Schwarz’s theorem, with a counterexample when assumptions fail); gives the second-order Taylor expansion in with explicit remainders; classifies critical points using eigenvalues and explains why gradient descent zigzags. It ends with a trick enabling all of this in models with millions of parameters: the Hessian–vector product, accessing curvature without ever forming the matrix.
Intuition: a smooth function up close is a bowl
In linearization you replace with its tangent plane. The plane gets value and slope right but misses how bends. The next natural step is a degree-2 polynomial also matching curvature:
It is a bowl, saddle or valley depending on the signs of ‘s eigenvalues. The figure overlays that model on three test surfaces and measures how far it can be trusted.
Three things deserve attention. The linear model resembles only in a small region and collapses where the gradient is nearly zero (the tangent plane is almost horizontal and says nothing about how curves). The quadratic model gains a much larger region almost everywhere. And that region is not a disk: in narrow Rosenbrock valleys it stretches along the valley and shrinks across it because curvature changes quickly in the steep direction. The lesson explains why: quadratic model error is controlled by the third derivative, becoming an exact bound in Taylor’s theorem.
Higher-order derivatives and the Hessian
Let with open. If has partial derivatives and these have partial derivatives in turn, write
Reading order is right to left: differentiate first with respect to and then . We call class if all partial derivatives through order 2 exist and are continuous.
It is literally the gradient’s Jacobian. Function has components , and its Jacobian matrix has at position derivative , that is, . Schwarz’s theorem (below, whose proof uses nothing following in this section) says for functions, so the gradient Jacobian is the Hessian. This is the most useful way to think in machine learning, because it connects everything with the familiar chain rule: the Hessian answers “how much does the gradient change when I move slightly?”, the linear map taking displacement to gradient change .
A lemma used three times
To discuss curvature along a direction, restrict to a line: . The chain rule gives the first two derivatives and, once is differentiable, the third equality below.
Proof
The first equality is the chain rule for , whose derivative is . Function is the composition of with that line; its Jacobian is (by Schwarz) and the chain rule gives the third equality. Differentiating the first, , which is because a scalar equals its transpose. Continuity of follows from that of .
∎The third equality seeds the lesson’s final topic: the Hessian–vector product is a directional derivative of the gradient, allowing computation without forming . The second will be directional curvature.
Examples to have at hand
Symmetry: Schwarz’s theorem
The examples’ Hessians were symmetric, and not by chance. Calculations with and agree whenever is reasonably smooth. The result is Schwarz’s theorem (also Clairaut’s or Young’s), and both its proof and what happens when it fails are worth knowing.
Proof
Two variables suffice; hold the others fixed. Write and for and , and . For small nonzero consider the double quotient
Let . Then . By the mean value theorem, there is between and with . Applying the mean value theorem again to differentiable , there is between and with . Hence
The numerator of is symmetric in the roles of and . Repeating with gives with other intermediate points. As , intermediate points tend to and, by continuity of both second derivatives, .
∎The proof shows where continuity is used: to pass from the value of at intermediate points to its value at . If mixed derivatives merely existed without continuity, quotient would still be the same for both differentiation orders, but might lack a double limit as , and the two differentiation orders are two different ways (two iterated limits) of approaching that point.
The counterexample
Let if and . In polar coordinates, : a four-lobed saddle. Away from the origin it is . At the origin, calculating directly,
Differentiating those linear functions: and . Both mixed derivatives exist at the origin and do not agree. More: is class (its gradient exists and is continuous), so even class is insufficient.
The cause is what the proof predicts. Away from the origin both mixed derivatives equal
a function only of angle (homogeneous of degree 0). On axis () it equals ; on axis () it equals ; at it equals , and takes every value between and . It has no limit as , so second derivatives are not continuous at the origin, the missing assumption.
In , symmetry has a spectral consequence used constantly. Since is real symmetric, the spectral theorem says it has real eigenvalues and an orthonormal eigenvector basis. This makes “directions of maximum and minimum curvature” meaningful.
Second-order Taylor in
The multivariable Taylor proof is a good example of a general technique: reduce to one variable by restriction to a segment. The result, with three remainder versions, is the second-order multivariable Taylor expansion.
Proof
Let for . By the preceding section’s lemma, , with and .
(1) The single-variable Taylor theorem with Lagrange remainder gives for some . Substitute the derivatives to obtain the formula.
(2) Let , tending to 0 with by continuity of . Subtracting from formula (1),
(3) With the single-variable function’s integral remainder, . By assumption, . Since , error is at most .
∎Each version has a use. Peano’s remainder is used in local proofs (critical-point classification below). Bound (3) is quantitative, making algorithms work: quadratic-model error grows like the cube of distance, with constant proportional to how much curvature changes. This explains the figure above and underlies trust-region methods: trust the quadratic model inside a disk and adapt its radius to how well prediction holds.
Higher orders
The same argument, using a single-variable expansion to order , gives
with multi-indices . The order-3 term is , where is a symmetric tensor (by repeated application of Schwarz’s theorem). In two variables, : the factors 3 are symmetry in action. Growth is explosive ( entries, and generally), so order 2 is the last routinely used in optimization.
Critical points and local geometry
A point is critical (or stationary) if . At a critical point the Taylor model loses its linear part, leaving
where are eigenvalues of and the coordinates of in the orthonormal eigenvector basis. All local geometry lies in the signs of : the weighted sum of squares is a bowl if all positive, an inverted bowl if all negative, and a saddle if both signs occur.
This is critical-point classification. The number of negative Hessian eigenvalues at a nondegenerate critical point is its index: 0 for a minimum, for a maximum and any intermediate value for a saddle.
Proof
For each unit direction , the Peano expansion at gives .
(1) If were a local minimum with for some , the right side would be negative for small , and , a contradiction. The maximum case is symmetric.
(3) Let and be unit eigenvectors with . Then and for small . Every neighborhood contains points with values above and below .
Part (2) is most delicate: checking lines is insufficient, all directions must be controlled at once; this is the first proof exercise below. Part (4) is illustrated by the following examples.
∎When the Hessian does not decide
Compare these functions at the origin, where all have zero gradient:
| What the origin is | ||
|---|---|---|
| strict minimum | ||
| saddle: rises in , falls in | ||
| neither minimum nor maximum: on axis , changes sign | ||
| monkey saddle (three hills and three valleys) |
The first three have the same Hessian and different behavior. In the null direction (), the quadratic term disappears and a higher-order term decides: , or . The last, , has zero Hessian: the quadratic model is identically zero and sign is distributed among six sectors.
Two facts complete the picture, without proof here. First, a critical point with nonsingular Hessian is isolated: since is the Jacobian of , the inverse function theorem makes injective near and there are no other critical points in a neighborhood. Second, Morse’s lemma says that for of class , is locally, after a smooth coordinate change, exactly with as many minus signs as the index.
In deep learning, degenerate situations are the norm. An overparameterized model has parameter-space directions that do not change the represented function, with zero curvature. Thus network-loss Hessians at points reached by training have many nearly zero eigenvalues, and saddle-point theory (how to escape them, the strict saddle property) matters more than isolated-minimum theory.
Directional curvature and the Rayleigh quotient
The second derivative of the function restricted to a line measures how much curves in that direction.
This is the Hessian’s Rayleigh quotient. A naming warning: it is the second derivative of the profile of along the line, not the geometric curvature of curve , which is . They agree when slope in that direction is zero (), and thus in all directions at once at a critical point; there is also the normal curvature of surface in direction (Euler’s theorem on principal curvatures).
Proof
By orthonormality, and , an average of the with weights summing to 1. An average lies between the minimum and maximum of its values and reaches the maximum when all weight is on the maximizing index.
∎In the plane, with at angle , this is : in polar coordinates it draws a “peanut” touching the circle of radius at and narrowing to at .
Why gradient descent zigzags
Let with positive definite, the model of any function near a nondegenerate minimum. Gradient descent with step is . In the eigenvector basis it decouples: component is multiplied at each step by .
- Stability. It converges from every starting point if and only if for every , that is, . With the highest-curvature component is amplified and the method diverges.
- Zigzag. If , factor is negative: that component changes sign each step, so the iterate bounces from one valley wall to the other.
- Slowness. The flattest component advances with factor , very close to 1 if . With the largest stable step (), that factor is , where is the Hessian’s condition number.
- Best step. Minimizing over balances both extremes: , giving and contraction factor .
Factor is a bound that no constant step can improve. For the Rosenbrock function at its minimum, (you calculate it in an exercise), so and steps are needed just to reduce error a thousandfold, even with the optimal step. This slowness is what second-order and momentum methods try to solve.
The Hessian–vector product
With parameters, the Hessian has entries. For these are numbers, about 4 TB in float32, while one parameter vector occupies 4 MB. Forming is impossible in models of that size, yet almost everything we need from curvature (largest eigenvalue, an approximate Newton step, the effect of on a vector) can be computed using one operation: multiply by a vector.
That formula says two things implementable in two ways.
- Approximate, with two gradients. Central difference approximates with error (plus roundoff, growing like ) and needs only a gradient function. This is the first implementation and what you will build from scratch.
- Exact, with automatic differentiation. is the Jacobian–vector product (JVP) of function in direction . In an automatic differentiation framework this is “forward over reverse”: compute the gradient with backpropagation and propagate a tangent forward through that calculation. The “reverse over reverse” alternative differentiates scalar with respect to and gives the same result because when does not depend on . This is Pearlmutter’s trick (1994), presented as an operator on the gradient computation itself.
Cost is the reason for all this. A gradient costs a few times evaluating (the cheap gradient principle), and an exact HVP costs a few times a gradient, with a constant factor independent of . Memory is that of vectors and gradient intermediates: , not . A model whose curvature matrix fits on no disk admits thousands of HVPs. This idea of treating a matrix as a vector-to-vector function (matrix-free operators) underlies Krylov methods.
HVPs yield:
- the largest eigenvalue via power iteration (which converges to the largest-magnitude eigenvalue: near a minimum it is , but with strongly negative curvatures it may be ; the Rayleigh quotient at each step estimates , improving with the square of ratio ), or via Lanczos, which converges much sooner;
- the Newton approximation solved by conjugate gradients, requiring only HVPs (Newton–CG);
- the effect of on a vector, needed by influence functions;
- the Hessian trace with Hutchinson’s estimator (randomized trace estimation);
- the full spectrum of large networks: Ghorbani, Krishnan and Xiao (2019, arXiv:1901.10159) estimated deep-network Hessian eigenvalue density with Lanczos and only HVPs, describing a main body of eigenvalues near zero and a few much larger outliers.
Implementation from scratch
First, the preceding section’s tools programmed in NumPy from a gradient. The test problem is regularized logistic regression with examples and features at different scales, so the Hessian is ill-conditioned and power iteration has work to do. Since is small, we can also calculate the analytic Hessian and compare.
import numpy as np
rng = np.random.default_rng(0)
n, d = 400, 30
X = rng.normal(size=(n, d)) * np.linspace(2.0, 0.2, d) # características con escalas distintas
w_true = rng.normal(size=d)
y = (X @ w_true + 2.0 * rng.normal(size=n) > 0).astype(float)
lam = 1e-3
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def loss(w):
z = X @ w
return np.mean(np.logaddexp(0.0, z) - y * z) + 0.5 * lam * w @ w
def grad(w):
return X.T @ (sigmoid(X @ w) - y) / n + lam * w
def hess(w): # analítico: solo para comparar
p = sigmoid(X @ w)
return (X.T * (p * (1 - p))) @ X / n + lam * np.eye(d)
def hvp_fd(grad_f, x, v, eps=1e-5):
"""H v por diferencias centradas de gradientes: dos gradientes, ningún hessiano."""
return (grad_f(x + eps * v) - grad_f(x - eps * v)) / (2 * eps)
def hessian_fd(grad_f, x, eps=1e-5):
"""Hessiano completo columna a columna: d productos hessiano-vector con los vectores de la base."""
m = x.size
H = np.column_stack([hvp_fd(grad_f, x, np.eye(m)[:, j], eps) for j in range(m)])
return (H + H.T) / 2
def power_iteration_hessian(grad_f, x, iters=200, seed=0):
"""Autovalor de mayor módulo del hessiano en x usando solo HVPs, con su cociente de Rayleigh."""
v = np.random.default_rng(seed).normal(size=x.size)
v /= np.linalg.norm(v)
historia = []
for _ in range(iters):
Hv = hvp_fd(grad_f, x, v)
historia.append(v @ Hv) # cociente de Rayleigh
v = Hv / np.linalg.norm(Hv)
return historia[-1], v, np.array(historia)
# el mínimo, por Newton (aquí sí podemos permitirnos el hessiano: d = 30)
w = np.zeros(d)
for it in range(30):
g = grad(w)
if np.linalg.norm(g) < 1e-12:
break
w -= np.linalg.solve(hess(w), g)
print("Newton:", it, "iteraciones, |grad| =", f"{np.linalg.norm(grad(w)):.1e}", " f =", round(loss(w), 6))
H_exacto = hess(w)
ev = np.linalg.eigvalsh(H_exacto)
print("autovalores exactos: min =", f"{ev[0]:.3e}", " max =", f"{ev[-1]:.4f}", " condición =", f"{ev[-1] / ev[0]:.1f}")
print("hessiano por diferencias, error máximo:", f"{np.abs(hessian_fd(grad, w) - H_exacto).max():.1e}")
lmax, v, historia = power_iteration_hessian(grad, w, iters=100)
print("potencia con HVP: lmax =", f"{lmax:.6f}", " error =", f"{abs(lmax - ev[-1]):.1e}", " |l2/l1| =", round(ev[-2] / ev[-1], 3))
for k in (5, 10, 20, 50, 100):
print(f" iteración {k:3d}: error del autovalor = {abs(historia[k - 1] - ev[-1]):.2e}")Three observations from the output. The finite-difference Hessian agrees with the analytic one to maximum error , because each column is an HVP and central-difference error is order plus roundoff. Power iteration converges, but slowly: ratio is close to 1, and the Rayleigh quotient converges like , so eventually error is multiplied by each iteration (initially it decreases faster while other eigenvalues matter). Most importantly, power_iteration_hessian never builds a matrix; it receives a grad_f function and works entirely with vectors, so would work equally with .
Now critical-point analysis. Himmelblau’s function, , is the classic test because it has four minima, four saddles and one local maximum. Newton on converges to any critical point without distinguishing type, so run it from many points and classify each result by Hessian eigenvalues.
import numpy as np
def f_h(p):
x, y = p
return (x * x + y - 11) ** 2 + (x + y * y - 7) ** 2
def grad_h(p):
x, y = p
return np.array([4 * x * (x * x + y - 11) + 2 * (x + y * y - 7),
2 * (x * x + y - 11) + 4 * y * (x + y * y - 7)])
def hess_h(p):
x, y = p
return np.array([[12 * x * x + 4 * y - 42, 4 * x + 4 * y],
[4 * x + 4 * y, 4 * x + 12 * y * y - 26]])
def newton_critico(p, iters=80):
for _ in range(iters):
try:
paso = np.linalg.solve(hess_h(p), grad_h(p))
except np.linalg.LinAlgError:
return None
p = p - paso
if not np.all(np.isfinite(p)) or np.abs(p).max() > 1e3:
return None
if np.linalg.norm(paso) < 1e-13:
break
return p if np.linalg.norm(grad_h(p)) < 1e-9 else None
rng = np.random.default_rng(3)
encontrados = []
for _ in range(400):
p = newton_critico(rng.uniform(-6, 6, size=2))
if p is not None and not any(np.linalg.norm(p - q) < 1e-6 for q in encontrados):
encontrados.append(p)
def tipo(ev):
if ev[0] > 0:
return "mínimo"
if ev[-1] < 0:
return "máximo"
return "silla"
filas = sorted(encontrados, key=lambda p: f_h(p))
print(f"{len(filas)} puntos críticos\n x y f(x,y) autovalores del hessiano tipo")
cuentas = {"mínimo": 0, "silla": 0, "máximo": 0}
for p in filas:
ev = np.linalg.eigvalsh(hess_h(p))
t = tipo(ev)
cuentas[t] += 1
print(f"{p[0]:8.4f} {p[1]:8.4f} {f_h(p):10.4f} {ev[0]:8.3f} {ev[1]:8.3f} {t}")
print(cuentas)Results agree with theory: four minima with and positive-definite Hessian, four saddles with one negative and one positive eigenvalue, and a local maximum with both negative. Notice Newton “finds” saddles and the maximum as easily as minima because it seeks gradient zeros rather than low values of : pure Newton is not a minimization method. Practical methods (damped Newton, trust regions) correct this by looking at eigenvalue signs.
Finally, the finite-difference step tradeoff. Central-difference HVP error has two terms: truncation, proportional to due to the third derivative, and roundoff, proportional to , where is double-precision unit roundoff and gradient roundoff is amplified by division by . The sum’s minimum is at , with relative error of order .
import numpy as np
import matplotlib.pyplot as plt
v = np.random.default_rng(1).normal(size=d) # d, w, grad, H_exacto vienen de la celda anterior
ref = H_exacto @ v
epsilons = 10.0 ** np.arange(-1, -13.5, -0.5)
errores = np.array([np.linalg.norm(hvp_fd(grad, w, v, e) - ref) / np.linalg.norm(ref) for e in epsilons])
i = int(np.argmin(errores))
print(f"mejor eps = {epsilons[i]:.1e}, error relativo = {errores[i]:.1e}")
for e, r in zip(epsilons[::2], errores[::2]):
print(f" eps = {e:.0e} error relativo = {r:.2e}")
plt.loglog(epsilons, errores, "o-", label="error medido")
plt.loglog(epsilons, errores[0] * (epsilons / epsilons[0]) ** 2, "--", color="gray", label="pendiente 2: truncamiento")
plt.loglog(epsilons, errores[-1] * (epsilons[-1] / epsilons), ":", color="gray", label="pendiente -1: redondeo")
plt.xlabel("eps"); plt.ylabel("error relativo del HVP"); plt.legend(); plt.show()The graph is V-shaped on logarithmic axes: truncation dominates on the right (slope 2), roundoff on the left (slope ). Too small an does not improve precision: it worsens it. In float32, with , the optimum is near and best possible error is order , another reason to use exact automatic-differentiation HVPs when training in reduced precision.
The professional version
In an automatic differentiation framework everything is calculated exactly without choosing . PyTorch offers three routes and all give the same result: torch.func.hessian (full Hessian, only for small models), jvp(grad(loss), ...) (forward over reverse, Pearlmutter’s HVP) and double torch.autograd.grad with create_graph=True (reverse over reverse, from higher-order differentiation and autograd’s dynamic graph). With a SciPy LinearOperator calling the HVP, extreme eigenvalues are obtained by Lanczos without forming the matrix. The cell runs locally because it uses PyTorch.
import numpy as np
import torch
from torch.func import grad, jvp, hessian
from scipy.sparse.linalg import LinearOperator, eigsh
torch.manual_seed(0)
torch.set_default_dtype(torch.float64)
n, d_in, d_h = 256, 5, 16
X = torch.randn(n, d_in)
y = torch.tanh(X @ torch.randn(d_in)) + 0.1 * torch.randn(n)
P = d_h * d_in + d_h + d_h + 1 # 113 parámetros de un MLP 5 -> 16 -> 1
def loss(theta):
W1 = theta[: d_h * d_in].view(d_h, d_in)
b1 = theta[d_h * d_in : d_h * d_in + d_h]
w2 = theta[d_h * d_in + d_h : d_h * d_in + 2 * d_h]
b2 = theta[-1]
pred = torch.tanh(X @ W1.T + b1) @ w2 + b2
return 0.5 * ((pred - y) ** 2).mean()
theta = 0.5 * torch.randn(P)
g = grad(loss)
for _ in range(4000): # descenso por gradiente hasta un punto casi estacionario
theta = theta - 0.2 * g(theta)
print("pérdida:", round(float(loss(theta)), 6), " |grad|:", f"{float(g(theta).norm()):.1e}")
def hvp_exacto(theta, v): # modo directo sobre modo inverso: jvp de la función gradiente
return jvp(g, (theta,), (v,))[1]
def hvp_inverso(theta, v): # inverso sobre inverso: grad de (grad f . v)
th = theta.clone().requires_grad_(True)
(gr,) = torch.autograd.grad(loss(th), th, create_graph=True)
(hv,) = torch.autograd.grad(gr @ v, th)
return hv
H = hessian(loss)(theta) # el hessiano completo: 113 x 113, solo para comparar
v = torch.randn(P)
Hv = H @ v
rel = lambda a: float((a - Hv).norm() / Hv.norm())
eps = 1e-5
fd = (g(theta + eps * v) - g(theta - eps * v)) / (2 * eps)
print("simetría del hessiano:", f"{float((H - H.T).abs().max()):.1e}")
print("jvp(grad):", f"{rel(hvp_exacto(theta, v)):.1e}", " doble grad:", f"{rel(hvp_inverso(theta, v)):.1e}", " diferencias:", f"{rel(fd):.1e}")
op = LinearOperator((P, P), dtype=np.float64,
matvec=lambda u: hvp_exacto(theta, torch.from_numpy(np.asarray(u, dtype=np.float64).ravel())).numpy())
lmax = eigsh(op, k=1, which="LA", return_eigenvectors=False)[0]
lmin = eigsh(op, k=1, which="SA", return_eigenvectors=False)[0]
ev = np.linalg.eigvalsh(H.numpy())
print(f"eigsh (solo HVPs): lmax = {lmax:.6f} lmin = {lmin:.3e}")
print(f"eigvalsh (completo): lmax = {ev[-1]:.6f} lmin = {ev[0]:.3e}")
print("autovalores < -1e-3:", int((ev < -1e-3).sum()), " |autovalor| < 1e-3:", int((np.abs(ev) < 1e-3).sum()), " de", P)
print("los cinco mayores:", np.round(ev[-5:], 4))npm run lab and open the connection link.Correspondence with what you programmed by hand is direct: jvp(g, ...) is hvp_fd with the exact derivative instead of the difference, double autograd.grad is the same product viewed as gradient of , and eigsh with a LinearOperator does what power_iteration_hessian did, but with Lanczos, converging in far fewer iterations. Also notice the spectrum at this nearly stationary point: of 113 eigenvalues, 72 have magnitude below and 2 are negative by more than , against a maximum of 3.43. There are many nearly flat directions, as critical-point analysis anticipated, and the Hessian is not positive semidefinite: there are two slightly negative-curvature directions, so gradient descent has stopped not near a well-formed minimum but on a nearly flat plateau with saddle features (and a small but nonzero gradient).
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What is the first step?
Step 1 of 3. How do you differentiate ?
grad_f(x) function returning the gradient. hvp_fd(grad_f, x, v, eps=1e-5) returns by central differences, calling grad_f exactly twice (tests count calls). power_iteration_hessian(grad_f, x, iters=300, eps=1e-5, seed=0) returns (lam, v): the Hessian's largest-magnitude eigenvalue with its sign, estimated by the Rayleigh quotient, and its unit eigenvector. Start from a random vector with np.random.default_rng(seed), normalize it, and at each iteration compute the HVP with hvp_fd, update lam with the Rayleigh quotient and renormalize. Do not build the Hessian.import numpy as np
def hvp_fd(grad_f, x, v, eps=1e-5):
"""H(x) v por diferencias centradas de gradientes."""
# tu código
return np.zeros_like(x)
def power_iteration_hessian(grad_f, x, iters=300, eps=1e-5, seed=0):
"""Autovalor de mayor módulo del hessiano en x (con signo) y su vector propio, solo con HVPs."""
# tu código
return 0.0, np.zeros_like(x)Summary
- Hessian is the Jacobian of . It is symmetric if (Schwarz); without second-derivative continuity this can fail, as in , where the mixed derivatives at the origin are and .
- Second-order Taylor in : , with (Peano), (Lagrange) and if is -Lipschitz. Quadratic-model error grows as the cube of distance.
- At a critical point, gives a strict minimum, a strict maximum, and an indefinite Hessian a saddle. A singular semidefinite Hessian gives no conclusion: , and have the same .
- Curvature in direction is Rayleigh quotient , between and . On a quadratic, gradient descent is stable if , zigzags if , and its best contraction factor is .
- Hessian–vector product costs a small multiple of a gradient (Pearlmutter), with linear memory. For finite differences the optimal step is in double precision; automatic differentiation is exact.
- HVPs calculate the largest eigenvalue (power, Lanczos), approximate Newton steps (conjugate gradients) and products with , without forming the Hessian. The Hessian is not Gauss–Newton or Fisher: it can have negative curvature.