Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsOptimization

Constrained optimization and Lagrange multipliers

P1.F740 min●●○ IntermediateReviewed Dec 1, 2026

Why this matters for machine learning

Many ML problems say “find the best parameters, but they must obey a rule”: probabilities must add to 1, a direction must have length 1, a margin must be at least 1. Lagrange multipliers turn the rule into extra equations, and the multiplier tells you what the rule costs.

  • A support vector machine maximizes the margin subject to every training point being on the correct side. The points that touch the constraint are the support vectors. (P3.B6: Support Vector Machines)
  • PCA looks for the unit-length direction with the largest variance. Maximizing a quadratic form on the unit circle gives the top eigenvector. (P3.C3: Principal Component Analysis)
  • The maximum-likelihood probabilities of a categorical variable are the observed frequencies, and the proof is one Lagrange multiplier for the rule that probabilities add to 1. (P1.D10: Maximum Likelihood Estimation)
  • Ridge regularization can be read as a penalty on the weights or as a constraint on their length. The two views are linked by a multiplier. (P3.A6: Regularization: L1 and L2)

Before this: Convex vs. non-convex, The gradient, Directional derivatives

After this lesson you can

  • Explain with a picture why, at a constrained optimum on a curve, the gradient of f is parallel to the gradient of the constraint
  • Set up the Lagrangian, solve the Lagrange conditions for a small problem by hand, and decide which candidate is the minimum and which the maximum
  • Say what the multiplier means (how fast the best value changes when the constraint level changes) and check it with numbers
  • State the KKT conditions for an inequality constraint, tell an active constraint from an inactive one, and name the standard practical methods (substitution, penalties, projection, reparameterization)

A hiker wants the lowest point of a landscape. In P1.F1 to P1.F6 the hiker could go anywhere. Now the hiker must stay on a trail. The bottom of the valley may be far from the trail, so the best point on the trail is a different question, and gradient descent walks straight off the path unless something stops it.

This lesson is about that question. The central picture is small: the best point on the trail is where the trail just touches a contour line of the landscape. From that picture comes one of the most used tools in applied mathematics, the Lagrange multiplier, and from it a short list of conditions (the KKT conditions) that reach into support vector machines.

Constraints, and why they change the answer

An optimization problem (P1.F1) minimizes an objective f(x)f(\mathbf{x}) over the parameters x\mathbf{x}. A constraint is a rule the parameters must obey. Two kinds matter.

  • An equality constraint pins the point to a curve or surface: g(x)=cg(\mathbf{x})=c.
  • An inequality constraint keeps the point inside a region: g(x)≤cg(\mathbf{x})\le c.

The points that obey every constraint form the feasible set. We write the problem as

min⁡x f(x)subject tog(x)=c.\min_{\mathbf{x}}\ f(\mathbf{x})\quad\text{subject to}\quad g(\mathbf{x})=c .

The unconstrained minimum may sit outside the feasible set, and then it is not an answer. Take f(x,y)=x2+y2f(x,y)=x^2+y^2, a bowl with its bottom at (0,0)(0,0) where f=0f=0. Add the constraint x+y=2x+y=2. The point (0,0)(0,0) has x+y=0x+y=0, so it is not feasible. Which feasible point has the smallest ff?

Method 1: solve the constraint for one variable

When the constraint is simple, use it to remove a variable. From x+y=2x+y=2 we get y=2−xy=2-x, so on the constraint f=x2+(2−x)2=2x2−4x+4f=x^2+(2-x)^2=2x^2-4x+4. This is an ordinary one-variable problem (P1.F1): f′=4x−4=0f'=4x-4=0 gives x=1x=1, then y=1y=1, and f=2f=2. The best feasible point is (1,1)(1,1).

This works only if you can solve for a variable. On a circle x2+y2=5x^2+y^2=5 you would get y=±5−x2y=\pm\sqrt{5-x^2}, two branches with a square root. Lagrange’s method avoids that, and it also gives something extra: the multiplier.

The picture: the contour touches the constraint

Draw the contour lines of ff (P1.C5): lines of equal ff. Draw the constraint curve on top. You may only move along the curve.

Suppose at some point the curve crosses a contour line. Then one way along the curve goes to a contour with a lower value and the other way to a higher one. So this point is not a minimum, and not a maximum either. You can only stop where the curve and a contour line touch: they share a tangent line. Touching is necessary but not sufficient: a curve can touch a contour line and still cross it (see the pitfalls below).

Here is the same fact in the language of slopes (P1.C6). Let t\mathbf{t} be a unit vector along the curve at the current point. The slope of ff in that direction is ∇f⋅t\nabla f\cdot\mathbf{t}. At a minimum or a maximum along the curve this slope is zero:

∇f⋅t=0,\nabla f\cdot\mathbf{t}=0 ,

which says that ∇f\nabla f is perpendicular to the curve.

Now look at the constraint function gg. Moving along the curve does not change gg, which is equal to cc all the way. This is the same argument as in P1.C5: a step along a contour line of gg changes gg by about ∇g⋅t=0\nabla g\cdot\mathbf{t}=0, so ∇g\nabla g is perpendicular to the curve too. In two dimensions there is only one direction perpendicular to a curve (up to a sign and a length), so ∇f\nabla f and ∇g\nabla g point along the same line. If ∇g≠0\nabla g\ne\mathbf{0}, that means

∇f=λ ∇gfor some number λ.\nabla f=\lambda\,\nabla g\quad\text{for some number }\lambda .

The number λ\lambda is the Lagrange multiplier. It is positive when the two gradients point the same way and negative when they point opposite ways. With more variables the argument is the same: ∇f\nabla f must be perpendicular to every direction that stays on the constraint surface, which puts it in the line spanned by ∇g\nabla g.

The Lagrangian and the recipe

Packaging the two conditions ∇f=λ∇g\nabla f=\lambda\nabla g and g=cg=c into one object gives the Lagrangian

L(x,λ)=f(x)−λ(g(x)−c).\mathcal{L}(\mathbf{x},\lambda)=f(\mathbf{x})-\lambda\bigl(g(\mathbf{x})-c\bigr).

Set all its partial derivatives to zero. The derivative with respect to x\mathbf{x} is ∇f−λ∇g=0\nabla f-\lambda\nabla g=\mathbf{0}, the touching condition. The derivative with respect to λ\lambda is −(g−c)=0-(g-c)=0, the constraint itself. With nn variables that is n+1n+1 equations for the n+1n+1 unknowns x1,…,xn,λx_1,\dots,x_n,\lambda.

Sign convention. This lesson subtracts, f−λ(g−c)f-\lambda(g-c). Many books add, f+λ(g−c)f+\lambda(g-c). Then their λ\lambda is the negative of ours, and the points x\mathbf{x} are the same. Check which convention a source uses before comparing multipliers.

The recipe:

  1. Write ∇f=λ∇g\nabla f=\lambda\nabla g and g=cg=c.
  2. Solve for x\mathbf{x} and λ\lambda. There may be several solutions.
  3. Compute ff at every solution and compare. The Lagrange conditions only list candidates.

Example A: a line. Minimize x2+y2x^2+y^2 subject to x+y=2x+y=2. Here ∇f=(2x,2y)\nabla f=(2x,2y) and ∇g=(1,1)\nabla g=(1,1). The conditions are 2x=λ2x=\lambda, 2y=λ2y=\lambda and x+y=2x+y=2. The first two give x=y=λ/2x=y=\lambda/2, and the third gives λ=2\lambda=2. So the point is (1,1)(1,1), with f=2f=2 and λ=2\lambda=2: the same answer as substitution.

Example B: a circle with two candidates. Optimize f=x+2yf=x+2y on the circle x2+y2=5x^2+y^2=5. Here ∇f=(1,2)\nabla f=(1,2) and ∇g=(2x,2y)\nabla g=(2x,2y). So 1=2λx1=2\lambda x and 2=2λy2=2\lambda y, which gives x=12λx=\frac{1}{2\lambda} and y=1λy=\frac1\lambda. The circle equation becomes 14λ2+1λ2=54λ2=5\frac{1}{4\lambda^2}+\frac1{\lambda^2}=\frac{5}{4\lambda^2}=5, so λ2=14\lambda^2=\frac14 and λ=±12\lambda=\pm\frac12.

  • λ=12\lambda=\frac12: the point (1,2)(1,2), with f=5f=5.
  • λ=−12\lambda=-\frac12: the point (−1,−2)(-1,-2), with f=−5f=-5.

Comparing values, (1,2)(1,2) is the maximum and (−1,−2)(-1,-2) the minimum. A circle is closed and bounded, so ff certainly has a largest and a smallest value on it, and these two candidates are the only places they can be. In the first case the gradients point the same way (λ>0\lambda>0), in the second opposite ways (λ<0\lambda<0).

The widget: contours touching a constraint

Pick a function ff and a constraint. Slide the blue point along the constraint (drag it, use the slider, or use the arrow keys when the point is focused). The orange arrow is ∇f\nabla f and the pink arrow is ∇g\nabla g. The small chart shows ff along the curve. When the arrows line up, the slope along the curve is zero, the contour touches the curve, and the widget reports λ\lambda. The c slider moves the constraint, and the readout below the chart shows how the best value responds. The g≤cg\le c button turns the constraint into a region (used in the inequality section below).

Slide the point along the constraint

f = x² + y², ∇f = (2x, 2y). Constraint: g(x, y) = x + y = c, with ∇g = (1, 1).

0−202xy∇g∇f
−20241020f along the linedistance along the line
point = (−0.06, 2.06)
f = 4.25
∇f = (−0.121, 4.121)
∇g = (1, 1)
angle between ∇f and ∇g: 46.7°
slope of f along the line: −3
λ (∇f = λ∇g): — (the arrows are not parallel)

The contour of f crosses the line here, so the slope of f along it (−3) is not zero: moving one way lowers f and the other way raises it. Slide toward where ∇f and ∇g line up.

The best value as c changes
Best minimum of f on the line: V(c) = 2 at (1, 1).
V(c + 0.05) − V(c − 0.05), divided by 0.1, is 2; the multiplier at the best point is λ = 2.

Thin grey lines are contour lines of f (f = 1, 3, 5, …); the thick dark one passes through your point. The pink curve is the constraint; the dashed segment is its tangent at your point. Arrows show direction only (their lengths are not to scale). Green diamonds are the best Lagrange points; hollow diamonds are the other Lagrange points.

Contour map of f (grey lines, the thick dark one through the blue point) with a constraint curve in pink. The orange arrow is the gradient of f and the pink arrow is the gradient of g, both drawn as directions only. Green diamonds mark the best Lagrange points and hollow diamonds the others. Below the map, a chart of f along the curve with the current position marked. Pick f and the constraint, slide the point, change c, switch the goal between minimum and maximum, or switch to g ≤ c to shade a region.

Things to try (each checked against the widget’s own code):

  • Bowl, line, c=2c=2 (the defaults). Slide the point and watch the angle between the arrows. Press Jump to it: the point is (1,1)(1,1), f=2f=2, the angle is 0∘0^\circ, the slope along the line is 00 and λ=2\lambda=2, as in Example A.
  • Slope, circle, c=5c=5. This is Example B. With the goal set to maximum the best point is (1,2)(1,2) with λ=0.5\lambda=0.5, and for minimum it is (−1,−2)(-1,-2) with λ=−0.5\lambda=-0.5. At the minimum the arrows point opposite ways (angle 180∘180^\circ).
  • Tilted bowl, circle, c=1c=1. The best value is 33 for the maximum and 11 for the minimum. These are the eigenvalues of the matrix (2112)\begin{pmatrix}2&1\\1&2\end{pmatrix} (more below). The circle has four Lagrange points: two tied maxima and two tied minima.
  • Bowl, circle. Here f=x2+y2f=x^2+y^2 is the same everywhere on the circle. The widget says so: every point is a Lagrange point, and a tie.
  • Saddle xyxy, line, c=4c=4. The maximum is 44 at (2,2)(2,2). Switch the goal to minimum and the widget reports that there is no minimum: ff falls without bound along the line.
  • The price of cc. In the first example the widget shows the difference quotient of the best value next to λ\lambda. At c=2c=2 both are 22. For the saddle xyxy on the line at c=4c=4, with the goal set to maximum, both are 22.

What the multiplier means: a price

The multiplier is not only a technical helper. Let V(c)V(c) be the best value of ff when the constraint is g=cg=c. Then

dVdc=λ.\frac{dV}{dc}=\lambda .

The multiplier is the rate at which the best value changes when the constraint level moves. Economists call it a shadow price: the price of relaxing the rule by one unit.

Check with Example A. Minimizing x2+y2x^2+y^2 on x+y=cx+y=c gives x=y=c/2x=y=c/2, so V(c)=c2/2V(c)=c^2/2 and V′(c)=cV'(c)=c. At c=2c=2 this is 2=λ2=\lambda. Moving from c=2c=2 to c=2.1c=2.1 raises the best value from 22 to 2.2052.205, about 0.20.2, which is λ×0.1\lambda\times0.1 (the exact change is 0.2050.205 because V′V' itself grows). In Example B, V(c)=5cV(c)=\sqrt5\sqrt c, so V′(5)=525=0.5V'(5)=\frac{\sqrt5}{2\sqrt5}=0.5, the multiplier of the maximum. A third check: maximizing xyxy on x+y=cx+y=c gives x=y=c/2x=y=c/2 and V=c2/4V=c^2/4. At c=10c=10 the point is (5,5)(5,5), V=25V=25, λ=5\lambda=5 and V′(10)=5V'(10)=5. Running the code below confirms these numbers by finite differences.

The size of λ\lambda depends on how the constraint is written. The constraint 2x+2y=42x+2y=4 describes the same line as x+y=2x+y=2, but its gradient is twice as long, so λ=1\lambda=1 instead of 22. The level has doubled to 44, so one unit of the new cc is a smaller change, and the best value rises by 11 per unit instead of 22. The multiplier is a price per unit of gg.

Go deeper Why the derivative of the best value is the multiplier

At the best point x∗(c)\mathbf{x}^*(c) the constraint holds, g(x∗)=cg(\mathbf{x}^*)=c, so the Lagrangian equals the objective there: V(c)=f(x∗(c))=L(x∗(c),λ∗(c),c)V(c)=f(\mathbf{x}^*(c))=\mathcal{L}(\mathbf{x}^*(c),\lambda^*(c),c). Differentiate with respect to cc with the chain rule (P1.C3 and P1.C4). The terms through x∗\mathbf{x}^* vanish because ∇xL=0\nabla_{\mathbf{x}}\mathcal{L}=\mathbf{0}, and the terms through λ∗\lambda^* vanish because g−c=0g-c=0. Only the explicit cc in −λ(g−c)-\lambda(g-c) is left, and its derivative is +λ+\lambda. So V′(c)=λV'(c)=\lambda. This needs VV to be differentiable, which holds under the usual smoothness conditions but not at every value of cc (in the inequality example below, V′V' changes its formula at c=0c=0 and the curvature of VV jumps there).

The same argument also shows why ∇f=λ∇g\nabla f=\lambda\nabla g is the right condition in more than two variables: the feasible directions are exactly those d\mathbf{d} with ∇g⋅d=0\nabla g\cdot\mathbf{d}=0, and ∇f⋅d=0\nabla f\cdot\mathbf{d}=0 for all of them means ∇f\nabla f lies in the line spanned by ∇g\nabla g.

More than one constraint

With several equality constraints g1=c1,…,gm=cmg_1=c_1,\dots,g_m=c_m the point must lie on all the surfaces at once. The touching condition says ∇f\nabla f is perpendicular to every direction that stays on all of them, so ∇f\nabla f is a combination of the constraint gradients, one multiplier each:

∇f=λ1∇g1+⋯+λm∇gm,gi=ci.\begin{aligned} \nabla f&=\lambda_1\nabla g_1+\dots+\lambda_m\nabla g_m,\\ g_i&=c_i . \end{aligned}

This is the gradient of L=f−∑iλi(gi−ci)\mathcal{L}=f-\sum_i\lambda_i(g_i-c_i) set to zero. Example: minimize x2+y2+z2x^2+y^2+z^2 subject to x+y+z=3x+y+z=3 and x−y=2x-y=2. The conditions are 2x=λ1+λ22x=\lambda_1+\lambda_2, 2y=λ1−λ22y=\lambda_1-\lambda_2 and 2z=λ12z=\lambda_1. Substituting into the constraints gives λ1=2\lambda_1=2 and λ2=2\lambda_2=2, so the point is (2,0,1)(2,0,1) with f=5f=5. Each multiplier is the price of its own constraint. The method needs the constraint gradients to be linearly independent (P1.B7) at the solution.

Candidates, not answers: three pitfalls

The solutions may be a maximum, a minimum, or neither. The recipe finds points where the slope along the constraint is zero. Example B returned both a maximum and a minimum. A third kind is possible: minimize yy subject to y=x3y=x^3. The conditions give λ=1\lambda=1 and x=0x=0, the point (0,0)(0,0). But along the curve f=x3f=x^3, which is negative for x<0x<0 and positive for x>0x>0: the point is neither a minimum nor a maximum, and the problem has no minimum at all. Compare values, think about the shape of the feasible set (a closed and bounded feasible set always contains both a minimum and a maximum of a continuous ff), or use the second-order test in the Go-deeper box below.

∇g=0\nabla g=\mathbf{0} breaks the method. Minimize xx subject to y2=x3y^2=x^3. This curve has x≥0x\ge0 and a sharp tip at the origin, so the minimum is (0,0)(0,0) with f=0f=0. But here g=y2−x3g=y^2-x^3 has ∇g=(−3x2,2y)\nabla g=(-3x^2,2y), which is (0,0)(0,0) at the origin, and ∇f=(1,0)\nabla f=(1,0) is not a multiple of the zero vector. The Lagrange system has no solution, although the minimum exists. The requirement ∇g≠0\nabla g\ne\mathbf{0} is a constraint qualification: a regularity condition that the method needs. In practice you check the constraint gradient at the candidates, and treat points where it vanishes separately.

Existence is not guaranteed. On a line the best value may not exist (the widget’s saddle xyxy has no minimum on a line), and a solution of the equations is not a proof that an optimum exists. A closed, bounded feasible set together with a continuous ff settles it; for an unbounded feasible set an extra argument is needed (for example, ff grows without bound far away).

Go deeper A second-order check of a candidate

Let HL\mathbf{H}_{\mathcal{L}} be the matrix of second derivatives of L\mathcal{L} with respect to x\mathbf{x} at a candidate (P1.C8). Look only at directions d\mathbf{d} tangent to the constraint, ∇g⋅d=0\nabla g\cdot\mathbf{d}=0. If d⊤HLd>0\mathbf{d}^\top\mathbf{H}_{\mathcal{L}}\mathbf{d}>0 for all those directions, the candidate is a local minimum of ff on the constraint. If it is negative for all of them, it is a local maximum. If the signs are mixed, the candidate is neither a local minimum nor a local maximum. If the value is zero (or the matrix is only semi-definite) the test says nothing. With one constraint in two dimensions there is a single tangent direction, so the test is one number.

Example: maximize xyxy on x+y=10x+y=10. At (5,5)(5,5), λ=5\lambda=5 and HL=(0110)\mathbf{H}_{\mathcal{L}}=\begin{pmatrix}0&1\\1&0\end{pmatrix} (the constraint is linear and adds nothing). The tangent direction is d=(1,−1)\mathbf{d}=(1,-1), and d⊤HLd=−2<0\mathbf{d}^\top\mathbf{H}_{\mathcal{L}}\mathbf{d}=-2<0: a local maximum, as the formula f=25−s2f=25-s^2 along the line shows. For y=x3y=x^3 the Hessian restricted to the tangent is 00 at the origin, so the test is silent, which is consistent with a point that is neither.

Inequality constraints and the KKT conditions

Now the region constraint g(x)≤cg(\mathbf{x})\le c, and we minimize ff. There are two cases.

  • Inactive. The unconstrained minimum of ff is already inside the region. Then the wall is irrelevant: the answer is that minimum, and nothing pushes against the wall.
  • Active. The unconstrained minimum is outside. For a convex ff (as in these examples) the best point is then on the wall g=cg=c, and near it the problem looks like the equality problem, with one new fact: the sign matters.

One variable shows both. Minimize (x−3)2(x-3)^2 subject to x≤5x\le5: the unconstrained minimum x=3x=3 is allowed, so the constraint is inactive. Minimize it subject to x≤1x\le1: the unconstrained minimum x=3x=3 is not allowed, so the answer is on the wall, x=1x=1, with f=4f=4. There f′(1)=2(1−3)=−4f'(1)=2(1-3)=-4: downhill (the direction of −f′-f') points to larger xx, out of the allowed region, and the wall holds the point back.

That is the general picture. At an active minimum, −∇f-\nabla f (downhill) points out of the region, in the same direction as ∇g\nabla g (which points toward larger gg, outward). So

∇f=−μ ∇gwithμ≥0.\nabla f=-\mu\,\nabla g\quad\text{with}\quad \mu\ge0 .

The wall can push inward but cannot pull. If μ\mu came out negative, −∇f-\nabla f would point into the region, and moving inward would lower ff: the point would not be a minimum. This sign rule is the new content. We write μ\mu for the inequality multiplier, with L=f+μ(g−c)\mathcal{L}=f+\mu(g-c); it equals −λ-\lambda of the equality convention above, and for equality constraints either sign is allowed.

The KKT conditions (Karush–Kuhn–Tucker; Karush derived them in an unpublished 1939 master’s thesis, and Kuhn and Tucker published them in 1951) for minimizing ff subject to g≤cg\le c:

  1. Stationarity: ∇f+μ∇g=0\nabla f+\mu\nabla g=\mathbf{0}.
  2. Primal feasibility: g≤cg\le c.
  3. Dual feasibility: μ≥0\mu\ge0.
  4. Complementary slackness: μ (g−c)=0\mu\,(g-c)=0. Either the constraint is active (g=cg=c) or its multiplier is zero. An inactive constraint costs nothing.

With several inequality constraints, each gets its own μi≥0\mu_i\ge0 and its own slackness condition. Equality constraints may be added with free-sign multipliers.

Example (the bowl again): minimize x2+y2x^2+y^2 subject to x+y≤cx+y\le c.

  • c=2c=2: the bottom (0,0)(0,0) has 0≤20\le2, so it is feasible. The constraint is inactive, μ=0\mu=0, the best value is 00.
  • c=−2c=-2: the bottom is not feasible. The best point is on the wall, (−1,−1)(-1,-1), with f=2f=2. There ∇f=(−2,−2)=−2⋅(1,1)\nabla f=(-2,-2)=-2\cdot(1,1), so μ=2≥0\mu=2\ge0.

The best value is V(c)=0V(c)=0 for c≥0c\ge0 and c2/2c^2/2 for c<0c<0: it follows the wall only once the wall starts to matter. At c=−2c=-2 the rate is V′(−2)=−2=−μV'(-2)=-2=-\mu (relaxing the constraint, raising cc, lowers the best value). In the widget, switch to g≤cg\le c with the bowl and the line, and slide cc across 00. Try the off-centre bowl, f=(x−2)2+(y−1)2f=(x-2)^2+(y-1)^2, with the circle x2+y2≤cx^2+y^2\le c: its unconstrained minimum (2,1)(2,1) has x2+y2=5x^2+y^2=5, so the constraint is inactive for c≥5c\ge5. At c=2c=2 it is active: the best point is on the circle, at (1.265,0.632)(1.265,0.632), with f=0.675f=0.675 and μ=0.581\mu=0.581. The slide c below 55 shows the switch.

When are the KKT conditions enough? They are necessary at a local minimum under a constraint qualification (for example, the gradients of the active constraints are linearly independent, or all constraints are linear). They are sufficient when the problem is convex, which is the next section. Without a qualification or without convexity they can miss the minimum or accept a point that is not one.

Go deeper Complementary slackness in words

Condition 4 says the product μ(g−c)\mu(g-c) is zero. Two numbers multiply to zero only if one of them is zero. If the constraint is slack (g<cg<c) there is nothing to push against, so μ=0\mu=0. If μ>0\mu>0 the constraint must be tight (g=cg=c). Both can be zero together, which happens when the unconstrained minimum lies exactly on the wall (the off-centre bowl at c=5c=5). Nonzero multipliers therefore mark exactly the constraints that matter, and this is why, in a support vector machine, only the points on the margin carry weight (see the box on SVMs below).

Convex problems: local is global again

P1.F2 showed that a convex function has no bad local minima. Constraints keep that property if the feasible set is convex too (a set where the segment between any two members stays in the set). A problem is convex when ff is convex, every inequality constraint gi≤cig_i\le c_i has a convex gig_i (balls, ellipse interiors and half-planes qualify), and every equality constraint is linear. Then a local minimum is a global one, and the KKT conditions are sufficient.

The caution is that an equality constraint with a curved boundary breaks convexity. The circle x2+y2=1x^2+y^2=1 is not a convex set: the segment between two points of the circle passes through the inside. A convex ff can then have local minima that are not global. Take f=x2+0.2yf=x^2+0.2y (convex) on the unit circle. The points (0,1)(0,1) and (0,−1)(0,-1) are both local minima, with f=0.2f=0.2 and f=−0.2f=-0.2: only the second is global. Replace the circle by the disc x2+y2≤1x^2+y^2\le1, which is convex, and the point (0,1)(0,1) is no longer a local minimum (moving a little inward lowers ff), leaving (0,−1)(0,-1) alone.

Three results you will meet again

Probabilities that add to 1. A categorical variable with KK classes has probabilities θ1,…,θK\theta_1,\dots,\theta_K with ∑jθj=1\sum_j\theta_j=1. If class jj occurred njn_j times in NN observations, the log-likelihood is ∑jnjln⁡θj\sum_j n_j\ln\theta_j (P1.D10). Maximize it with the constraint ∑jθj=1\sum_j\theta_j=1. The Lagrange conditions are nj/θj=λn_j/\theta_j=\lambda, so θj=nj/λ\theta_j=n_j/\lambda, and adding up, 1=N/λ1=N/\lambda: λ=N\lambda=N and

θ^j=njN.\hat\theta_j=\frac{n_j}{N}.

For the ten die rolls of P1.D10, with counts (1,1,2,1,2,3)(1,1,2,1,2,3), this gives (0.1,0.1,0.2,0.1,0.2,0.3)(0.1,0.1,0.2,0.1,0.2,0.3) with log-likelihood −16.96-16.96, better than the −17.92-17.92 of the fair die, and λ=10=N\lambda=10=N. The multiplier has the price meaning too: if the probabilities were allowed to add to cc instead, the best log-likelihood would be −16.96+Nln⁡c-16.96+N\ln c, whose slope at c=1c=1 is NN. We ignored the rules θj≥0\theta_j\ge0: they are inequality constraints, but they stay inactive here, because ln⁡θj→−∞\ln\theta_j\to-\infty as θj→0\theta_j\to0 and every count in this example is positive. A zero count gives θ^j=0\hat\theta_j=0, an active constraint, and nj/Nn_j/N is still the answer. A similar calculation for the entropy −∑pjln⁡pj-\sum p_j\ln p_j (P1.E2) with only ∑pj=1\sum p_j=1 gives −ln⁡pj−1=λ-\ln p_j-1=\lambda for every jj, so all pjp_j are equal: the uniform distribution is the most uncertain, as P1.E2 showed.

A direction of fixed length: the top eigenvector. Maximize the variance-like quantity x⊤Σx\mathbf{x}^\top\boldsymbol\Sigma\mathbf{x} over unit vectors, x⊤x=1\mathbf{x}^\top\mathbf{x}=1 (P1.B12). Without the constraint the value grows without limit as x\mathbf{x} gets longer, so a length rule is needed. The gradient conditions are 2Σx=2λx2\boldsymbol\Sigma\mathbf{x}=2\lambda\mathbf{x}, that is

Σx=λx,\boldsymbol\Sigma\mathbf{x}=\lambda\mathbf{x},

an eigenvector equation, and the value there is x⊤Σx=λx⊤x=λ\mathbf{x}^\top\boldsymbol\Sigma\mathbf{x}=\lambda\mathbf{x}^\top\mathbf{x}=\lambda. So the Lagrange points are the eigenvectors, the value at each is its eigenvalue, and the maximum is the eigenvector of the largest eigenvalue. For Σ=(2112)\boldsymbol\Sigma=\begin{pmatrix}2&1\\1&2\end{pmatrix} the eigenvalues are 33 and 11, with eigenvectors along (1,1)/2(1,1)/\sqrt2 and (1,−1)/2(1,-1)/\sqrt2. This is exactly the widget’s tilted bowl f=2x2+2xy+2y2=x⊤Σxf=2x^2+2xy+2y^2=\mathbf{x}^\top\boldsymbol\Sigma\mathbf{x} on the circle c=1c=1. If Σ\boldsymbol\Sigma is the covariance matrix of a data set, the maximum is the largest variance and the maximizer is the first principal direction of PCA (P3.C3).

A penalty is a constraint in disguise. Ridge regression (P3.A6) minimizes a loss plus α∥w∥2\alpha\lVert\mathbf{w}\rVert^2. A small one-weight example: minimize (w−3)2+αw2(w-3)^2+\alpha w^2. The answer is w=3/(1+α)w=3/(1+\alpha), which is 1.51.5 for α=1\alpha=1. Now ask for the minimum of (w−3)2(w-3)^2 under the constraint w2≤1.52w^2\le1.5^2. The unconstrained minimum w=3w=3 is outside, so the wall is active and the answer is w=1.5w=1.5, the same point, with multiplier μ=(3−1.5)/1.5=1=α\mu=(3-1.5)/1.5=1=\alpha. The penalty strength plays the role of the multiplier. For convex problems every penalty strength α>0\alpha>0 matches a constraint level, and the two views give the same solution for matching values; they are different ways to choose the trade-off, not different models.

Go deeper Maximum entropy with a second rule, and the softmax shape

Add a second rule to the entropy problem: the average value must be fixed, ∑jpjxj=m\sum_j p_jx_j=m. With multipliers λ\lambda and β\beta for the two rules, the conditions are −ln⁡pj−1=λ+βxj-\ln p_j-1=\lambda+\beta x_j (with a sign convention absorbed into β\beta), so pj∝e−βxjp_j\propto\mathrm{e}^{-\beta x_j}: the exponentiate-and-normalize shape of softmax (P3.A8). For values x=(1,2,3)x=(1,2,3) and mean m=2.5m=2.5, the maximum-entropy probabilities are (0.1162,0.2676,0.6162)(0.1162,0.2676,0.6162), with entropy 0.90120.9012 nats against ln⁡3=1.0986\ln3=1.0986 for the uniform distribution (whose mean is 22, so it breaks the rule). The same exponential shape appears as the Boltzmann distribution of statistical physics.

Go deeper Duality and support vector machines: a preview

For min⁡f\min f subject to g=cg=c, the dual function is d(λ)=min⁡xL(x,λ)d(\lambda)=\min_{\mathbf{x}}\mathcal{L}(\mathbf{x},\lambda), the best value of the Lagrangian for a fixed λ\lambda. For any λ\lambda it lies at or below the true best value (weak duality), and for convex problems with a mild extra condition the highest value of dd equals the best value of the original problem (strong duality). For Example A, L=x2+y2−λ(x+y−2)\mathcal{L}=x^2+y^2-\lambda(x+y-2) is lowest at x=y=λ/2x=y=\lambda/2, so d(λ)=2λ−λ2/2d(\lambda)=2\lambda-\lambda^2/2. It is 1.51.5 at λ=1\lambda=1, 22 at λ=2\lambda=2 and 1.51.5 at λ=3\lambda=3: its top is 22, at the multiplier we found, and 22 is the best value of the primal problem.

A hard-margin support vector machine (P3.B6) minimizes 12∥w∥2\tfrac12\lVert\mathbf{w}\rVert^2 subject to one inequality per training point, yi(w⋅xi+b)≥1y_i(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1. In one dimension take x=0x=0 labelled −1-1, x=2x=2 labelled +1+1, and x=5x=5 labelled +1+1. The solution is w=1w=1, b=−1b=-1. The first two constraints hold with equality (2−1=12-1=1 and −(0−1)=1-(0-1)=1) and are active, with multipliers 0.50.5 and 0.50.5. The third point has 5−1=4>15-1=4>1, so its constraint is inactive and by complementary slackness its multiplier is 00. The points with nonzero multipliers, the ones touching the constraints, are the support vectors. The kernel trick (P3.B7) works in the dual problem. Details belong to those lessons.

How constrained problems are solved in practice

Training code rarely solves the Lagrange equations by hand. The common routes:

  • Substitute. Use the constraint to remove a variable, as at the start.
  • Reparameterize. Change variables so the constraint holds automatically. Probabilities can be written p=softmax(z)p=\mathrm{softmax}(\mathbf{z}) with free z\mathbf{z} (P3.A8). A vector of fixed length can be written w=v/∥v∥\mathbf{w}=\mathbf{v}/\lVert\mathbf{v}\rVert; weight normalization (Salimans and Kingma, 2016) is a version of this idea for neural-network layers. Gradient descent on z\mathbf{z} for the counts (2,3,5)(2,3,5) approaches (0.2,0.3,0.5)(0.2,0.3,0.5), the constrained answer, and stays inside the simplex throughout (exact zeros would need z→−∞\mathbf{z}\to-\infty).
  • Penalize. Minimize f+ρ (g−c)2f+\rho\,(g-c)^2 for a large ρ\rho. For Example A the minimizer is x=y=2ρ1+2ρx=y=\frac{2\rho}{1+2\rho}: 0.6670.667 for ρ=1\rho=1, 0.9520.952 for ρ=10\rho=10, 0.9950.995 for ρ=100\rho=100 and 0.99950.9995 for ρ=1000\rho=1000. The constraint is only approximately met (x+y−2=−0.095x+y-2=-0.095 at ρ=10\rho=10), and a huge ρ\rho makes the problem hard for gradient descent (P1.F3). This is the same idea as a regularizer (P3.A6).
  • Project. Take a gradient step, then move back to the nearest feasible point (projected gradient descent). For the unit ball, projecting means dividing the vector by max⁡(1,∥p∥)\max(1,\lVert\mathbf{p}\rVert); there are also fast routines for projecting onto the probability simplex. Minimizing (x−2)2+(y−1)2(x-2)^2+(y-1)^2 inside the unit disc with projected gradient descent reaches (0.894,0.447)=(2,1)/5(0.894,0.447)=(2,1)/\sqrt5, the point of the disc nearest to (2,1)(2,1). Constraining every neuron’s incoming weight vector to a maximum length, a max-norm constraint, is a projection used together with dropout (Srivastava et al., 2014; dropout: P4.17). Clipping the gradient (P4.16) is different: it limits the step, not the weights.
  • Specialized solvers. Augmented Lagrangian, interior-point and sequential quadratic programming methods are the general-purpose tools of numerical optimization libraries.

Intuition

You may only walk along the trail. You stop when no step along the trail lowers the ground: the trail runs level, which means it runs along a contour line of the landscape. The multiplier says how steeply the best value would change if the trail were moved by one unit.

Math

Equality: L(x,λ)=f(x)−λ(g(x)−c)\mathcal{L}(\mathbf{x},\lambda)=f(\mathbf{x})-\lambda(g(\mathbf{x})-c); the conditions are ∇f=λ∇g\nabla f=\lambda\nabla g and g=cg=c; V′(c)=λV'(c)=\lambda.

Several constraints: L=f−∑iλi(gi−ci)\mathcal{L}=f-\sum_i\lambda_i(g_i-c_i); ∇f=∑iλi∇gi\nabla f=\sum_i\lambda_i\nabla g_i with independent gradients.

Inequality (minimize ff subject to g≤cg\le c): L=f+μ(g−c)\mathcal{L}=f+\mu(g-c); ∇f+μ∇g=0\nabla f+\mu\nabla g=\mathbf{0}, g≤cg\le c, μ≥0\mu\ge0, μ(g−c)=0\mu(g-c)=0; necessary under a constraint qualification, sufficient for convex problems.

Special cases: simplex gives θ^j=nj/N\hat\theta_j=n_j/N with λ=N\lambda=N; unit sphere gives Σx=λx\boldsymbol\Sigma\mathbf{x}=\lambda\mathbf{x}; penalty min⁡f+ρ(g−c)2\min f+\rho(g-c)^2 approaches the constrained answer as ρ→∞\rho\to\infty.

Code

import numpy as np

# minimize x^2 + y^2 subject to x + y = c: the Lagrange conditions are a linear system in (x, y, lambda)
def lagrange_line(c):
    M = np.array([[2.0, 0.0, -1.0], [0.0, 2.0, -1.0], [1.0, 1.0, 0.0]])
    return np.linalg.solve(M, [0.0, 0.0, c])      # x, y, lambda

print(lagrange_line(2.0))                          # [1. 1. 2.]

For nonlinear constraints, scipy.optimize.minimize with constraints=[{"type": "eq", ...}, {"type": "ineq", ...}] solves the problem numerically (SciPy’s “ineq” means the function is at least 00).

Try it

The three cells use only NumPy. The first solves the Lagrange conditions for Example A as a linear system, checks the price of cc by finite differences, and finds both candidates of Example B by brute force. The second does the categorical maximum-likelihood problem and the unit-length problem. The third compares the practical methods: penalties, projection and the ridge constraint.

Try it: Lagrange conditions and the price of the constraint

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: probabilities that add to 1, and a unit-length vector

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: penalties, projection and ridge as a constraint

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Check your understanding

  1. At the minimum of ff on a smooth constraint curve g=cg=c, with ∇g≠0\nabla g\neq\mathbf{0}, which statement holds?

  2. What is the maximum of xyxy subject to x+y=6x+y=6?

  3. In minimizing x2+y2x^2+y^2 on x+y=cx+y=c, the best value is c2/2c^2/2. About how much does it rise when cc goes from 22 to 2.12.1?

  4. Minimize ff subject to g≤cg\le c. At the solution the constraint is inactive (strictly g<cg<c). What does complementary slackness say about its multiplier?

  5. Take the convex function f=x2+0.2yf=x^2+0.2y. Which statement about local minima is right?

Exercises

  1. Minimize x2+y2x^2+y^2 subject to x+2y=5x+2y=5. Find the point, λ\lambda and the best value.
    Show answer(2x,2y)=λ(1,2)(2x,2y)=\lambda(1,2) gives x=λ/2x=\lambda/2 and y=λy=\lambda. Then x+2y=λ/2+2λ=5x+2y=\lambda/2+2\lambda=5 gives λ=2\lambda=2, the point is (1,2)(1,2), and the best value is 1+4=51+4=5. As a check, 55 is the squared distance from the origin to the line, 52/(12+22)=55^2/(1^2+2^2)=5.
  2. Maximize xyxy subject to x+y=10x+y=10. What are the point, λ\lambda, and dV/dcdV/dc at c=10c=10?
    Show answery=λy=\lambda, x=λx=\lambda, so x=y=5x=y=5, f=25f=25 and λ=5\lambda=5. For general cc, V(c)=c2/4V(c)=c^2/4, so V′(10)=5=λV'(10)=5=\lambda.
  3. Find the largest and smallest values of x−yx-y on the circle x2+y2=2x^2+y^2=2.
    Show answer(1,−1)=λ(2x,2y)(1,-1)=\lambda(2x,2y) gives x=12λx=\frac1{2\lambda} and y=−12λy=-\frac1{2\lambda}. The circle gives 12λ2=2\frac{1}{2\lambda^2}=2, so λ=±12\lambda=\pm\frac12. For λ=12\lambda=\frac12 the point is (1,−1)(1,-1) and f=2f=2 (maximum); for λ=−12\lambda=-\frac12 the point is (−1,1)(-1,1) and f=−2f=-2 (minimum).
  4. Minimize (x−5)2(x-5)^2 subject to x≤2x\le2, then subject to x≤7x\le7. What are the solutions and the multipliers?
    Show answerFor x≤2x\le2 the unconstrained minimum 55 is not allowed, so the answer is on the wall: x=2x=2, f=9f=9. There f′(2)=−6f'(2)=-6 and g′=1g'=1, so −6+μ=0-6+\mu=0 gives μ=6≥0\mu=6\ge0. For x≤7x\le7 the constraint is inactive: x=5x=5, f=0f=0 and μ=0\mu=0.
  5. A die is rolled 1010 times and shows classes 1,2,31,2,3 with counts (2,3,5)(2,3,5) (a three-sided die). What are the maximum-likelihood probabilities, the multiplier, and the log-likelihood compared with the uniform guess?
    Show answerθ^=(0.2,0.3,0.5)\hat{\boldsymbol\theta}=(0.2,0.3,0.5) and λ=N=10\lambda=N=10. The log-likelihood is 2ln⁡0.2+3ln⁡0.3+5ln⁡0.5=−10.302\ln0.2+3\ln0.3+5\ln0.5=-10.30, against 10ln⁡13=−10.9910\ln\frac13=-10.99 for the uniform guess.
  6. Find the direction of largest variance, and its variance, for Σ=(3113)\boldsymbol\Sigma=\begin{pmatrix}3&1\\1&3\end{pmatrix}.
    Show answerMaximizing x⊤Σx\mathbf{x}^\top\boldsymbol\Sigma\mathbf{x} on unit vectors gives eigenvectors. The eigenvalues are 44 and 22. The maximum is 44 along (1,1)/2(1,1)/\sqrt2, and 22 along (1,−1)/2(1,-1)/\sqrt2 is the minimum.

Next: this lesson closes the optimization module. P3.B6 uses constraints and multipliers in support vector machines, P3.A6 returns to the penalty-versus-constraint view with ridge and lasso, and P4.13 turns to the optimizers used to train networks.

Key takeaways

  • A constrained problem is “minimize f(x) subject to g(x) = c” (equality) or “g(x) ≤ c” (inequality). The feasible set is the set of points that obey the constraint, and the unconstrained minimum may not be in it.
  • At a constrained optimum on a smooth curve the contour of f touches the curve. Walking along the curve the slope of f is zero, so ∇f is perpendicular to the curve, and so is ∇g: the two gradients are parallel, ∇f = λ∇g (when ∇g ≠ 0).
  • The Lagrangian is ℒ(x, λ) = f(x) − λ(g(x) − c). Setting its derivatives to zero gives ∇f = λ∇g and g = c. The solutions are candidates only: compare the values of f (or use second-order tests) to pick the minimum and the maximum.
  • The multiplier λ is the rate of change of the best value as c changes. For minimizing x² + y² on x + y = c it is c, so λ = 2 at c = 2, and the best value rises by about 0.2 when c goes from 2 to 2.1.
  • For minimizing f subject to g ≤ c, the KKT conditions are stationarity ∇f + μ∇g = 0, feasibility g ≤ c, μ ≥ 0 and complementary slackness μ(g − c) = 0. An inactive constraint has μ = 0; an active one pushes back with μ ≥ 0.
  • Maximizing the log-likelihood on the probability simplex gives the observed frequencies (counts divided by N), maximizing xᵀΣx on the unit circle gives the top eigenvector, and a ridge penalty is a length constraint in disguise. In practice constraints are handled by substitution, penalties, projection or a reparameterization.
Found a mistake? Tell us