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 minimizing empirical loss , sometimes with a regularization term.
- Calibrate a simulator. Choose physical parameters bringing simulator output close to measurements , minimizing with each parameter within an admissible range.
- Allocate resources. Choose portfolio weights minimizing risk 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:
- 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).
- Does a solution exist? Many training failures, such as weights growing without bound, are symptoms of a problem with no minimum.
- 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. is always defined (as an element of ), but can be empty. A problem can have an optimal value and no solution: is attained at no positive . Thus distinguish “the optimal value is ” from “the problem has a solution.”
Four outcomes are possible. Depending on and , the problem is:
| Outcome | What happens | ||
|---|---|---|---|
| Solvable | The best value is attained | finite | nonempty |
| Infimum not attained | Values approach without reaching it | finite | empty |
| Unbounded | decreases arbitrarily over | empty | |
| Infeasible | No point satisfies the constraints | empty |
Feasibility is part of the problem. There is no “best ” without saying which points compete. Changing the feasible set changes the problem, even with the same formula. The next figure makes this concrete: with one objective, changing constraints moves from solvable to infeasible, unbounded or an escaping infimum.
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. is : solutions are the same and the optimal value changes sign, . In the figure, the “maximum value of ” is the opposite of .
- Rescale the objective. If is strictly increasing, minimizing has the same solutions with another optimal value. Thus minimize rather than (the former is differentiable everywhere; the latter is not exactly where residual vanishes), or rather than the product: maximum likelihood and minimum negative log likelihood coincide.
- One equality is two inequalities. is equivalent to and . 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. is equivalent to with . It converts inequalities into equalities at the cost of sign-constrained variables.
- Epigraph form. is equivalent to subject to : 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 , where on and outside. Lesson 11’s proximal methods use this idea.
Local and global minima
An optimizer’s goal is the best point in all of . But most algorithms can only compare a point with its neighbors, giving rise to two notions.
Four important observations:
- Only feasible neighbors count. In a constrained problem a boundary point of can be a local minimum even if falls outside the set. Minimizing on has its minimum at , where the derivative is .
- Global implies local, and the converse is false: 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.
- There is a class where the distinction disappears. In convex problems, studied from lesson 3, every local minimum is global: if a feasible had , their segment would be feasible and convexity puts below the chord, strictly below even arbitrarily close to . Convexity makes optimization tractable.
- A global minimum need not be unique. With a flat valley, is a whole line; with symmetry (permuting hidden-layer neurons), 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 ) attains its minimum. But the feasible set is rarely compact: is not. The way out is to observe that minimizing only depends on the part of where is already sufficiently small.
Proof
Since is compact and nonempty and continuous, the extreme value theorem gives with for every . Now let be arbitrary. If , we are done. Otherwise , since . In either case .
For the final claim, choosing any and makes sublevel nonempty; its boundedness (by coercivity) and closedness (by continuity of and closedness of ) are proved in the coercivity exercise at the end.
∎The proof never uses that is closed: what matters is that some sublevel is compact. Closedness of 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 : the thick orange segment in the lower strip is . For each function decide, before reading the comment, which assumption fails (or why none does).
What to take from the figure:
- A finite infimum is not a minimum. and are bounded below and do not attain their bound.
- Coercivity buys compactness. If 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 to be lower semicontinuous: whenever , exactly what makes sublevels closed and what the extreme value theorem needs for a minimum; the final function violates this.
- Domain matters. Sublevels of are compact although domain 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 and labels , if some correctly classifies all data, then for every and loss along tends to as . Since always, the infimum is and not attained: the function is not coercive and sublevels are unbounded. Gradient descent does not stop, and grows as (the implicit bias of gradient descent on separable data, studied by Soudry and colleagues in 2018). Check it.
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 loss divides by 10 whenever is multiplied by 10 and grows without bound: another then per factor 10, approaching , i.e. as (here limiting direction is , 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 stabilizes at . 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 is differentiable on open and we seek minima inside the feasible set (here unconstrained: ). The idea is as in one variable: at a minimum no descent direction exists.
Proof
Differentiability gives the first-order expansion as . Suppose and take . Then , negative for every sufficiently small . But then points arbitrarily close to (all in open ) have strictly smaller value, contradicting that is a local minimum.
∎The proof says more than the statement: if , direction is descent and underlies gradient descent. Stationary points are exactly fixed points of . This condition uses the calculus lesson’s gradient, and must be read carefully:
- It is necessary, not sufficient. has and is not a minimum. has 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 ( on ). The correct generalization replacing with Karush–Kuhn–Tucker conditions is in the KKT conditions lesson.
- For convex problems it is sufficient, making “solve ” the complete algorithm (lesson 3).
Second-order conditions
If , the linear term in Taylor expansion vanishes and curvature decides. The second-order Taylor expansion with Peano remainder, for of class , is
where is the Hessian, symmetric by Schwarz’s theorem. If , the difference is the quadratic form plus a remainder negligible relative to . Everything that follows reads that quadratic form.
Proof
(1) The first-order condition gives . Fix and take . Since is a local minimum, for small , . Dividing by and taking leaves . Since was arbitrary, .
(2) Let . By the spectral theorem, for every . Taylor’s formula gives . Some makes the remainder’s absolute value less than when , and then for .
∎Proof (2) also gives quadratic growth. Near a minimum with definite Hessian, rises at least as . This constant will appear as strong convexity in convergence rates.
Notice the distinction: in (1), semidefinite and a necessary conclusion; in (2), definite 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 has a minimum on every line through a point, the point is a minimum.” This is Peano’s example:
At the origin, and . On each line with , is positive near ; on the horizontal axis it is and on the vertical axis : every line through the origin has a strict minimum at . Yet on parabola , . The origin is not a local minimum. Between and lies a wedge, arbitrarily thin near the origin, where 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 , .
Classify critical points by Hessian inertia
Because the Hessian is real symmetric, it has 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 and . For the third, let and be unit eigenvectors with eigenvalues and . By Taylor and , , positive for and negative for for small . Arbitrarily close points have both larger and smaller values, so is not a local extremum. The fourth row is the previous example (, , , Peano).
∎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 and a positive eigenvalue, the point cannot be a local maximum: the necessary condition applied to would require . Only a minimum () or no extremum (, Peano) remain.
- Signs can be read without eigenvalues. By Sylvester’s law of inertia, inertia is invariant under congruence with invertible , so it can be obtained via pivoted factorization (counting eigenvalue signs of and blocks of ), the same order as eigendecomposition but several times cheaper and noniterative. To decide , 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 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 (all critical points nondegenerate, finitely many, and at infinity), Morse theory says : minima offset saddles. Check Himmelblau in the next figure, with 4 minima, 4 saddles and 1 maximum: .
The figure shows something books overlook: “nondegenerate” is a matter of degree. Rosenbrock’s only critical point has Hessian eigenvalues approximately and . It is positive definite, so is a strict minimum, but the curvature ratio 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.
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 exactly, calculates the Hessian at each solution and classifies. We test a quartic with three real critical points and the four degenerate examples above.
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 and ) and two minima at and with eigenvalues and ; all four degenerate examples yield “degenerate”: monkey saddle with eigenvalues and the other three with , 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 numerically from many initial conditions and retains distinct solutions. For Himmelblau, with 9 real critical points:
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 (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 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 is infeasible ( 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
More than one answer may be correct.
Step 1 of 3. How do you prove is closed?
Step 1 of 4. Which Taylor expansion do you use?
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 . An eigenvalue is considered zero if tol, positive if tol and negative if 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"Summary
- A standard-form problem has variable, objective and constraints, feasible set , optimal value and solution set. It may be solvable, have an unattained infimum, be unbounded () or infeasible ().
- Maximizing is minimizing (optimal value changes sign). Local is not global except in the convex case.
- If 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, and ; if and , it is a strict local minimum with quadratic growth.
- Hessian inertia classifies a critical point: one direction of each sign is a saddle; with zero eigenvalues and only one sign the test is inconclusive (, , monkey saddle, Peano).
- Numerically, classification requires explicit tolerance, symmetrizing the Hessian and using
eigvalsh.