Module contents
Lesson 1 of 27Review 60 min

Formulating optimization problems and recognizing optima

Formulate optimization problems and derive existence and optimality conditions.

After this lesson you can

  • Write a standard-form optimization problem, identifying decision variable, objective, constraints, feasible set and optimal value.
  • Prove existence of a global minimizer using coercivity and compact sublevel sets.
  • Derive necessary first- and second-order conditions from Taylor expansion.
  • Classify critical points using Hessian eigenvalues and recognize degenerate cases.

Before you start

Motivation: one problem in four disguises

Training a network, calibrating a simulator, allocating a budget and planning a robot’s motion appear to be four disciplines. Written mathematically, they are the same sentence:

  • Train a model. Choose parameters θ\theta minimizing empirical loss R^(θ)=1n∑iℓ(fθ(xi),yi)\hat R(\theta) = \tfrac1n\sum_i \ell(f_\theta(\vb{x}_i), y_i), sometimes with a regularization term.
  • Calibrate a simulator. Choose physical parameters p\vb{p} bringing simulator output s(p)\vb{s}(\vb{p}) close to measurements d\vb{d}, minimizing ∥s(p)−d∥2\norm{\vb{s}(\vb{p}) - \vb{d}}^2 with each parameter within an admissible range.
  • Allocate resources. Choose portfolio weights w\vb{w} minimizing risk w⊤Σw\vb{w}\T\mat{\Sigma}\vb{w} subject to summing to 1, expected return exceeding a threshold and no negative positions.
  • Control a robot. Choose a sequence of motor torques minimizing trajectory cost subject to the dynamics and each motor’s maximum torque.

In all four cases there is something to decide (parameters, weights, torques), a number to measure (loss, mismatch, risk, cost) and rules that cannot be skipped (ranges, budget, dynamics). Mathematical optimization studies that structure, regardless of application domain. This entire module builds on it: gradient methods, Newton, stochastic gradients and adaptive optimizers used to train modern models are ways to solve that single problem.

Before solving it, this lesson rigorously answers three prior questions, because later algorithms assume them:

  1. What exactly is an optimization problem? The vocabulary to write it unambiguously, and what can go wrong (no feasible solutions, an unbounded objective, or a best value that is not attained).
  2. Does a solution exist? Many training failures, such as weights growing without bound, are symptoms of a problem with no minimum.
  3. How do you recognize an optimum? Without constraints the answer is local and uses gradient and Hessian. You will learn what they say and, equally importantly, when they are silent.

Standard form: a problem’s vocabulary

Three nuances of that definition cause almost all misunderstandings.

Optimal value is an infimum, not a minimum. p⋆p^\star is always defined (as an element of [−∞,+∞][-\infty, +\infty]), but X⋆\mathcal{X}^\star can be empty. A problem can have an optimal value and no solution: inf⁡x>01x=0\inf_{x > 0} \tfrac1x = 0 is attained at no positive xx. Thus distinguish “the optimal value is p⋆p^\star” from “the problem has a solution.”

Four outcomes are possible. Depending on f0f_0 and F\mathcal{F}, the problem is:

OutcomeWhat happensp⋆p^\starX⋆\mathcal{X}^\star
SolvableThe best value is attainedfinitenonempty
Infimum not attainedValues approach p⋆p^\star without reaching itfiniteempty
Unboundedf0f_0 decreases arbitrarily over F\mathcal{F}−∞-\inftyempty
InfeasibleNo point satisfies the constraints+∞+\inftyempty

Feasibility is part of the problem. There is no “best x\vb{x}” without saying which points compete. Changing the feasible set changes the problem, even with the same f0f_0 formula. The next figure makes this concrete: with one objective, changing constraints moves from solvable to infeasible, unbounded or an escaping infimum.

InteractiveInside the problem
x*
  • feasible set
  • contours of ff
  • level through the optimum
Objective
Direction
Optimal value p⋆p^\star1.146
x⋆\vb{x}^\star(1.15, 0.60)
Optimum attained: p⋆=1.146p^\star = 1.146 at x⋆=(1.152,0.603)\vb{x}^\star = (1.152, 0.603).
Choose an objective (squared distance to a point c\vb{c} or linear function g⊤x\vb{g}\T\vb{x}) and a feasible set; drag c\vb{c} or arrow g\vb{g}. Gray curves are level sets of ff and blue passes through the optimum: the optimum is where the lowest level curve still touching the feasible set grazes it. Switch from a closed to an open ball: the infimum remains but the point disappears. Switch to maximization: unconstrained the problem is unbounded, and on the ball the maximum is the farthest point. With a line, rotate g\vb{g} parallel to its normal: what happens to ff along it? With the nonconvex ball exterior, place c\vb{c} inside: the optimum jumps to the boundary, and if c\vb{c} is the center the whole circumference is optimal. With two incompatible constraints, what optimal value does convention inf⁡∅=+∞\inf\varnothing = +\infty give?

Transformations that preserve the problem

Standard form is an interchange format: algorithms and solvers expect it, and almost any real problem can be put into it. These are common transformations, what they preserve and what they do not.

  • Maximize. max⁡f0\max f_0 is min⁡(−f0)\min(-f_0): solutions are the same and the optimal value changes sign, pmax⁡⋆=−pmin⁡⋆p^\star_{\max} = -p^\star_{\min}. In the figure, the “maximum value of ff” is the opposite of p⋆p^\star.
  • Rescale the objective. If φ\varphi is strictly increasing, minimizing φ(f0)\varphi(f_0) has the same solutions with another optimal value. Thus minimize ∥Xw−y∥2\norm{\mat{X}\vb{w} - \vb{y}}^2 rather than ∥Xw−y∥\norm{\mat{X}\vb{w} - \vb{y}} (the former is differentiable everywhere; the latter is not exactly where residual vanishes), or −log⁡∏ip(yi∣xi)-\log \prod_i p(y_i \given \vb{x}_i) rather than the product: maximum likelihood and minimum negative log likelihood coincide.
  • One equality is two inequalities. h(x)=0h(\vb{x}) = 0 is equivalent to h(x)≤0h(\vb{x}) \le 0 and −h(x)≤0-h(\vb{x}) \le 0. The feasible set is the same, but constraint qualifications guaranteeing Lagrange multipliers fail at every feasible point because the gradients of both inequalities oppose one another and no direction strictly improves both; the multiplier also ceases to be unique, clouding its interpretation in the duality lesson. Keep the equality.
  • Slack variables. fi(x)≤0f_i(\vb{x}) \le 0 is equivalent to fi(x)+si=0f_i(\vb{x}) + s_i = 0 with si≥0s_i \ge 0. It converts inequalities into equalities at the cost of sign-constrained variables.
  • Epigraph form. min⁡f0(x)\min f_0(\vb{x}) is equivalent to min⁡x,tt\min_{\vb{x}, t} t subject to f0(x)≤tf_0(\vb{x}) \le t: the objective becomes linear and all complexity moves to constraints. This is used extensively in convex programming.
  • Implicit constraints. A constrained problem is unconstrained for f0+IFf_0 + I_{\mathcal{F}}, where IF(x)=0I_{\mathcal{F}}(\vb{x}) = 0 on F\mathcal{F} and +∞+\infty outside. Lesson 11’s proximal methods use this idea.

Local and global minima

An optimizer’s goal is the best point in all of F\mathcal{F}. But most algorithms can only compare a point with its neighbors, giving rise to two notions.

Four important observations:

  1. Only feasible neighbors count. In a constrained problem a boundary point of F\mathcal{F} can be a local minimum even if f0f_0 falls outside the set. Minimizing xx on [0,1][0, 1] has its minimum at x=0x = 0, where the derivative is 1≠01 \neq 0.
  2. Global implies local, and the converse is false: f(x)=x4−3x2+xf(x) = x^4 - 3x^2 + x has two valleys, the right one a local but not global minimum. In general there is no efficient test certifying a local minimum as global: one fact separating easy from hard problems.
  3. There is a class where the distinction disappears. In convex problems, studied from lesson 3, every local minimum is global: if a feasible y\vb{y} had f0(y)<f0(x⋆)f_0(\vb{y}) < f_0(\vb{x}^\star), their segment would be feasible and convexity puts f0f_0 below the chord, strictly below f0(x⋆)f_0(\vb{x}^\star) even arbitrarily close to x⋆\vb{x}^\star. Convexity makes optimization tractable.
  4. A global minimum need not be unique. With a flat valley, X⋆\mathcal{X}^\star is a whole line; with symmetry (permuting hidden-layer neurons), X⋆\mathcal{X}^\star contains copies of the same model. Strict or strong convexity gives uniqueness (lesson 3).

Existence: when there is a minimum

The most dangerous case above is the table’s second row: no solution but finite optimal value. Algorithms do not warn: they iterate, function value decreases, and parameters grow without bound. You need to recognize it in advance.

The starting point is a familiar calculus result. The extreme value theorem says a continuous function on a nonempty compact set (closed and bounded in Rn\R^n) attains its minimum. But the feasible set is rarely compact: Rn\R^n is not. The way out is to observe that minimizing only depends on the part of F\mathcal{F} where f0f_0 is already sufficiently small.

Proof

Since SαS_\alpha is compact and nonempty and ff continuous, the extreme value theorem gives x⋆∈Sα\vb{x}^\star \in S_\alpha with f(x⋆)≤f(x)f(\vb{x}^\star) \le f(\vb{x}) for every x∈Sα\vb{x} \in S_\alpha. Now let x∈F\vb{x} \in \mathcal{F} be arbitrary. If x∈Sα\vb{x} \in S_\alpha, we are done. Otherwise f(x)>α≥f(x⋆)f(\vb{x}) > \alpha \ge f(\vb{x}^\star), since x⋆∈Sα\vb{x}^\star \in S_\alpha. In either case f(x⋆)≤f(x)f(\vb{x}^\star) \le f(\vb{x}).

For the final claim, choosing any x0∈F\vb{x}_0 \in \mathcal{F} and α=f(x0)\alpha = f(\vb{x}_0) makes sublevel SαS_\alpha nonempty; its boundedness (by coercivity) and closedness (by continuity of ff and closedness of F\mathcal{F}) are proved in the coercivity exercise at the end. ■\blacksquare

∎

The proof never uses that F\mathcal{F} is closed: what matters is that some sublevel is compact. Closedness of F\mathcal{F} is needed only to deduce that from coercivity. The assumptions (continuity, closed sublevel, bounded sublevel) work together and each can fail differently. The next interactive catalogs failures and successes. Move level cc: the thick orange segment in the lower strip is ScS_c. For each function decide, before reading the comment, which assumption fails (or why none does).

InteractiveDoes the minimum exist?
infimum← f se acerca sin llegar← sin cota
  • f(x)=ex, x∈Rf(x)=e^{x},\ x\in\R
  • level cc and sublevel {f≤c}\{f \le c\}
  • infimum
  • minimizer
2.00
inf⁡f\inf f0.000
Attained?no
Sublevel {f≤c}\{f \le c\}[−∞, 0.69]
Boundedno
Closedyes
Compactno
The infimum is 0 and is not attained. Coercivity fails: f(x)→0f(x) \to 0 as x→−∞x \to -\infty, not to +∞+\infty. The sublevel sets (−∞,ln⁡c](-\infty, \ln c] are closed but unbounded, hence not compact. The infimum 00 is “attained at infinity”.
Seven functions: a different assumption fails in some and none fails in others. Move level cc and inspect the sublevel set in the lower strip (an empty circle denotes an excluded endpoint). For exe^x and arctan⁡x\arctan x the infimum is finite and no minimizer exists: sublevels are closed but unbounded rays. For xx on (0,2)(0, 2) they are bounded but not closed. For x+1/xx + 1/x the domain is open yet a minimum exists because f→∞f \to \infty at the boundary. For x2+asin⁡(bx)x^2 + a\sin(bx) coercivity guarantees a global minimum but not the absence of multiple local minima: increase aa until they appear. For sin⁡3x+x/2\sin 3x + x/2 on [−2,2][-2, 2] Weierstrass applies directly. In the final example the domain is compact and for c≥1c \ge 1 the sublevel is too, but the function is discontinuous and has no minimum.

What to take from the figure:

  • A finite infimum is not a minimum. exe^x and arctan⁡x\arctan x are bounded below and do not attain their bound.
  • Coercivity buys compactness. If f→+∞f \to +\infty in every direction, sublevels are contained in a ball. This is the assumption checked in practice.
  • Continuity cannot be removed, though it can be weakened. It suffices for ff to be lower semicontinuous: f(x)≤lim inf⁡f(xk)f(\vb{x}) \le \liminf f(\vb{x}_k) whenever xk→x\vb{x}_k \to \vb{x}, exactly what makes sublevels closed and what the extreme value theorem needs for a minimum; the final function violates this.
  • Domain matters. Sublevels of x+1/xx + 1/x are compact although domain (0,∞)(0, \infty) is not. This is the idea of interior-point barrier functions.

When training has no minimum

A practically important case is logistic regression on linearly separable data. With loss R^(w)=1n∑ilog⁡(1+e−yiw⊤xi)\hat R(\vb{w}) = \tfrac1n\sum_i \log(1 + e^{-y_i \vb{w}\T\vb{x}_i}) and labels yi=±1y_i = \pm 1, if some w0\vb{w}_0 correctly classifies all data, then yiw0⊤xi>0y_i \vb{w}_0\T\vb{x}_i > 0 for every ii and loss along tw0t\vb{w}_0 tends to 00 as t→∞t \to \infty. Since R^>0\hat R > 0 always, the infimum is 00 and not attained: the function is not coercive and sublevels are unbounded. Gradient descent does not stop, and ∥w∥\norm{\vb{w}} grows as log⁡t\log t (the implicit bias of gradient descent on separable data, studied by Soudry and colleagues in 2018). Check it.

[ ]Logistic regression: without and with overlapBrowser
import numpy as np

def perdida(w, X, y):
    return np.mean(np.logaddexp(0, -y * (X @ w)))

def grad(w, X, y):
    s = -y / (1 + np.exp(y * (X @ w)))
    return X.T @ s / len(y)

x = np.array([-2.0, -1.0, 1.0, 2.0, 1.5])
Xs, ys = np.column_stack([x[:4], np.ones(4)]), np.array([-1.0, -1.0, 1.0, 1.0])   # separable
Xn, yn = np.column_stack([x, np.ones(5)]), np.array([-1.0, -1.0, 1.0, 1.0, -1.0])  # el último punto solapa

for nombre, (X, y) in {"separable": (Xs, ys), "con solapamiento": (Xn, yn)}.items():
    w = np.zeros(2)
    print(nombre)
    for t in range(1, 10001):
        w -= 0.5 * grad(w, X, y)
        if t in (10, 100, 1000, 10000):
            print(f"  t = {t:5d}   pérdida = {perdida(w, X, y):.3e}   ‖w‖ = {np.linalg.norm(w):6.3f}   ‖∇‖ = {np.linalg.norm(grad(w, X, y)):.1e}")

With separable data, from t=100t = 100 loss divides by 10 whenever tt is multiplied by 10 and ∥w∥\norm{\vb{w}} grows without bound: another 2.172.17 then 2.282.28 per factor 10, approaching ln⁡10≈2.30\ln 10 \approx 2.30, i.e. as log⁡t\log t (here limiting direction is (1,0)(1, 0), the unit-norm maximum-margin separator): nothing converges because there is nowhere to converge. With one overlapping point the problem does have a minimum, gradient falls to zero and ∥w∥\norm{\vb{w}} stabilizes at 2.1192.119. This explains why logistic regression is regularized by default and early stopping can sometimes be a form of regularization.

First-order optimality conditions

Suppose a minimum exists. How is it recognized? Start with the cheapest information: gradient. From now on f:U→Rf : U \to \R is differentiable on open U⊆RnU \subseteq \R^n and we seek minima inside the feasible set (here unconstrained: F=U\mathcal{F} = U). The idea is as in one variable: at a minimum no descent direction exists.

Proof

Differentiability gives the first-order expansion f(x⋆+td)=f(x⋆)+t ∇f(x⋆)⊤d+o(t)f(\vb{x}^\star + t\vb{d}) = f(\vb{x}^\star) + t\,\grad f(\vb{x}^\star)\T\vb{d} + o(t) as t→0t \to 0. Suppose g=∇f(x⋆)≠0\vb{g} = \grad f(\vb{x}^\star) \neq \vb{0} and take d=−g\vb{d} = -\vb{g}. Then f(x⋆+td)−f(x⋆)=−t∥g∥2+o(t)=t (−∥g∥2+o(1))f(\vb{x}^\star + t\vb{d}) - f(\vb{x}^\star) = -t\norm{\vb{g}}^2 + o(t) = t\,(-\norm{\vb{g}}^2 + o(1)), negative for every sufficiently small t>0t > 0. But then points arbitrarily close to x⋆\vb{x}^\star (all in open UU) have strictly smaller value, contradicting that x⋆\vb{x}^\star is a local minimum. ■\blacksquare

∎

The proof says more than the statement: if ∇f(x)≠0\grad f(\vb{x}) \neq \vb{0}, direction −∇f(x)-\grad f(\vb{x}) is descent and underlies gradient descent. Stationary points are exactly fixed points of x↦x−η∇f(x)\vb{x} \mapsto \vb{x} - \eta\grad f(\vb{x}). This condition uses the calculus lesson’s gradient, and must be read carefully:

  • It is necessary, not sufficient. f(x)=x3f(x) = x^3 has f′(0)=0f'(0) = 0 and is not a minimum. f(x,y)=x2−y2f(x, y) = x^2 - y^2 has ∇f(0,0)=0\grad f(0, 0) = \vb{0} and is a saddle.
  • It does not say minimum, maximum or saddle, or local versus global. With many critical points (as in the zoo below), “zeroing the gradient” is not very informative.
  • It applies only at interior points. With constraints, a minimum can be on the boundary with nonzero gradient (min⁡x\min x on [0,1][0, 1]). The correct generalization replacing ∇f=0\grad f = \vb{0} with Karush–Kuhn–Tucker conditions is in the KKT conditions lesson.
  • For convex problems it is sufficient, making “solve ∇f(x)=0\grad f(\vb{x}) = \vb{0}” the complete algorithm (lesson 3).

Second-order conditions

If ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}, the linear term in Taylor expansion vanishes and curvature decides. The second-order Taylor expansion with Peano remainder, for ff of class C2C^2, is

f(x⋆+h)=f(x⋆)+∇f(x⋆)⊤h+12 h⊤ ∇2f(x⋆) h+o(∥h∥2),f(\vb{x}^\star + \vb{h}) = f(\vb{x}^\star) + \grad f(\vb{x}^\star)\T\vb{h} + \tfrac12\,\vb{h}\T\,\hess f(\vb{x}^\star)\,\vb{h} + o(\norm{\vb{h}}^2),

where ∇2f\hess f is the Hessian, symmetric by Schwarz’s theorem. If ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}, the difference f(x⋆+h)−f(x⋆)f(\vb{x}^\star + \vb{h}) - f(\vb{x}^\star) is the quadratic form 12h⊤Hh\tfrac12\vb{h}\T\mat{H}\vb{h} plus a remainder negligible relative to ∥h∥2\norm{\vb{h}}^2. Everything that follows reads that quadratic form.

Proof

(1) The first-order condition gives ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}. Fix d∈Rn\vb{d} \in \R^n and take h=td\vb{h} = t\vb{d}. Since x⋆\vb{x}^\star is a local minimum, for small tt, 0≤f(x⋆+td)−f(x⋆)=12t2 d⊤Hd+o(t2)0 \le f(\vb{x}^\star + t\vb{d}) - f(\vb{x}^\star) = \tfrac12 t^2\,\vb{d}\T\mat{H}\vb{d} + o(t^2). Dividing by t2t^2 and taking t→0t \to 0 leaves d⊤Hd≥0\vb{d}\T\mat{H}\vb{d} \ge 0. Since d\vb{d} was arbitrary, H⪰0\mat{H} \succeq 0.

(2) Let μ=λmin⁡(H)>0\mu = \lambda_{\min}(\mat{H}) > 0. By the spectral theorem, h⊤Hh≥μ∥h∥2\vb{h}\T\mat{H}\vb{h} \ge \mu\norm{\vb{h}}^2 for every h\vb{h}. Taylor’s formula gives f(x⋆+h)−f(x⋆)≥μ2∥h∥2+o(∥h∥2)f(\vb{x}^\star + \vb{h}) - f(\vb{x}^\star) \ge \tfrac{\mu}{2}\norm{\vb{h}}^2 + o(\norm{\vb{h}}^2). Some δ>0\delta > 0 makes the remainder’s absolute value less than μ4∥h∥2\tfrac{\mu}{4}\norm{\vb{h}}^2 when ∥h∥<δ\norm{\vb{h}} < \delta, and then f(x⋆+h)−f(x⋆)≥μ4∥h∥2>0f(\vb{x}^\star + \vb{h}) - f(\vb{x}^\star) \ge \tfrac{\mu}{4}\norm{\vb{h}}^2 > 0 for 0<∥h∥<δ0 < \norm{\vb{h}} < \delta. ■\blacksquare

∎

Proof (2) also gives quadratic growth. Near a minimum with definite Hessian, ff rises at least as μ4∥h∥2\tfrac{\mu}{4}\norm{\vb{h}}^2. This constant μ\mu will appear as strong convexity in convergence rates.

Notice the distinction: in (1), semidefinite ⪰\succeq and a necessary conclusion; in (2), definite ≻\succ and a sufficient conclusion. Between them lies a band of singular semidefinite Hessian cases that neither resolves. Definitive proof that the band is real:

A subtler and more instructive example overturns a natural idea: “if ff has a minimum on every line through a point, the point is a minimum.” This is Peano’s example:

f(x,y)=(y−x2)(y−3x2)=y2−4x2y+3x4.f(x, y) = (y - x^2)(y - 3x^2) = y^2 - 4x^2 y + 3x^4.

At the origin, ∇f=0\grad f = \vb{0} and ∇2f=diag⁡(0,2)⪰0\hess f = \operatorname{diag}(0, 2) \succeq 0. On each line y=mxy = mx with m≠0m \neq 0, f=x2(m2−4mx+3x2)f = x^2(m^2 - 4mx + 3x^2) is positive near 00; on the horizontal axis it is 3x4>03x^4 > 0 and on the vertical axis y2>0y^2 > 0: every line through the origin has a strict minimum at 00. Yet on parabola y=2x2y = 2x^2, f(x,2x2)=x2⋅(−x2)=−x4<0f(x, 2x^2) = x^2 \cdot (-x^2) = -x^4 < 0. The origin is not a local minimum. Between y=x2y = x^2 and y=3x2y = 3x^2 lies a wedge, arbitrarily thin near the origin, where ff is negative. Testing lines is insufficient: test all curves, and the Hessian, a second-order object, cannot see parabolas.

To see all this, the next interactive places the function alongside its quadratic model at a\vb{a}, q(x)=f(a)+∇f(a)⊤(x−a)+12(x−a)⊤∇2f(a)(x−a)q(\vb{x}) = f(\vb{a}) + \grad f(\vb{a})\T(\vb{x} - \vb{a}) + \tfrac12(\vb{x} - \vb{a})\T\hess f(\vb{a})(\vb{x} - \vb{a}).

InteractiveThe local quadratic model
stationary point of q
  • contours of ff
  • contours of qq (same levels)
  • disk of radius ρ\rho
  • critical points of ff
0.80
a\vb{a}(2.200, 1.600)
∥∇f(a)∥\norm{\grad f(\vb{a})}50.3990
Eigenvalues of H(a)\mat{H}(\vb{a})33.846, 2.154
According to the modelnot critical
max⁡∣f−q∣\max\abs{f - q} in the disk4.915
∇f(a)≠0\grad f(\vb{a}) \neq \vb{0}: this is not a critical point, so there is nothing to classify. The model qq has its own stationary point (the orange circle, classified as “minimum”). Check it: it can lie far from the actual critical points of ff.
Drag point a\vb{a} over level curves of ff (blue). Orange curves are its quadratic model qq at the same levels; the thick curve has level f(a)f(\vb{a}). Near a\vb{a} they coincide, far away they do not: watch maximum error max⁡∣f−q∣\max\abs{f - q} in the dashed disk as radius increases, and the orange circle, the stationary point of qq (Newton's step), which away from a critical point can lie far from critical points of ff. Select “Go to a critical point” and check that in Himmelblau and Rosenbrock the model determines type. Then try x4+y2x^4 + y^2 and x3+y2x^3 + y^2: the model at the origin is identical but behavior differs. With “Shade” mark the region f<f(a)f < f(\vb{a}): near a local minimum there is no shaded region; in Peano's example the wedge between parabolas is shaded.

Classify critical points by Hessian inertia

Because the Hessian is real symmetric, it has nn real eigenvalues and an orthonormal eigenvector basis. Their signs matter, not their values.

Proof

The first two rows are part (2) of the previous theorem applied to ff and −f-f. For the third, let v+\vb{v}_+ and v−\vb{v}_- be unit eigenvectors with eigenvalues λ+>0\lambda_+ > 0 and λ−<0\lambda_- < 0. By Taylor and ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}, f(x⋆+tv±)−f(x⋆)=12λ±t2+o(t2)f(\vb{x}^\star + t\vb{v}_\pm) - f(\vb{x}^\star) = \tfrac12\lambda_\pm t^2 + o(t^2), positive for v+\vb{v}_+ and negative for v−\vb{v}_- for small tt. Arbitrarily close points have both larger and smaller values, so x⋆\vb{x}^\star is not a local extremum. The fourth row is the previous example (x4x^4, x3x^3, −x4-x^4, Peano). ■\blacksquare

∎

A few comments on using this result:

  • One negative-curvature direction suffices to rule out a minimum, however small. One positive and one negative direction give a saddle even when all others are zero. This asymmetry explains why the smallest Hessian eigenvalue matters in saddle-point escape.
  • Even when inconclusive, the test rules something out. With singular H⪰0\mat{H} \succeq 0 and a positive eigenvalue, the point cannot be a local maximum: the necessary condition applied to −f-f would require H⪯0\mat{H} \preceq 0. Only a minimum (x4+y2x^4 + y^2) or no extremum (x3+y2x^3 + y^2, Peano) remain.
  • Signs can be read without eigenvalues. By Sylvester’s law of inertia, inertia is invariant under congruence P⊤HP\mat{P}\T\mat{H}\mat{P} with invertible P\mat{P}, so it can be obtained via pivoted LDL⊤\mat{L}\mat{D}\mat{L}\T factorization (counting eigenvalue signs of 1×11 \times 1 and 2×22 \times 2 blocks of D\mat{D}), the same O(n3)O(n^3) order as eigendecomposition but several times cheaper and noniterative. To decide H≻0\mat{H} \succ 0, Cholesky factorization suffices, failing exactly when it is not positive definite (see positive definite matrices).
  • In floating point there is no sharp boundary between “zero” and “positive.” A computed eigenvalue 10−1210^{-12} may be a noisy zero or genuine curvature of that size. Numerical classification needs an explicit tolerance and a “degenerate” case when it cannot decide.
  • Each type has an index, and these indices are not arbitrary. For a coercive Morse function on Rn\R^n (all critical points nondegenerate, finitely many, and f→∞f \to \infty at infinity), Morse theory says ∑x⋆(−1)ıˊndice(x⋆)=1\sum_{\vb{x}^\star}(-1)^{\text{índice}(\vb{x}^\star)} = 1: minima offset saddles. Check Himmelblau in the next figure, with 4 minima, 4 saddles and 1 maximum: 4−4+1=14 - 4 + 1 = 1.
InteractiveA zoo of critical points
  • minimum
  • saddle
  • maximum
  • degenerate
  • section with λ>0\lambda > 0
  • section with λ<0\lambda < 0
  • section with λ=0\lambda = 0
Hessian eigenvalue plane (λ1,λ2)(\lambda_1, \lambda_2)
minimummaximumsaddlesaddleλ₁λ₂
The purple axes are degenerate cases (λi=0\lambda_i = 0).
1.2
−0.8
29°
Point(0.000, 0.000)
ff0.000
Eigenvalues of H\mat{H}1.200, −0.800
Inertia (n+,n−,n0)(n_+, n_-, n_0)(1, 1, 0)
Verdictsaddle
Eigenvalues have opposite signs: a saddle point. It rises in one principal direction and falls in the other, so it is not a local extremum even though ∇f=0\grad f = \vb{0}.
Left: surface and critical points, and at the selected point sections in both principal Hessian directions (blue for positive curvature, red for negative, violet for zero). Right: Hessian eigenvalue plane (λ1,λ2)(\lambda_1, \lambda_2). With the quadratic, you control the point: drag from first quadrant (minimum) to third (maximum) through a saddle, then onto a violet axis (zero eigenvalue) to see the test cease deciding and a flat valley or ridge appear. Rotate axes to check classification is orientation-independent. With Himmelblau, each of 9 critical points is a point in the plane. With Rosenbrock the critical point nearly touches an axis: the Hessian is invertible but nearly singular. The monkey saddle, x4+y2x^4 + y^2, x3+y2x^3 + y^2 and Peano are degenerate.

The figure shows something books overlook: “nondegenerate” is a matter of degree. Rosenbrock’s only critical point (1,1)(1, 1) has Hessian eigenvalues approximately 1001.61001.6 and 0.40.4. It is positive definite, so is a strict minimum, but the curvature ratio 1001.6/0.4≈25001001.6 / 0.4 \approx 2500 makes the valley numerically nearly flat in one direction. This ill-conditioning slows gradient methods.

This connects to deep learning. Critical points encountered in network losses often have many nearly zero eigenvalues (parameter directions barely changing the function) and especially many more saddles than local minima as dimension grows (Dauphin and colleagues, 2014). Understanding saddles, not only minima, helps explain successful training; study them in the nonconvex reality lesson and the strict saddle property.

Implementation from scratch

Start with basics: a function measuring Hessian inertia with explicit tolerance and a classifier. Then use it to check Peano’s example, which the Hessian declares “degenerate,” probing the function along lines and parabolas.

[ ]Inertia and classification with toleranceBrowser
import numpy as np

def inercia(H, tol=1e-9):
    """(n_pos, n_neg, n_cero) de una matriz simétrica, con tolerancia relativa al mayor autovalor."""
    H = 0.5 * (np.asarray(H, dtype=float) + np.asarray(H, dtype=float).T)   # simetriza el ruido numérico
    w = np.linalg.eigvalsh(H)
    corte = tol * max(1.0, np.abs(w).max())
    return int((w > corte).sum()), int((w < -corte).sum()), int((np.abs(w) <= corte).sum())

def tipo(H, tol=1e-9):
    npos, nneg, ncero = inercia(H, tol)
    if npos > 0 and nneg > 0:
        return "silla"           # una dirección de cada signo basta, aunque haya autovalores nulos
    if ncero > 0:
        return "degenerado"
    return "mínimo" if nneg == 0 else "máximo"

for nombre, H in {"diag(2, 3)": np.diag([2.0, 3.0]), "diag(2, -1)": np.diag([2.0, -1.0]), "diag(-1, -4)": np.diag([-1.0, -4.0]),
                  "diag(0, 2)  (x⁴+y², x³+y², Peano)": np.diag([0.0, 2.0]), "diag(1, 1e-12)": np.diag([1.0, 1e-12])}.items():
    print(f"{nombre:36s} inercia = {inercia(H)}   ->  {tipo(H)}")

# Peano: f = (y - x²)(y - 3x²). En el origen el hessiano es diag(0, 2) pero el origen NO es un mínimo.
f = lambda x, y: (y - x**2) * (y - 3 * x**2)
rng = np.random.default_rng(0)
t = np.linspace(-1e-4, 1e-4, 2001)          # radio de prueba pequeño: el mínimo sobre cada recta es local
t = t[t != 0]
peor_recta = min(f(t * np.cos(a), t * np.sin(a)).min() for a in rng.uniform(0, np.pi, 400))
print("\nmínimo de f sobre 400 rectas por el origen:", f"{peor_recta:.2e}", "(nunca baja de 0)")
x = 1e-2
print("f sobre la parábola y = 2x² en x = 0.01:", f"{f(x, 2 * x**2):.2e}", "= -x⁴ =", f"{-x**4:.2e}")

Function tipo already has the right hierarchy: before declaring “degenerate” it checks for opposite-sign curvature, because a saddle is certain even with zero eigenvalues. Peano’s example passes the line test with no violation and fails on the first parabola tested: nothing testable one direction at a time detects the negative wedge.

Now the critical-point hunter. Symbolic algebra solves ∇f=0\grad f = \vb{0} exactly, calculates the Hessian at each solution and classifies. We test a quartic with three real critical points and the four degenerate examples above.

[ ]Exact critical points with SymPyBrowser
import numpy as np
import sympy as sp

x, y = sp.symbols("x y", real=True)
funciones = {
    "x⁴ + y⁴ − 4xy + 1": x**4 + y**4 - 4 * x * y + 1,
    "x³ − 3xy² (silla de mono)": x**3 - 3 * x * y**2,
    "x⁴ + y²": x**4 + y**2,
    "x³ + y²": x**3 + y**2,
    "(y − x²)(y − 3x²) (Peano)": (y - x**2) * (y - 3 * x**2),
}

def tipo_numerico(H, tol=1e-9):
    w = np.linalg.eigvalsh(np.array(H, dtype=float))
    npos, nneg, ncero = int((w > tol).sum()), int((w < -tol).sum()), int((abs(w) <= tol).sum())
    if npos and nneg:
        return "silla", w
    return ("degenerado" if ncero else ("mínimo" if nneg == 0 else "máximo")), w

for nombre, f in funciones.items():
    grad = [sp.diff(f, v) for v in (x, y)]
    hess = sp.hessian(f, (x, y))
    print(nombre)
    for sol in sp.solve(grad, [x, y], dict=True):
        k, w = tipo_numerico(hess.subs(sol))
        print(f"   ({sol[x]}, {sol[y]})   autovalores = {np.round(w, 3)}   ->  {k}")

Results match theory: the quartic has a saddle at the origin (eigenvalues −4-4 and 44) and two minima at (1,1)(1, 1) and (−1,−1)(-1, -1) with eigenvalues 88 and 1616; all four degenerate examples yield “degenerate”: monkey saddle with eigenvalues (0,0)(0, 0) and the other three with (0,2)(0, 2), identical for three functions with different behavior. Deciding requires higher derivatives or the function itself, as above.

For a function without closed-form roots or a real loss, the usual approach solves ∇f=0\grad f = \vb{0} numerically from many initial conditions and retains distinct solutions. For Himmelblau, with 9 real critical points:

[ ]Numerical critical points with scipy.optimize.rootBrowser
import numpy as np
from scipy.optimize import root

grad = lambda p: [4 * p[0] * (p[0]**2 + p[1] - 11) + 2 * (p[0] + p[1]**2 - 7),
                  2 * (p[0]**2 + p[1] - 11) + 4 * p[1] * (p[0] + p[1]**2 - 7)]
hess = lambda p: [[12 * p[0]**2 + 4 * p[1] - 42, 4 * p[0] + 4 * p[1]],
                  [4 * p[0] + 4 * p[1], 12 * p[1]**2 + 4 * p[0] - 26]]

hallados = []
for a in np.linspace(-5, 5, 9):
    for b in np.linspace(-5, 5, 9):
        r = root(grad, [a, b], jac=hess, tol=1e-12)
        if r.success and not any(np.linalg.norm(r.x - q) < 1e-6 for q in hallados):
            hallados.append(r.x)

print(f"{len(hallados)} puntos críticos distintos desde 81 arranques")
indices = []
for q in sorted(hallados, key=lambda q: (q[1], q[0])):
    w = np.linalg.eigvalsh(np.array(hess(q)))
    indices.append(int((w < 0).sum()))
    print(f"  ({q[0]:8.4f}, {q[1]:8.4f})   autovalores = {np.round(w, 2)}   índice = {indices[-1]}")
print("suma de (-1)^índice =", sum((-1) ** i for i in indices), "(teoría de Morse: 1)")

# contraste con SymPy: la cuártica x⁴ + y⁴ − 4xy + 1 tenía exactamente (−1, −1), (0, 0) y (1, 1)
g4 = lambda p: [4 * p[0]**3 - 4 * p[1], 4 * p[1]**3 - 4 * p[0]]
h4 = lambda p: [[12 * p[0]**2, -4.0], [-4.0, 12 * p[1]**2]]
num4 = []
for a in np.linspace(-2, 2, 9):
    for b in np.linspace(-2, 2, 9):
        r = root(g4, [a, b], jac=h4, tol=1e-12)
        if r.success and not any(np.linalg.norm(r.x - q) < 1e-6 for q in num4):
            num4.append(r.x)
exactos = np.array([[-1.0, -1.0], [0.0, 0.0], [1.0, 1.0]])
err = max(np.linalg.norm(exactos - q, axis=1).min() for q in num4)
print(f"\ncuártica: {len(num4)} puntos numéricos, distancia máxima a los exactos de SymPy = {err:.1e}")

# punto degenerado: la silla de mono. La jacobiana es singular en el origen y root no puede certificarlo
mono = lambda p: [3 * p[0]**2 - 3 * p[1]**2, -6 * p[0] * p[1]]
r = root(mono, [0.5, 0.3], tol=1e-12)
print("\nsilla de mono desde (0.5, 0.3): success =", r.success, f"  ‖x‖ = {np.linalg.norm(r.x):.1e}", "  llamadas =", r.nfev)
print("mensaje:", r.message)

Three lessons from the output. First, 81 grid starts find all 9 Himmelblau critical points, and the Morse count is 4−4+1=14 - 4 + 1 = 1 (four index-0 minima, four index-1 saddles and one index-2 maximum). For the quartic, the numerical method rediscovers exactly the three SymPy points with rounding-level error: when a symbolic solution exists it tests the numerical one. Second, index is measured with eigvalsh, the symmetric-matrix method, which also guarantees sorted real eigenvalues. Third, the degenerate case: the solver converges, but very slowly, ultimately reporting failure because calls are exhausted even though the iterate is within 10−10010^{-100} of the origin; when the Jacobian (here Hessian) is singular, Newton-type methods lose quadratic convergence and cannot certify the solution. See Newton’s method.

The library version

In real code the Hessian is rarely written by hand. With automatic differentiation in PyTorch:

import torch

def f(p):                      # Himmelblau, p es un tensor de forma (2,)
    x, y = p
    return (x**2 + y - 11) ** 2 + (x + y**2 - 7) ** 2

p = torch.tensor([3.0, 2.0])
g = torch.autograd.functional.jacobian(f, p)     # gradiente: casi cero en un punto crítico
H = torch.autograd.functional.hessian(f, p)      # hessiano 2x2
w = torch.linalg.eigvalsh(H)                     # autovalores reales y ascendentes
print(g, w)                                      # g ≈ 0, w > 0: mínimo

For networks with millions of parameters forming H\mat{H} is infeasible (n2n^2 entries). Compute Hessian-vector products without building the matrix and estimate extreme eigenvalues using Lanczos iteration. To seek local minima (not all critical points), use scipy.optimize.minimize, which takes objective, initial point and optionally gradient.

Common errors

Exercises

QuizCritical points of a quartic in y
Let f(x,y)=x2−y2+14y4f(x, y) = x^2 - y^2 + \tfrac14 y^4. What are its critical points and types?
QuizLocal minimum at the origin?
For which functions is the origin a local minimum (not necessarily strict)?

More than one answer may be correct.

QuizWhy there is no minimizer
You train unregularized logistic regression on linearly separable data and observe loss always falling while ∥w∥\norm{\vb{w}} grows without bound. What is the correct explanation?
NumericOptimal value by substitution
Calculate by substitution the optimal value p⋆p^\star of minimizing x2+y2x^2 + y^2 subject to x+2y=5x + 2y = 5.
NumericIndex of a critical point in R³
At a critical point of a three-variable function, the Hessian is H=[220224042]\mat{H} = \begin{bmatrix} 2 & 2 & 0 \\ 2 & 2 & 4 \\ 0 & 4 & 2 \end{bmatrix}. What is its index (number of negative eigenvalues)?
ProofCoercive and continuous implies a minimum
Prove: If f:Rn→Rf : \R^n \to \R is continuous and coercive, it attains its global minimum.
0
Use the existence theorem via compact sublevels just seen. Fix x0∈Rn\vb{x}_0 \in \R^n and α=f(x0)\alpha = f(\vb{x}_0), and study Sα={x:f(x)≤α}S_\alpha = \{\vb{x} : f(\vb{x}) \le \alpha\}.

Step 1 of 3. How do you prove SαS_\alpha is closed?

ProofThe second-order necessary condition
Prove: If ff is of class C2C^2 on open UU and x⋆∈U\vb{x}^\star \in U is a local minimum, then ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0} and ∇2f(x⋆)⪰0\hess f(\vb{x}^\star) \succeq 0.
0
You already know ∇f(x⋆)=0\grad f(\vb{x}^\star) = \vb{0}. For semidefiniteness, fix direction d\vb{d} and study f(x⋆+td)f(\vb{x}^\star + t\vb{d}) as t→0t \to 0.

Step 1 of 4. Which Taylor expansion do you use?

CodeClassify a critical point
Implement classify_critical_point(H, tol), which takes the Hessian H (a square matrix, possibly asymmetric due to numerical noise) at a critical point and returns one of 'mínimo', 'máximo', 'silla' or 'degenerado'. First symmetrize H as (H+H⊤)/2(\mat{H} + \mat{H}\T)/2. An eigenvalue λ\lambda is considered zero if ∣λ∣≤\abs{\lambda} \le tol, positive if λ>\lambda > tol and negative if λ<−\lambda < -tol. If eigenvalues of both signs exist, it is 'silla' even if there are zero eigenvalues. Otherwise, 'degenerado' if any eigenvalue is zero, and otherwise 'mínimo' (all positive) or 'máximo' (all negative). Do not call np.linalg.eigvals: use np.linalg.eigvalsh.
import numpy as np

def classify_critical_point(H, tol=1e-9):
  """'mínimo', 'máximo', 'silla' o 'degenerado' según la inercia del hessiano H."""
  H = np.asarray(H, dtype=float)
  # tu código: simetriza, calcula autovalores con eigvalsh y cuenta signos con la tolerancia
  return "degenerado"
Shift+Enter to run

Summary

Key idea
Optimization chooses the best point in a feasible set. Before calculating it, know whether it exists (coercivity and compact sublevels) and how to recognize a local optimum: zero gradient and Hessian inertia to distinguish minimum, maximum and saddle, with a degenerate band where the test is inconclusive.
  • A standard-form problem has variable, objective and constraints, feasible set F\mathcal{F}, optimal value p⋆=inf⁡f0(F)p^\star = \inf f_0(\mathcal{F}) and solution set. It may be solvable, have an unattained infimum, be unbounded (p⋆=−∞p^\star = -\infty) or infeasible (p⋆=+∞p^\star = +\infty).
  • Maximizing ff is minimizing −f-f (optimal value changes sign). Local is not global except in the convex case.
  • If ff is continuous and sublevels compact (in particular, if coercive), a global minimum exists. Without coercivity a finite infimum may have no minimizer, as in separable logistic regression.
  • At an interior local minimum, ∇f=0\grad f = \vb{0} and ∇2f⪰0\hess f \succeq 0; if ∇f=0\grad f = \vb{0} and ∇2f≻0\hess f \succ 0, it is a strict local minimum with quadratic growth.
  • Hessian inertia (n+,n−,n0)(n_+, n_-, n_0) classifies a critical point: one direction of each sign is a saddle; with zero eigenvalues and only one sign the test is inconclusive (x4x^4, x3x^3, monkey saddle, Peano).
  • Numerically, classification requires explicit tolerance, symmetrizing the Hessian and using eigvalsh.