Lagrangian duality: bounds, certificates and sensitivity
Construct the dual problem and explain why it always provides bounds (weak duality), when they are exact (strong duality under Slater), and how the duality gap certifies solution quality. Introduce convex conjugates and Fenchel duality, alternative theorems such as Farkas' lemma, and multipliers as shadow prices.
After this lesson you can
Derive the dual function and dual problem for LPs, QPs, minimum-norm least squares and lasso.
Prove weak duality and explain geometrically strong duality under Slater's condition.
Use the duality gap as a stopping criterion and suboptimality certificate.
Calculate conjugates of norms, quadratics, log-sum-exp and negative entropy and apply Fenchel duality.
Interpret optimal multipliers as derivatives of optimal value with respect to constraint perturbations.
Apply Farkas' lemma to construct infeasibility certificates.
Motivation: how far remains, without knowing the target
A solver returns a point x^ with f0(x^)=−44.99. Is it optimal? If not, is it close or light-years away? Looking at the last step’s change does not answer: a slow, stuck method also takes tiny steps. To claim “the optimum is in [−47,−44.99]” requires a guaranteed lower bound on optimal value p⋆, a number provably at most f0(x) for every feasible point x without solving the problem.
Lower bounds can be constructed. Consider minimizing x2 subject to x≥1. For any number λ≥0 and feasible x, x2≥x2+λ(1−x), because the added term is λ times something nonpositive. The right side is a parabola in x whose minimum is calculated by hand: at x=λ/2 it equals λ−λ2/4. So for eachλ≥0,
p⋆≥λ−4λ2.
With λ=1 we get p⋆≥0.75; with λ=2, p⋆≥1, and since x=1 is feasible and gives 1, the optimum is exactly 1: point and bound certify each other. That is the whole idea: constraints are “charged” a price λ, the relaxed problem is solved without constraints, and the best price gives the best bound. It appears wherever knowing when to stop or a constraint’s cost matters:
Guaranteed stopping criteria. scikit-learn’s Lasso iterates by coordinates until the duality gap falls below tol (attribute dual_gap_ stores it); interior-point solvers print primal objective, dual objective and their difference each iteration.
Certificates. An infeasibility or optimality result with a proof verifiable in linear time, rather than “the solver said so”.
Prices. A budget constraint’s multiplier is the marginal value of one extra budget unit. Shadow prices are the dual’s economic interpretation.
Easier problems. For a difficult or nonconvex problem, the dual is always convex and gives a bound (the MAX-CUT relaxation in the convex problems lesson arises this way). For support vector machines, the dual enables the kernel trick.
This lesson constructs the dual of any problem, proves it always gives bounds (weak duality), finds when they are exact (strong duality under the Slater condition of the previous lesson), introduces convex conjugates, interprets multipliers as prices, and concludes with alternative theorems, the same dual applied to “does this system have a solution?”
The dual function: an infimum of lines
Work with the standard-form problem from the KKT lesson, without assuming convexity,
with optimal value p⋆∈[−∞,+∞] (with +∞ if no feasible points) and functions defined on Rn unless a domain is stated. The Lagrangian is L(x,λ,ν)=f0(x)+∑iλifi(x)+∑jνjhj(x).
The two properties making g useful follow from the definition, but deserve a careful look.
Proof
Fix x. Mapping (λ,ν)↦L(x,λ,ν) is affine: the Lagrangian is linear in multipliers. Thus g is the infimum over all x of a family of affine functions. The pointwise infimum of concave functions is concave (its hypograph is an intersection of convex hypographs), so g is concave. The domain is the set {g>−∞} of a concave function, which is convex. ■
∎
It is convexity in reverse, holding without assumptions on f0, fi or hj. In the motivation problem each x contributes line λ↦x2+λ(1−x), and g(λ)=infx(…) is their lower envelope, the concave parabola λ−λ2/4 (the orange curve in the lower panel of the figure below).
Weak duality: the dual always gives a bound
Since g is concave, seeking its best value is a convex problem; only the sign of inequality multipliers must be added.
(D) is convex regardless of (P): maximize a concave function on a convex set. Any dual-feasible point is already a certificate, guaranteed by the lesson’s simplest and most useful result.
The direct three-line proof is the first guided exercise at the end. Here is another, showing why the dual is the “opposite” problem. Fix x and maximize the Lagrangian over admissible multipliers. If x is feasible, each λifi(x)≤0 and each νjhj(x)=0, so the maximum is attained at λ=0 and equals f0(x). If infeasible, some fi(x)>0 (let λi→∞) or some hj(x)=0 (let νj→±∞) and the maximum is +∞. Thus,
λ⪰0,νsupL(x,λ,ν)={f0(x)+∞if x is feasible,otherwise.⟹p⋆=xinfλ⪰0,νsupL,d⋆=λ⪰0,νsupxinfL.
Constraints are an adversarial player punishing any violation with infinite price, and (D) swaps player order. For any function φ(x,y), supyinfxφ≤infxsupyφ: for every (x′,y′), infxφ(x,y′)≤φ(x′,y′)≤supyφ(x′,y), and take the supremum over y′ on the left and infimum over x′ on the right. This is the minimax inequality, and weak duality is a special case. Swapping order can only help the second player, and strong duality asks when it does not help at all.
The gap: a quality certificate
Two immediate consequences, including p⋆=−∞ or +∞:
If p⋆=−∞, no dual-feasible point exists (any would be a bound ≤−∞). If d⋆=+∞, no primal-feasible point exists.
Suboptimality certificate. If x^ is primal feasible and (λ^,ν^) is dual feasible, then
The primal-dual pair’s duality gap is a verifiable upper bound on error of x^. If zero, x^ is optimal and (λ^,ν^) is optimal for (D). The difference p⋆−d⋆≥0 is called the optimal duality gap: what the dual cannot close.
Check against brute force for n=14 (all 214=16384 candidates fit in memory).
[ ]Dual bound versus brute force for a nonconvex problemBrowser
import numpy as np
rng = np.random.default_rng(4)
n = 14
M = rng.normal(size=(n, n))
W = (M + M.T) / 2
# Los 2^14 candidatos x en {-1, 1}^n: se puede comprobar por fuerza bruta
bits = ((np.arange(2 ** n)[:, None] >> np.arange(n)) & 1) * 2 - 1
p_star = np.einsum("ki,ij,kj->k", bits, W, bits).min()
def phi(nu):
"""Cota válida para todo nu, y un supergradiente."""
w, V = np.linalg.eigh(W + np.diag(nu))
return n * w[0] - nu.sum(), n * V[:, 0] ** 2 - 1
nu, mejor = np.zeros(n), -np.inf
print("iteración cota actual mejor cota")
for k in range(1, 801):
val, g = phi(nu)
mejor = max(mejor, val)
if k in (1, 10, 100, 800):
print(f"{k:9d} {val:11.3f} {mejor:10.3f}")
nu = nu + g / np.sqrt(k) # ascenso por supergradiente
# Una solución factible por redondeo del autovector
v = np.linalg.eigh(W)[1][:, 0]
x_h = np.where(v >= 0, 1.0, -1.0)
f_h = x_h @ W @ x_h
print(f"\nheurística de signos: f0 = {f_h:.3f}")
print(f"cota dual inicial n*lambda_min = {n * np.linalg.eigvalsh(W)[0]:.3f}; cota tras el ascenso = {mejor:.3f}")
print(f"certificado: la heurística está a {f_h - mejor:.3f} del óptimo (error relativo {100 * (f_h - mejor) / abs(mejor):.1f} %)")
print(f"verdad (fuerza bruta): p* = {p_star:.3f}, distancia real de la cota al óptimo p* - cota = {p_star - mejor:.3f}")
The first bound (ν=0 in φ, that is nλmin) is −59.39, far below, and ascent raises it to −46.935. The sign heuristic turns out to be exactly optimal (−44.99), but without knowing that, the certificate already says it is within 1.95, or 4.1%. The gap p⋆−d⋆ is nonzero (the problem is nonconvex): solving the dual SDP with a solver gives d⋆=−46.90, so ascent stopped 0.04 from the best possible price and the true gap is 1.91. No ν closes it: this is a limit of the dual, not the ascent algorithm.
Dual geometry: the (u,t) plane
With one constraint, f1(x)≤0, the entire dual fits in one picture. Each point x in space maps to a plane point (u,t)=(f1(x),f0(x)), and their set is
G={(f1(x),f0(x)):x∈Rn}⊂R2.
Both theoretical quantities have direct interpretations. The primal optimum is the lowest point of G in the feasible half-plane u≤0, p⋆=inf{t:(u,t)∈G,u≤0}. And since L(x,λ)=t+λu at (u,t),
g(λ)=(u,t)∈Ginf(λu+t),
which is the inner product of (λ,1) and (u,t) minimized over G. It is the height of line t=g(λ)−λu, of slope −λ, lying below G and touching it (a supporting line): g(λ) is its intercept on the t axis. And d⋆ is the highest intercept among supporting lines of nonpositive slope.
InteractiveDuality in the (u, t) plane
G={(f1(x),f0(x))}
supporting line, slope −λ
convex hull of A
p⋆
The dual function g(λ): concave and always below p⋆
Problem
λ1.00
g(λ) (t-intercept)0.750
p⋆ (primal optimum)1.000
d⋆=maxλg1.000
gap p⋆−d⋆0.000
Strong duality: the line with λ⋆=2.00 passes through (0,p⋆) and d⋆=p⋆. minx2 subject to 1−x≤0. G is a parabola and A is convex: the supporting line at λ⋆=2 passes through (0,p⋆).
What is the dual function in the (u,t) plane and when does the best line touch the optimum? The thick, text-colored curve is G and the gray region is A=G+R+2 (everything above and to the right). Rotate the supporting line with λ: its t-axis intercept is g(λ) (lower panel). In “Convex”, λ⋆=2 raises it to (0,p⋆) and g reaches p⋆. In “Nonconvex”, the well of f0 at x=0 (infeasible) makes A nonconvex; increase κ and see the convex envelope (magenta) cross the t axis below p⋆: that gap is the duality gap. In “No Slater” the problem is convex but only x=0 is feasible, and no finite-slope line passes through (0,1).
Three observations about the figure:
Weak duality in one sentence. A supporting line of slope −λ≤0 rises leftward: points of G with u≤0 lie above it, in particular above its height g(λ) at u=0. Hence p⋆≥g(λ), and λ≥0 is needed: positive slope would make the line decrease leftward and the conclusion fail.
The dual sees only the convex envelope. The infimum of linear function λu+t is the same over G, A and either convex envelope, so g and d⋆ depend only on the convex envelope boundary of A at u=0. If A is already convex, that boundary is G‘s and nothing is lost. Otherwise the gap p⋆−d⋆ is the vertical distance between G and its envelope at u=0.
Convexity alone is not quite enough. In the third case A is convex, but the only supporting line at (0,p⋆) is vertical and corresponds to no finite λ. An assumption ruling out vertical lines is needed: Slater’s condition.
Strong duality
Strong duality does not always hold, even for convex problems. It holds with a qualification such as Slater’s, seen in the previous lesson as one condition guaranteeing KKT. Its role here is to rule out the vertical line.
Proof
By Slater, p⋆<+∞; if p⋆=−∞, weak duality gives d⋆=−∞ and nothing remains. Let p⋆ be finite. Define two sets in Rm×Rp×R:
Both are convex: B is an open segment, and if (u,v,t) and (u′,v′,t′) lie in A with witnesses x and x′, witness θx+(1−θ)x′ satisfies inequalities for the convex combination by convexity of fi, and equality by affinity. They are disjoint: a common point (0,0,s) would have feasible x with f0(x)≤s<p⋆, impossible.
By the separating hyperplane theorem for two disjoint convex sets (obtained from the point-versus-closed-convex-set version, applied to 0∈/A−B; if 0 lies in the closure, separate points zk→0 outside it and take a limit of unit normals), there are (λ~,ν~,μ)=0 and α with
λ~⊤u+ν~⊤v+μt≥α∀(u,v,t)∈A,μs≤α∀s<p⋆.
Since ui and t can increase without limit inside A, the first inequality forces λ~⪰0 and μ≥0. The second gives μp⋆≤α. Using points (f1(x),…,fm(x),Ax−b,f0(x)) in the first yields, for every x,
i∑λ~ifi(x)+ν~⊤(Ax−b)+μf0(x)≥α≥μp⋆.(∗)
Case μ>0. Dividing by μ, L(x,λ~/μ,ν~/μ)≥p⋆ for every x, that is g(λ~/μ,ν~/μ)≥p⋆. Weak duality makes this equality and the dual is attained there.
Case μ=0 (where Slater enters). Then (∗) says ∑iλ~ifi(x)+ν~⊤(Ax−b)≥0 for every x. At x^ the second term vanishes and ∑iλ~ifi(x^)≥0 remains with every fi(x^)<0 and λ~i≥0: possible only if λ~=0. Then ν~⊤(Ax−b)≥0 for every x∈Rn: an affine function bounded below on the whole space is constant, so A⊤ν~=0 and, by the rank of A, ν~=0. But then (λ~,ν~,μ)=0, contradicting nonzero. The case μ=0 is impossible. ■
∎
The proof is the figure: separating A from B means finding the supporting line at (0,p⋆), and μ=0 is the vertical line Slater rules out. Four nuances:
Slater is sufficient, not necessary. Problems without a strictly feasible point may have strong duality.
Affine constraints need not be strict. In the refined version, strict feasibility is needed only for non-affine fi, and ordinary feasibility for affine ones. In particular, an LP with finite optimum always has strong duality and the dual attains its optimum, without further checks (Boyd and Vandenberghe, §5.2.3 and §5.2.4).
Proper domains. If f0 or fi are defined only on a domain, the Slater point must be in its relative interior.
Convex without Slater, with a gap. With variables (x,y) and domain y>0, minimizing e−x subject to x2/y≤0 is convex; the constraint forces x=0 and p⋆=1. But L=e−x+λx2/y has infimum 0 for every λ≥0 (take y→∞ then x→∞), so d⋆=0<1=p⋆. This is the figure’s third case.
Strong duality and KKT: the same story
The preceding lesson ended with KKT conditions for deciding optimality. Duality explains them: they are exactly the conditions for zero gap.
Proof
With strong duality, f0(x⋆)=g(λ⋆,ν⋆)=infxL(x,λ⋆,ν⋆)≤L(x⋆,λ⋆,ν⋆)=f0(x⋆)+∑iλi⋆fi(x⋆)≤f0(x⋆), where the last step uses λi⋆≥0, fi(x⋆)≤0 and hj(x⋆)=0. The chain starts and ends at the same number, so all inequalities are equalities: the first says x⋆ attains the infimum of L(⋅,λ⋆,ν⋆) (and, if differentiable, ∇xL=0: stationarity); the second says ∑iλi⋆fi(x⋆)=0 with all terms ≤0, i.e. complementary slackness. The converse is the preceding lesson’s sufficiency argument: with λ⋆⪰0 the Lagrangian is convex in x and its gradient vanishes at x⋆, so g(λ⋆,ν⋆)=L(x⋆,λ⋆,ν⋆)=f0(x⋆). ■
∎
Rewriting the gap makes it practical. If x^ is feasible and minimizes L(⋅,λ^,ν^) (so g=L(x^,λ^,ν^)), then
The gap is total violation of complementary slackness: each inactive constraint with positive multiplier contributes a piece. Interior-point methods exploit this identity: they maintain “controlled” slack λifi=−1/τ and the gap is m/τ.
Examples: duals of familiar problems
A good habit when deriving a dual is to follow three steps: write the Lagrangian, minimize over x (recording which multipliers give a finite minimum), and substitute. Four frequently reused cases.
Standard-form linear program. To minimize c⊤x with Ax=b and x⪰0 (inequalities −xk≤0 have multipliers λk≥0), L=c⊤x−λ⊤x+ν⊤(Ax−b)=(c+A⊤ν−λ)⊤x−b⊤ν. It is linear in x: its infimum is −∞ unless the coefficient vanishes, when it equals −b⊤ν. Thus
g(λ,ν)={−b⊤ν−∞if A⊤ν−λ+c=0,otherwise,y el dual esmaxb⊤ysubject toA⊤y⪯c,
with y=−ν (multiplier λ is eliminated: it is slack s=c−A⊤y⪰0). The implicit constraint of g has become the dual constraint. For an inequality-form LP, minimizing c⊤x with Ax⪯b, the same calculation gives maximizing −b⊤λ with A⊤λ+c=0 and λ⪰0. The production problem, maximizing p⊤x with Ax⪯b and x⪰0 (profits p, resources b), has dual minimizing b⊤y with A⊤y⪰p and y⪰0: set resource prices y so making each product earns no more than its resource cost. This is the shadow price of the sensitivity section. By refined Slater, a finite LP optimum guarantees strong duality, characterized by complementary slackness xksk=0: a product is made only when resource cost equals profit, and a positively priced resource is exhausted.
Quadratic program. To minimize 21x⊤Px+q⊤x with P≻0 and Ax⪯b, L=21x⊤Px+(q+A⊤λ)⊤x−b⊤λ is strictly convex quadratic in x, minimized at x=−P−1(q+A⊤λ), so
g(λ)=−21(q+A⊤λ)⊤P−1(q+A⊤λ)−b⊤λ,λ⪰0.
The dual of a QP is another, concave QP with only sign constraint λ⪰0; recover the primal as x⋆=−P−1(q+A⊤λ⋆). This is the support vector machine dual form, where quadratic-term matrix AP−1A⊤ is a Gram matrix of data (inner products), enabling kernels.
Minimum-norm least squares. Minimize ∥x∥22 with Ax=b, A∈Rm×n with m<n and rank m. Here L=x⊤x+ν⊤(Ax−b) is minimized at x=−21A⊤ν and
g(ν)=−41A⊤ν22−b⊤ν.
It is concave and its maximum is at ∇g=−21AA⊤ν−b=0, that is ν⋆=−2(AA⊤)−1b. Recovering the primal, x⋆=A⊤(AA⊤)−1b=A+b, the pseudoinverse solution from the pseudoinverse and minimum-norm solution lesson: the dual derives it without knowing the pseudoinverse. Constraints are affine, so strong duality is guaranteed.
[ ]Dual of minimum-norm least squaresBrowser
import numpy as np
rng = np.random.default_rng(2)
A = rng.normal(size=(3, 7)); b = rng.normal(size=3)
g = lambda nu: -0.25 * np.sum((A.T @ nu) ** 2) - b @ nu # función dual de min ||x||² s.a. Ax = b
nu_star = -2 * np.linalg.solve(A @ A.T, b) # su máximo: grad g = 0
x_star = -0.5 * A.T @ nu_star # minimizador de L(·, nu*)
print("g(nu*) =", round(g(nu_star), 8), " ||x*||² =", round(x_star @ x_star, 8))
print("x* coincide con la pseudoinversa A⁺b:", np.allclose(x_star, np.linalg.pinv(A) @ b))
print("nu* maximiza g (1000 perturbaciones al azar):", all(g(nu_star + rng.normal(size=3)) <= g(nu_star) + 1e-12 for _ in range(1000)))
Lasso. Minimizing P(x)=21∥Ax−b∥22+λ∥x∥1 has no constraints, hence no dual until one is created: introduce z=Ax−b as a new variable with multiplier ν. Then L=21∥z∥2+λ∥x∥1+ν⊤(Ax−b−z) separates into z and x:
infz(21∥z∥2−ν⊤z)=−21∥ν∥2 (at z=ν);
infx(λ∥x∥1+(A⊤ν)⊤x) is 0 if A⊤ν∞≤λ and −∞ otherwise: if any (A⊤ν)k>λ, take x along that axis with suitable sign and the term decreases without bound; if all satisfy the bound, λ∣xk∣+(A⊤ν)kxk≥0.
With substitution θ=−ν and adding and subtracting 21∥b∥2, the dual is
θmaxD(θ)=21∥b∥2−21∥θ−b∥2subject toA⊤θ∞≤λ.
The lasso dual is a projection: find the point of polytope {θ:A⊤θ∞≤λ} nearest b. Strong duality holds (the problem is convex and constraint z=Ax−b affine), and the dual solution is the residual, θ⋆=b−Ax⋆. This yields three things:
A dual bound for any x. Residual b−Ax usually violates the θ constraint, but scaling fixes it: θ=α(b−Ax) with α=min{1,λ/A⊤(b−Ax)∞} is dual feasible. With it, the duality gap at x is P(x)−D(θ).
Complementary slackness. Stationarity says A⊤θ⋆∈λ∂∥x⋆∥1, meaning ak⊤θ⋆=λsign(xk⋆) if xk⋆=0 and ak⊤θ⋆≤λ if zero (with ak column k of A). In particular, ak⊤θ⋆<λ implies xk⋆=0: inactive variables can be identified from the dual.
Safe variable screening.D is strongly concave with modulus 1, so for any dual-feasible θ, 21∥θ−θ⋆∥2≤D(θ⋆)−D(θ)≤P(x)−D(θ)=gap, meaning θ⋆ lies in a ball of radius 2gap around θ. If ak⊤θ+∥ak∥2gap<λ, then ak⊤θ⋆<λ and xk⋆=0with certainty: the variable can be removed. The smaller the gap, the more variables can be screened. This is the idea of Fercoq, Gramfort and Salmon’s (2015) Gap Safe rules.
The gap as a stopping criterion
We now have everything for a guaranteed solver. The interactive runs proximal descent (iterations xk+1=Sλ/L(xk−L1A⊤(Axk−b)), the method of the proximal methods lesson; the choice does not matter) on a lasso with 40 rows and 60 columns, and calculates each iteration’s primal value P(xk), scaled dual bound D above, and their difference.
InteractivePrimal and dual converging
P(xk) primal
D dual bound
p⋆
gap P−D
true suboptimality P−p⋆
tolerance ε
k = 0
Dual point
iteration k0
primal P(xk)6.5008
dual bound D0.7567
gap P−D5.74e0
true suboptimality P−p⋆4.93e0
D≤p⋆?yes, a bound
A solver with ε=3.2⋅10−2 stops at k=504: gap =3.1⋅10−2≤ε, and true suboptimality, 1.3⋅10−4, is no greater. The certificate is conservative but never lies.
When can a solver stop without knowing the optimum? Above, primal value (blue) decreases and dual bound (aqua) increases; optimum p⋆ always lies between them. Below, on a logarithmic scale, gap (magenta) and true suboptimality P−p⋆ (blue), calculable only afterward with very precise p⋆. Move the tolerance: the cursor jumps to the first iteration with gap below ε, and true suboptimality always stays below the gap. “Best so far” stores the best dual bound seen. “Unscaled” uses the raw residual, an infeasible dual point: the “bound” lies above p⋆ (starts at P(0) and decreases toward it), the gap becomes zero or negative, and the solver would stop falsely.
As you interact, see that the gap always bounds true suboptimality. Initially both are of the same order, but as iterations advance the slack grows to several orders of magnitude (at iteration 800, gap 2⋅10−3 versus suboptimality 8⋅10−7), because the scaled dual point converges more slowly than the primal: the gap is a conservative certificate that never lies but certifies less than the iterate has achieved. With the unscaled point, the dual bound starts exactly at P(0), well above p⋆: at x0=0 the unscaled residual is −b, its dual value is 21∥b∥2=P(0) and the “gap” is 0; in later iterations it is negative. A stopping rule based on it would terminate at iteration 0.
Convex conjugate and Fenchel duality
One part of duality needs no constraints. Examining the infimum of L over x for lasso led to calculating supx(y⊤x−λ∥x∥1): the height to which a line of given slope rises without crossing a function. This is the conjugate, and its table of results helps derive duals in sequence.
The geometric interpretation is the dual’s: for each slope y, line (or hyperplane) x↦y⊤x−f∗(y) is the largest affine function of slope y lying below f, and −f∗(y) is its intercept. Immediately: f(x)≥y⊤x−f∗(y) for every x. Four frequently used properties:
f∗ is convex and closed, regardless of f: it is a supremum of affine functions of y (dual to “the dual function is concave”).
Fenchel-Young inequality.f(x)+f∗(y)≥y⊤x for all x,y, the definition rewritten. Equality holds iff x maximizes y⊤x−f(x), meaning (for convex f) y∈∂f(x), and for differentiable f, y=∇f(x).
Biconjugate.f∗∗ is the largest closed convex function below f (its closed convex envelope). Indeed f∗∗(x)=supy(y⊤x−f∗(y)) is the supremum of affine minorants of f (one per slope), and a supremum of affine minorants is the largest closed convex function below f, because a closed convex function is the supremum of its affine minorants (from separating the epigraph from points below). In particular, f∗∗=f iff f is convex and closed (Fenchel-Moreau theorem). With nonconvex f, the conjugate “sees” only what a line can touch from below.
Differentiability and gradient. If f is strictly convex and differentiable, f∗ is differentiable in the interior of its domain and there ∇f∗=(∇f)−1: the gradient of f∗ at y is the contact point. (With f=ex, f∗ is finite at y=0 but not differentiable there: the horizontal line never touches.)
The figure sweeps the slope and shows the conjugate being traced.
InteractiveThe conjugate as envelope of tangents
The function f(x)=21x2 and the line of slope y touching it from below
Its conjugate f∗(y)=21y2, traced progressively
y = −3.00
f
line of slope y (tangent from below)
f∗
f(x)+f∗(y)−xy≥0
f∗∗
slope y−3.00
f∗(y)4.500
line intercept at x=0 (−f∗)−4.500
contact x⋆ (with y∈∂f(x⋆))−3.00
f(x)+f∗(y)−xy, at test x10.125
It is its own conjugate: the only function with f∗=f. The line of slope y touches at x=y.
Which line of slope y touches f from below, and what height does it reach at the origin? Play the y sweep (or drag the timeline): the orange line of slope y touches f at the contact point, its intercept at x=0 is −f∗(y), and the graph of f∗ (below) is traced. The slider's test x measures vertical distance between f and the line, f(x)+f∗(y)−xy≥0 (Fenchel-Young), zero only at contact. With ∣x∣ and ex, some slopes have no line below (f∗=+∞). For the nonconvex double-well function, enable f∗∗: no line touches the central peak, and the biconjugate flattens it.
Conjugates to know
f(x)
f∗(y)
Domain of f∗
21∥x∥22
21∥y∥22
Rn
21x⊤Qx, Q≻0
21y⊤Q−1y
Rn
a norm ∥x∥
0 if ∥y∥∗≤1, +∞ otherwise
dual norm ball
21x2+∣x∣ (on R)
21(∣y∣−1)+2
R
ex
ylny−y (with 0ln0=0)
y≥0
log∑iexi
∑iyilnyi
y⪰0, 1⊤y=1
∑ixilnxi (negative entropy, x⪰0)
∑ieyi−1
Rn
−logx
−1−log(−y)
y<0
indicator 1C(x)
support function supx∈Cy⊤x
Rn if C is bounded
The dual norm is ∥y∥∗=sup{y⊤x:∥x∥≤1}. For norms on ℓp spaces, the dual of ∥⋅∥p is ∥⋅∥q with 1/p+1/q=1 (the dual of ∥⋅∥1 is ∥⋅∥∞, and ∥⋅∥2 is self-dual). Two representative proofs:
Proof
A norm. Let f(x)=∥x∥. If ∥y∥∗≤1, the dual norm definition gives y⊤x≤∥y∥∗∥x∥≤∥x∥, so y⊤x−∥x∥≤0, with equality at x=0: f∗(y)=0. If ∥y∥∗>1, some z has ∥z∥≤1 and y⊤z>1, and with x=tz we have y⊤x−∥x∥≥t(y⊤z−1)→∞ as t→∞: f∗(y)=+∞.
Log-sum-exp. Let f(x)=log∑iexi. If y⪰0 and 1⊤y=1, the gradient of y⊤x−f(x) is y−softmax(x), vanishing at x=logy (with yi>0; take the limit at the boundary), where value is ∑iyilnyi−log∑iyi=∑iyilnyi, and concavity makes it the maximum. If 1⊤y=1, x=t1 gives t(1⊤y−1)−logn, unbounded as t→±∞. If any yi<0, x=−tei gives t∣yi∣−log(n−1+e−t)→∞. ■
∎
The second proof has a noteworthy consequence: the gradient of log-sum-exp is softmax, and the conjugate lives on the simplex and is negative entropy. (Without the simplex constraint, negative entropy ∑ixilnxi has conjugate ∑ieyi−1: maximum of yx−xlnx occurs at x=ey−1.) Softmax and entropy are Legendre duals, explaining their appearance together in cross-entropy, maximum entropy, and entropy regularization.
[ ]Numerical conjugates and the Fenchel-Young inequalityBrowser
import numpy as np
xs = np.linspace(-12, 12, 24001) # rejilla fina: f*(y) = max_x (y x - f(x))
def conjugada(f, y):
return np.max(y * xs - f(xs))
casos = {
"½x²": (lambda x: 0.5 * x**2, lambda y: 0.5 * y**2, [-2.0, 0.7, 3.0]),
"½x² + |x|": (lambda x: 0.5 * x**2 + np.abs(x), lambda y: 0.5 * max(abs(y) - 1, 0) ** 2, [-3.0, 0.5, 3.0]),
"eˣ": (np.exp, lambda y: y * np.log(y) - y, [0.5, 1.0, 4.0]),
"log(1 + eˣ)": (lambda x: np.logaddexp(0, x), lambda y: y * np.log(y) + (1 - y) * np.log(1 - y), [0.1, 0.5, 0.9]),
}
for nombre, (f, fstar, ys) in casos.items():
err = max(abs(conjugada(f, y) - fstar(y)) for y in ys)
print(f"{nombre:12s} f*(y) numérica frente a la fórmula: error máximo {err:.1e}")
f, fstar = casos["½x² + |x|"][0], casos["½x² + |x|"][1]
print("f*(3) para ½x² + |x| =", round(conjugada(f, 3.0), 6))
# Desigualdad de Fenchel-Young: f(x) + f*(y) >= x y, con igualdad solo en el contacto
rng = np.random.default_rng(0)
peor = min(f(x) + fstar(y) - x * y for x, y in rng.uniform(-2, 2, size=(2000, 2)))
print("f(x) + f*(y) - xy >= 0 en 2000 pares al azar:", peor >= -1e-12)
print("en el contacto x* = 2, y = 3 (f'(2) = 3):", f(2.0) + fstar(3.0) - 2.0 * 3.0)
# f** de una función no convexa: su envolvente convexa
g = lambda x: (x**2 - 1) ** 2
yc = np.linspace(-40, 40, 801)
gs = np.array([conjugada(g, y) for y in yc])
for x in (0.0, 0.5, 1.0, 1.5):
print(f"x = {x}: f(x) = {g(x):.4f}, f**(x) = {np.max(x * yc - gs):.4f}")
The numerical conjugate agrees with the table formulas, f∗(3)=2 for 21x2+∣x∣ (calculated by hand in an exercise), and Fenchel-Young holds with equality only at contact. For the double well, f∗∗ is 0 on [−1,1] and agrees with f outside: only the function sees the central peak (f(0)=1); no line touches it from below.
Fenchel duality
The conjugate lets us write duals of problems with a sum of two terms without explicit constraints.
Proof
Weak duality is Fenchel-Young used twice: f(x)+f∗(−A⊤y)≥−y⊤Ax and h(Ax)+h∗(y)≥y⊤Ax. Adding, f(x)+h(Ax)≥−f∗(−A⊤y)−h∗(y) for every x and y. Equality under the qualification is strong duality of the equivalent problem “minimize f(x)+h(z) with z=Ax”, whose dual is exactly d⋆ (separation of the Lagrangian in x and z is the lasso construction). For functions finite everywhere this is Slater’s theorem above; for functions equal to +∞ outside a domain, the relative-interior assumption plays the strictly feasible point’s role, and the proof is the same convex separation expressed with relative interiors (Rockafellar, corollary 31.2.1). ■
∎
Lasso is a case with f(x)=λ∥x∥1, whose conjugate is the indicator of {w:∥w∥∞≤λ}, and h(z)=21∥z−b∥2, with h∗(y)=21∥y∥2+b⊤y. The Fenchel dual maximizes −21∥y∥2−b⊤y with A⊤y∞≤λ: the same expression from the z construction. With a conjugate table, deriving a dual is mechanical: a norm becomes its dual ball (hence complexity bounds for linear classes, studied in statistical learning theory, use the data’s dual norm), a quadratic becomes its inverse, and entropy becomes log-sum-exp.
Sensitivity: multipliers are prices
So far the dual has bounded values. Its second major interpretation is that multipliers measure how much a constraint costs. Perturb problem (P) and study how the optimum moves: sensitivity analysis:
with p⋆(0,0)=p⋆. A ui>0relaxes constraint i (gives more room), and ui<0tightens it.
Proof
Let x be feasible for the perturbed problem. Then p⋆=g(λ⋆,ν⋆)≤L(x,λ⋆,ν⋆)=f0(x)+∑iλi⋆fi(x)+∑jνj⋆hj(x)≤f0(x)+λ⋆Tu+ν⋆Tv, where the last inequality uses λi⋆≥0 and fi(x)≤ui, and hj(x)=vj. Thus f0(x)≥p⋆−λ⋆Tu−ν⋆Tv; the infimum over x gives the result. ■
∎
Function u↦p⋆(u,0) lies above hyperplane p⋆−λ⋆Tu, touching it at u=0; read this carefully:
Large λi⋆ means tightening constraint i (ui<0) greatly increases optimal cost: by at least λi⋆∣ui∣. Relaxing it (ui>0) may save a lot.
Small or zero λi⋆ means relaxing it helps little: the optimum cannot improve by more than λi⋆ui. With λi⋆=0 (inactive or degenerate active constraint), nothing is gained to first order.
If p⋆(u,v) is differentiable at the origin, λi⋆=−∂p⋆/∂ui and νj⋆=−∂p⋆/∂vj: the bound is affine below p⋆(⋅) and touching at 0, possible only if slopes agree. The minus sign follows convention fi≤ui: relaxing decreases cost.
In a production problem (maximize profit with limited resources), write −profit as objective and the sign changes: the multiplier is profit increase per resource unit, λi⋆=∂(profit⋆)/∂bi≥0, resource i‘s shadow price: the most one should pay for another unit. Its dual, setting prices y to minimize total resource value b⊤y, says the same: the market price making production and resource sale equally attractive. The calculation recurs in quantitative finance: in a minimum-variance portfolio with target return, its multiplier gives variance cost of each additional required return point, and an exposure limit’s multiplier gives variance added by maintaining it.
InteractiveShadow prices
6x+4y≤b1
x+2y≤b2
profit level curve
c=λ1a1+λ2a2
Optimal profit p⋆ versus b1 (the other availability is fixed)
Resource shown in curve
optimal production (x,y)(3.00, 1.50)
optimal profit p⋆21.00
shadow price λ1 (raw material)0.75
shadow price λ2 (machine hours)0.50
b1λ1+b2λ2 (dual objective)21.00
linear segment of p⋆[12.0, 36.0]
One more unit of raw material is worth 0.75 in profit, only up to b=36.0 (or down to 12.0 if reduced). Outside this interval the price changes.
How much is an extra unit of resource worth, and how far does that price apply? Production LP: max5x+4y with 6x+4y≤b1 (raw material) and x+2y≤b2 (machine hours). Slide b1 or b2: above are the feasible region and optimum, with profit vector c decomposed into the two constraint normals (coefficients are shadow prices). Below, optimal profit versus selected resource: a concave piecewise-linear curve whose slope is the shadow price. Cross a basis change, shown by hollow points, and price jumps: the raw-material slope 0.75 holds only between b1=12 and b1=36. At the basis change the derivative does not exist and the multiplier is nonunique.
In the figure’s LP, with b=(24,6) the optimum is (x,y)=(3,1.5) with profit 21, and c=(5,4)=0.75(6,4)+0.5(1,2): coefficients λ1⋆=0.75 and λ2⋆=0.5 are shadow prices, and strong duality is checked with b⊤λ⋆=24⋅0.75+6⋅0.5=21. The following warning matters as much as the result.
[ ]Shadow prices with HiGHS and finite differencesBrowser
import numpy as np
from scipy.optimize import linprog
c = np.array([5.0, 4.0]) # beneficio por unidad de A y de B
A = np.array([[6.0, 4.0], [1.0, 2.0]]) # consumo de materia prima y de horas de máquina
def resolver(b):
# linprog minimiza: se cambia el signo del beneficio
return linprog(-c, A_ub=A, b_ub=b, bounds=(0, None), method="highs")
r = resolver([24.0, 6.0])
lam = -r.ineqlin.marginals # con la convención de esta lección, lambda >= 0
print("x* =", r.x, " beneficio =", -r.fun)
print("precios sombra de HiGHS:", lam, " -> b·lambda =", np.array([24.0, 6.0]) @ lam)
# Derivada numérica del valor óptimo respecto de b1 y de b2 (diferencias centrales)
h = 1e-3
d1 = (-resolver([24 + h, 6]).fun + resolver([24 - h, 6]).fun) / (2 * h)
d2 = (-resolver([24, 6 + h]).fun + resolver([24, 6 - h]).fun) / (2 * h)
print(f"diferencias finitas: dp/db1 = {d1:.4f}, dp/db2 = {d2:.4f}")
# ¿Hasta dónde vale la aproximación lineal en b1?
print("\n b1 p*(b1) p*(24) + lambda1 (b1 - 24) error")
for b1 in (8, 12, 16, 24, 30, 36, 40):
p = -resolver([b1, 6.0]).fun
lineal = 21.0 + lam[0] * (b1 - 24)
print(f"{b1:5.0f} {p:8.3f} {lineal:18.3f} {p - lineal:14.3f}")
HiGHS returns λ⋆=(0.75,0.5) (with marginals sign reversed: in linprog the multiplier of a ≤ constraint in a minimization problem is ≤0), confirmed by finite differences. The table shows the exact segment: between b1=12 and b1=36 the linear approximation has no error; outside, it lies above the true value (as concavity requires).
Alternative theorems: infeasibility can also be certified
An alternative theorem says that, of two systems of equalities and inequalities, exactly one has a solution. It gives a short proof that one system has no solution: exhibit a solution of the other. Farkas’ is the most used.
The geometry is in the figure: (1) says b lies in the cone generated by columns of A, and (2) says there is a hyperplane y⊥ through the origin with all columns on one side (y⊤ak≥0) and b on the other. This is the separating hyperplane theorem applied to a cone. Both cannot hold: b⊤y=x⊤A⊤y≥0 if x⪰0 and A⊤y⪰0. Showing one always holds is the second guided exercise, with one technical detail: the cone generated by finitely many vectors is closed.
InteractiveFarkas' lemma as a certificate
cone {Ax:x≥0}
certificate y
hyperplane y⊥
Does x≥0 exist with Ax=b?no
y⊤a1 (must be ≥0)2.53
y⊤a2 (must be ≥0)0.00
y⊤a3 (must be ≥0)3.64
y⊤b (must be <0)−2.37
Alternative (II): the hyperplane y⊥ leaves the three columns on one side (A⊤y≥0) and b on the other. It comes from the projection of b onto the cone: y=p−b.
How do we prove b is not a conic combination of columns? Drag b and the three columns ak. If b is inside the blue cone, the panel gives coefficients x⪰0 with Ax=b. Outside, certificate y (magenta) appears: hyperplane y⊥ leaves the cone and three columns on one side (y⊤ak≥0), and b on the other (y⊤b<0). It is the vector from b to its projection onto the cone. Spread the columns until no half-plane contains them all: the cone becomes the whole plane and no certificate is possible.
Infeasibility certificates and their relation to the dual
Applying Farkas to Ax⪯b (split x=x+−x− and add slacks s⪰0, yielding system [A−AI](x+,x−,s)=b with variables ⪰0) gives the most useful form:
Ax⪯b has no solution⟺∃λ⪰0:A⊤λ=0,b⊤λ<0.
An example with three inequalities: x1+x2≤1, −x1≤−1, −x2≤−1. Multipliers λ=(1,1,1) satisfy A⊤λ=0 and b⊤λ=1−1−1=−1<0: adding the three inequalities gives 0≤−1. This proof takes one line to verify.
The connection to the dual is direct. Feasibility problem “minimize 0 with Ax⪯b” has dual function g(λ)=−b⊤λ if A⊤λ=0 and −∞ otherwise. A λ as in the lemma yields g(tλ)=−tb⊤λ→+∞: the dual is unbounded, and weak duality makes the primal infeasible. That is the easy half. The hard half (the lemma) says that for linear systems such a ray always exists: infeasibility is certified by a dual ray without any qualification. Four possible states of an LP and its dual:
Primal
Dual
Comment
finite optimum
finite optimum
p⋆=d⋆
unbounded (p⋆=−∞)
infeasible
the descent direction certifies unboundedness
infeasible
unbounded
a dual ray certifies infeasibility
infeasible
infeasible
possible, though rare
A certificate like this appears whenever a solver returns “infeasible” with a Farkas ray. In machine learning, Gordan’s version (previous lesson) answers a classic question: data (x~i,yi) are strictly linearly separable iff no nonzero θ⪰0 exists with ∑iθiyix~i=0, meaning the origin is not in the convex hull of yix~i. If data are not separable, the certificate is that zero convex combination.
[ ]Infeasibility certificates with HiGHSBrowser
import numpy as np
from scipy.optimize import linprog
# Sistema infactible: x1 + x2 <= 1, x1 >= 1, x2 >= 1 escrito como G x <= h
G = np.array([[1.0, 1.0], [-1.0, 0.0], [0.0, -1.0]])
h = np.array([1.0, -1.0, -1.0])
print("¿factible?", linprog(np.zeros(2), A_ub=G, b_ub=h, bounds=(None, None), method="highs").status == 0)
# Certificado de Farkas: lambda >= 0, Gᵀlambda = 0, hᵀlambda < 0 (se normaliza hᵀlambda = -1)
cert = linprog(np.zeros(3), A_eq=np.vstack([G.T, h]), b_eq=[0, 0, -1], bounds=(0, None), method="highs")
lam = cert.x
print("lambda =", lam.round(4), " Gᵀlambda =", (G.T @ lam).round(12), " hᵀlambda =", round(h @ lam, 6))
# Misma idea para Ax = b, x >= 0: alternativa Aᵀy >= 0, bᵀy < 0
A = np.array([[1.0, 2.0, 1.0], [2.0, 1.0, 1.0]])
for b in (np.array([4.0, 5.0]), np.array([-1.0, 2.0])):
fact = linprog(np.zeros(3), A_eq=A, b_eq=b, bounds=(0, None), method="highs").status == 0
if fact:
print("b =", b, ": existe x >= 0 con Ax = b")
else:
y = linprog(b, A_ub=-A.T, b_ub=np.zeros(3), bounds=(-1, 1), method="highs").x # minimiza bᵀy con Aᵀy >= 0
print("b =", b, ": no existe x >= 0; certificado y =", y.round(3), " Aᵀy =", (A.T @ y).round(3), " bᵀy =", round(b @ y, 3))
The certificates are exact: λ=(1,1,1) is the sum of the three inequalities, and for b=(−1,2) vector y=(1,−0.5) satisfies A⊤y⪰0 with b⊤y=−2<0.
Implementation from scratch
Two pieces: an LP dual derived by hand and solved separately, and the lasso duality gap inside a custom solver that stops with a certificate.
An LP’s dual and feasible pairs
Generate the LP with a strictly positive primal point and y0 giving strict dual slack, making both feasible. Solve separately with HiGHS (scipy.optimize.linprog): primal with A_eq, dual derived by hand in the examples section.
[ ]Primal and dual of an LP: strong duality, slack and feasible pairsBrowser
import numpy as np
from scipy.optimize import linprog
rng = np.random.default_rng(11)
m, n = 4, 9
A = rng.normal(size=(m, n))
x0 = rng.uniform(0.5, 2, n) # un punto estrictamente positivo: el primal es factible
b = A @ x0
y0 = rng.normal(size=m)
c = A.T @ y0 + rng.uniform(0.5, 2, n) # c - Aᵀy0 > 0: el dual es factible
# Primal: min cᵀx s.a. Ax = b, x >= 0
primal = linprog(c, A_eq=A, b_eq=b, bounds=(0, None), method="highs")
# Dual (derivado a mano): max bᵀy s.a. Aᵀy <= c, y libre
dual = linprog(-b, A_ub=A.T, b_ub=c, bounds=(None, None), method="highs")
x, y = primal.x, dual.x
s = c - A.T @ y # holguras duales, s >= 0
print(f"p* = {primal.fun:.6f} d* = {-dual.fun:.6f} (diferencia {abs(primal.fun + dual.fun):.1e})")
print(f"holgura complementaria: max |x_i s_i| = {np.abs(x * s).max():.1e}")
# Dualidad débil: pares (x, y) factibles cualesquiera (combinaciones convexas de puntos factibles)
gaps = []
for _ in range(2000):
t, u = rng.uniform(size=2)
xf = t * x + (1 - t) * x0 # factible: A xf = b, xf >= 0
yf = u * y + (1 - u) * y0 # factible: Aᵀyf <= c
gap = c @ xf - b @ yf
assert abs(gap - (c - A.T @ yf) @ xf) < 1e-9 # identidad del gap: cᵀx - bᵀy = sᵀx
gaps.append(gap)
print(f"2000 pares factibles al azar: gap mínimo {min(gaps):.4f} >= 0, y la identidad cᵀx - bᵀy = sᵀx se cumple")
Optimal values agree to machine precision and complementary slackness xksk=0 holds: at optimum, each positive primal variable has zero dual slack and conversely. For arbitrary feasible pairs the gap is c⊤x−b⊤y=s⊤x≥0, the LP gap form: the gap is the inner product of two nonnegative vectors.
A solver using gap as its stopping criterion
The three pieces are the lasso gap (residual scaled to dual feasibility, as in examples), a primal method (proximal descent), and comparison with true suboptimality, calculable afterward because here p⋆ can be obtained with many iterations.
[ ]Lasso duality gap as a stopping ruleBrowser
import numpy as np
def lasso_primal(x, A, b, lam):
return 0.5 * np.sum((A @ x - b) ** 2) + lam * np.abs(x).sum()
def lasso_duality_gap(x, A, b, lam):
"""Gap de dualidad del lasso en x: P(x) - D(nu), con nu = alpha (Ax - b) factible."""
r = A @ x - b
alpha = min(1.0, lam / max(np.abs(A.T @ r).max(), 1e-300)) # escala hasta ||Aᵀnu||_inf <= lam
nu = alpha * r
dual = -0.5 * nu @ nu - b @ nu
return lasso_primal(x, A, b, lam) - dual
def soft(z, t):
return np.sign(z) * np.maximum(np.abs(z) - t, 0.0)
rng = np.random.default_rng(7)
m, n = 40, 60
A = (0.7 * rng.normal(size=(m, n)) + 0.7 * rng.normal(size=(m, 1))) / np.sqrt(m)
x_true = np.zeros(n); x_true[rng.choice(n, 5, replace=False)] = rng.choice([-1, 1], 5) * rng.uniform(1, 2, 5)
b = A @ x_true + 0.05 * rng.normal(size=m)
lam = 0.06 * np.abs(A.T @ b).max()
L = np.linalg.norm(A, 2) ** 2
# p* con muchas iteraciones de FISTA (solo para comparar a posteriori)
y, xf, t = np.zeros(n), np.zeros(n), 1.0
for _ in range(4000):
xn = soft(y - A.T @ (A @ y - b) / L, lam / L)
tn = (1 + np.sqrt(1 + 4 * t * t)) / 2
y, xf, t = xn + (t - 1) / tn * (xn - xf), xn, tn
p_star = lasso_primal(xf, A, b, lam)
def ista(tol, max_iter=5000):
x = np.zeros(n)
for k in range(max_iter + 1):
gap = lasso_duality_gap(x, A, b, lam)
if gap <= tol:
return x, k, gap
x = soft(x - A.T @ (A @ x - b) / L, lam / L)
return x, max_iter, gap
for tol in (1e-1, 1e-2, 1e-3):
x, k, gap = ista(tol)
sub = lasso_primal(x, A, b, lam) - p_star
print(f"tol = {tol:.0e}: parada en k = {k:4d}, gap = {gap:.2e}, subóptimo real = {sub:.2e} (subóptimo <= gap: {sub <= gap})")
# El criterio ingenuo «el paso es pequeño» no certifica nada
x, k = np.zeros(n), 0
while True:
xn = soft(x - A.T @ (A @ x - b) / L, lam / L)
if np.linalg.norm(xn - x) < 1e-3: break
x, k = xn, k + 1
print(f"criterio ||x_k+1 - x_k|| < 1e-3: parada en k = {k}, subóptimo real = {lasso_primal(x, A, b, lam) - p_star:.2e}, gap = {lasso_duality_gap(x, A, b, lam):.2e}")
For each tolerance the solver stops with the gap below it and true suboptimality, unknown to the solver, is always smaller. The step-size criterion also stops, but does not know how far remains: only the gap, independent of knowing p⋆, supplies the number. For a worse-conditioned problem a small step and large error can coexist.
The library version
In practice the solver returns the dual. With cvxpy, each constraint carries its multiplier in dual_value (nonnegative under this lesson’s ≤ convention) and problem.value gives primal value. With HiGHS in scipy.optimize.linprog, multipliers appear in res.ineqlin.marginals and res.eqlin.marginals (with minimization sign: negated for a ≤ constraint, as in the shadow-price cell). For lasso, sklearn.linear_model.Lasso exposes dual_gap_, the gap at the scale of its own objective 2n1∥y−Xw∥2+α∥w∥1, unlike this lesson’s (which does not divide by n).
import cvxpy as cpx = cp.Variable(n)restr = [G @ x <= h]prob = cp.Problem(cp.Minimize(0.5 * cp.quad_form(x, P) + q @ x), restr)prob.solve()lam = restr[0].dual_value # multiplicadores de las desigualdades, >= 0print(prob.value, lam) # valor primal y precios sombra
Common mistakes
Exercises
ProofWeak duality, step by step
Prove: Let (P) be any problem, convex or not, with optimal value p⋆. For all λ⪰0 and ν, g(λ,ν)≤p⋆.
0
If no feasible points exist, p⋆=+∞ and nothing remains to prove. Otherwise fix any feasible x~ and compare g with f0(x~).
Step 1 of 4. For feasible x~ and λ⪰0, how does ∑iλifi(x~)+∑jνjhj(x~) compare with 0?
CodeThe lasso duality gap
Implement lasso_duality_gap(x, A, b, lam) to return duality gap P(x)−D(ν) of lasso P(x)=21∥Ax−b∥22+λ∥x∥1 at x. Construct the dual point by scaling the residualr=Ax−b: ν=αr with α=min{1,λ/A⊤r∞} (if A⊤r=0, α=1), satisfying A⊤ν∞≤λ, with dual value D(ν)=−21∥ν∥2−b⊤ν.
import numpy as np
def lasso_duality_gap(x, A, b, lam):
"""Gap de dualidad P(x) - D(nu) del lasso, con nu = alpha (Ax - b) dual factible."""
# tu código: valor primal, residuo, escala alpha, valor dual y su diferencia
return 0.0
Shift+Enter to run
NumericA conjugate by hand
Let f(x)=21x2+∣x∣. Calculate its convex conjugate at y=3, that is, f∗(3)=supx(3x−f(x)).
NumericHow far the shadow price applies
In production LP max5x+4y subject to 6x+4y≤b1, x+2y≤6, x,y≥0, optimal profit at b1=24 is 21, with shadow price λ1=0.75 for b1. How much does optimal profit increase if b1 rises from 24 to 40?
ProofFarkas' lemma from a separating hyperplane
Prove: Let A∈Rm×n and b∈Rm. Exactly one is true: (I) there exists x⪰0 with Ax=b; (II) there exists y with A⊤y⪰0 and b⊤y<0.
0
Let C={Ax:x⪰0} be the cone generated by columns of A. (I) means b∈C. First prove both cannot hold, then that failure of (I) implies (II).
Step 1 of 4. Why can (I) and (II) not both hold?
QuizWhat the dual guarantees without convexity
For a nonconvex optimization problem (arbitrary f0,fi,hj), which statements about its Lagrange dual are always true?
More than one answer may be correct.
QuizIs strong duality guaranteed?
For which problems is strong duality d⋆=p⋆ guaranteed by this lesson's results?
More than one answer may be correct.
QuizReading a certificate
A solver returns feasiblex^ with f0(x^)=10.4 and a dual-feasible point (λ^,ν^) with g(λ^,ν^)=9.7. What can be asserted with certainty?
Summary
Key idea
The dual function g(λ,ν)=infxL is always concave and, with λ⪰0, always lower-bounds the optimum: d⋆≤p⋆. Gap f0(x^)−g of a feasible primal-dual pair certifies the quality of x^ without knowing p⋆; under convexity and Slater’s condition the gap can be driven to zero. Optimal multipliers are also derivatives of optimal value with respect to constraints: shadow prices.
Dual function. Infimum of affine functions in (λ,ν): always concave, with a domain to write down because dual constraints live there.
Weak duality.d⋆≤p⋆ without assumptions. The dual exchanges infsup for supinf; in the (u,t) plane it is a supporting line of slope −λ≤0 whose t-axis intercept lies below every feasible point.
Strong duality. With convexity and Slater (or feasible affine constraints), d⋆=p⋆ and the dual is attained. The proof separates A from B; Slater rules out a vertical hyperplane. Without it a gap can occur even when convex, and without convexity the gap measures loss from convexification.
KKT as zero gap. With strong duality primal and dual optima satisfy KKT; for convex problems KKT implies zero gap. For feasible x^ minimizing L, the gap is ∑iλ^i∣fi(x^)∣: complementary-slackness violation.
Useful duals. LP (maxb⊤y with A⊤y⪯c), QP (another QP), minimum norm (gives the pseudoinverse), and lasso (projection onto {A⊤θ∞≤λ}, with gap-based safe screening).
Conjugate and Fenchel.f∗(y)=supx(y⊤x−f(x)) is convex; Fenchel-Young and f∗∗ = closed convex envelope. Norm ↔ dual ball, quadratic ↔ inverse, log-sum-exp ↔ entropy. Fenchel duality gives max−f∗(−A⊤y)−h∗(y) for minf(x)+h(Ax).
Sensitivity.p⋆(u)≥p⋆−λ⋆Tu and λi⋆=−∂p⋆/∂ui: a constraint’s price, local until the next basis change.
Alternatives and certificates. Farkas: Ax=b, x⪰0 has a solution or there is y with A⊤y⪰0 and b⊤y<0. Infeasibility is certified by a dual ray, and every LP solver response (optimal, infeasible or unbounded) can carry a certificate verifiable in linear time.
Where it returns. The SVM dual permits the kernel trick; interior-point and augmented Lagrangian and ADMM methods work with primal and dual together; and the dual of an MDP’s linear problem with occupancy measures connects to constrained reinforcement learning.