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 over the parameters . A constraint is a rule the parameters must obey. Two kinds matter.
- An equality constraint pins the point to a curve or surface: .
- An inequality constraint keeps the point inside a region: .
The points that obey every constraint form the feasible set. We write the problem as
The unconstrained minimum may sit outside the feasible set, and then it is not an answer. Take , a bowl with its bottom at where . Add the constraint . The point has , so it is not feasible. Which feasible point has the smallest ?
Method 1: solve the constraint for one variable
When the constraint is simple, use it to remove a variable. From we get , so on the constraint . This is an ordinary one-variable problem (P1.F1): gives , then , and . The best feasible point is .
This works only if you can solve for a variable. On a circle you would get , 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 (P1.C5): lines of equal . 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 be a unit vector along the curve at the current point. The slope of in that direction is . At a minimum or a maximum along the curve this slope is zero:
which says that is perpendicular to the curve.
Now look at the constraint function . Moving along the curve does not change , which is equal to all the way. This is the same argument as in P1.C5: a step along a contour line of changes by about , so 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 and point along the same line. If , that means
The number 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: must be perpendicular to every direction that stays on the constraint surface, which puts it in the line spanned by .
The Lagrangian and the recipe
Packaging the two conditions and into one object gives the Lagrangian
Set all its partial derivatives to zero. The derivative with respect to is , the touching condition. The derivative with respect to is , the constraint itself. With variables that is equations for the unknowns .
Sign convention. This lesson subtracts, . Many books add, . Then their is the negative of ours, and the points are the same. Check which convention a source uses before comparing multipliers.
The recipe:
- Write and .
- Solve for and . There may be several solutions.
- Compute at every solution and compare. The Lagrange conditions only list candidates.
Example A: a line. Minimize subject to . Here and . The conditions are , and . The first two give , and the third gives . So the point is , with and : the same answer as substitution.
Example B: a circle with two candidates. Optimize on the circle . Here and . So and , which gives and . The circle equation becomes , so and .
- : the point , with .
- : the point , with .
Comparing values, is the maximum and the minimum. A circle is closed and bounded, so 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 (), in the second opposite ways ().
The widget: contours touching a constraint
Pick a function 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 and the pink arrow is . The small chart shows along the curve. When the arrows line up, the slope along the curve is zero, the contour touches the curve, and the widget reports . The c slider moves the constraint, and the readout below the chart shows how the best value responds. The button turns the constraint into a region (used in the inequality section below).
Things to try (each checked against the widget’s own code):
- Bowl, line, (the defaults). Slide the point and watch the angle between the arrows. Press Jump to it: the point is , , the angle is , the slope along the line is and , as in Example A.
- Slope, circle, . This is Example B. With the goal set to maximum the best point is with , and for minimum it is with . At the minimum the arrows point opposite ways (angle ).
- Tilted bowl, circle, . The best value is for the maximum and for the minimum. These are the eigenvalues of the matrix (more below). The circle has four Lagrange points: two tied maxima and two tied minima.
- Bowl, circle. Here is the same everywhere on the circle. The widget says so: every point is a Lagrange point, and a tie.
- Saddle , line, . The maximum is at . Switch the goal to minimum and the widget reports that there is no minimum: falls without bound along the line.
- The price of . In the first example the widget shows the difference quotient of the best value next to . At both are . For the saddle on the line at , with the goal set to maximum, both are .
What the multiplier means: a price
The multiplier is not only a technical helper. Let be the best value of when the constraint is . Then
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 on gives , so and . At this is . Moving from to raises the best value from to , about , which is (the exact change is because itself grows). In Example B, , so , the multiplier of the maximum. A third check: maximizing on gives and . At the point is , , and . Running the code below confirms these numbers by finite differences.
The size of depends on how the constraint is written. The constraint describes the same line as , but its gradient is twice as long, so instead of . The level has doubled to , so one unit of the new is a smaller change, and the best value rises by per unit instead of . The multiplier is a price per unit of .
Go deeper Why the derivative of the best value is the multiplier
At the best point the constraint holds, , so the Lagrangian equals the objective there: . Differentiate with respect to with the chain rule (P1.C3 and P1.C4). The terms through vanish because , and the terms through vanish because . Only the explicit in is left, and its derivative is . So . This needs to be differentiable, which holds under the usual smoothness conditions but not at every value of (in the inequality example below, changes its formula at and the curvature of jumps there).
The same argument also shows why is the right condition in more than two variables: the feasible directions are exactly those with , and for all of them means lies in the line spanned by .
More than one constraint
With several equality constraints the point must lie on all the surfaces at once. The touching condition says is perpendicular to every direction that stays on all of them, so is a combination of the constraint gradients, one multiplier each:
This is the gradient of set to zero. Example: minimize subject to and . The conditions are , and . Substituting into the constraints gives and , so the point is with . 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 subject to . The conditions give and , the point . But along the curve , which is negative for and positive for : 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 ), or use the second-order test in the Go-deeper box below.
breaks the method. Minimize subject to . This curve has and a sharp tip at the origin, so the minimum is with . But here has , which is at the origin, and is not a multiple of the zero vector. The Lagrange system has no solution, although the minimum exists. The requirement 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 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 settles it; for an unbounded feasible set an extra argument is needed (for example, grows without bound far away).
Go deeper A second-order check of a candidate
Let be the matrix of second derivatives of with respect to at a candidate (P1.C8). Look only at directions tangent to the constraint, . If for all those directions, the candidate is a local minimum of 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 on . At , and (the constraint is linear and adds nothing). The tangent direction is , and : a local maximum, as the formula along the line shows. For the Hessian restricted to the tangent is 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 , and we minimize . There are two cases.
- Inactive. The unconstrained minimum of 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 (as in these examples) the best point is then on the wall , and near it the problem looks like the equality problem, with one new fact: the sign matters.
One variable shows both. Minimize subject to : the unconstrained minimum is allowed, so the constraint is inactive. Minimize it subject to : the unconstrained minimum is not allowed, so the answer is on the wall, , with . There : downhill (the direction of ) points to larger , out of the allowed region, and the wall holds the point back.
That is the general picture. At an active minimum, (downhill) points out of the region, in the same direction as (which points toward larger , outward). So
The wall can push inward but cannot pull. If came out negative, would point into the region, and moving inward would lower : the point would not be a minimum. This sign rule is the new content. We write for the inequality multiplier, with ; it equals 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 subject to :
- Stationarity: .
- Primal feasibility: .
- Dual feasibility: .
- Complementary slackness: . Either the constraint is active () or its multiplier is zero. An inactive constraint costs nothing.
With several inequality constraints, each gets its own and its own slackness condition. Equality constraints may be added with free-sign multipliers.
Example (the bowl again): minimize subject to .
- : the bottom has , so it is feasible. The constraint is inactive, , the best value is .
- : the bottom is not feasible. The best point is on the wall, , with . There , so .
The best value is for and for : it follows the wall only once the wall starts to matter. At the rate is (relaxing the constraint, raising , lowers the best value). In the widget, switch to with the bowl and the line, and slide across . Try the off-centre bowl, , with the circle : its unconstrained minimum has , so the constraint is inactive for . At it is active: the best point is on the circle, at , with and . The slide c below 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 is zero. Two numbers multiply to zero only if one of them is zero. If the constraint is slack () there is nothing to push against, so . If the constraint must be tight (). Both can be zero together, which happens when the unconstrained minimum lies exactly on the wall (the off-centre bowl at ). 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 is convex, every inequality constraint has a convex (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 is not a convex set: the segment between two points of the circle passes through the inside. A convex can then have local minima that are not global. Take (convex) on the unit circle. The points and are both local minima, with and : only the second is global. Replace the circle by the disc , which is convex, and the point is no longer a local minimum (moving a little inward lowers ), leaving alone.
Three results you will meet again
Probabilities that add to 1. A categorical variable with classes has probabilities with . If class occurred times in observations, the log-likelihood is (P1.D10). Maximize it with the constraint . The Lagrange conditions are , so , and adding up, : and
For the ten die rolls of P1.D10, with counts , this gives with log-likelihood , better than the of the fair die, and . The multiplier has the price meaning too: if the probabilities were allowed to add to instead, the best log-likelihood would be , whose slope at is . We ignored the rules : they are inequality constraints, but they stay inactive here, because as and every count in this example is positive. A zero count gives , an active constraint, and is still the answer. A similar calculation for the entropy (P1.E2) with only gives for every , so all 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 over unit vectors, (P1.B12). Without the constraint the value grows without limit as gets longer, so a length rule is needed. The gradient conditions are , that is
an eigenvector equation, and the value there is . 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 the eigenvalues are and , with eigenvectors along and . This is exactly the widget’s tilted bowl on the circle . If 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 . A small one-weight example: minimize . The answer is , which is for . Now ask for the minimum of under the constraint . The unconstrained minimum is outside, so the wall is active and the answer is , the same point, with multiplier . The penalty strength plays the role of the multiplier. For convex problems every penalty strength 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, . With multipliers and for the two rules, the conditions are (with a sign convention absorbed into ), so : the exponentiate-and-normalize shape of softmax (P3.A8). For values and mean , the maximum-entropy probabilities are , with entropy nats against for the uniform distribution (whose mean is , 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 subject to , the dual function is , the best value of the Lagrangian for a fixed . For any it lies at or below the true best value (weak duality), and for convex problems with a mild extra condition the highest value of equals the best value of the original problem (strong duality). For Example A, is lowest at , so . It is at , at and at : its top is , at the multiplier we found, and is the best value of the primal problem.
A hard-margin support vector machine (P3.B6) minimizes subject to one inequality per training point, . In one dimension take labelled , labelled , and labelled . The solution is , . The first two constraints hold with equality ( and ) and are active, with multipliers and . The third point has , so its constraint is inactive and by complementary slackness its multiplier is . 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 with free (P3.A8). A vector of fixed length can be written ; weight normalization (Salimans and Kingma, 2016) is a version of this idea for neural-network layers. Gradient descent on for the counts approaches , the constrained answer, and stays inside the simplex throughout (exact zeros would need ).
- Penalize. Minimize for a large . For Example A the minimizer is : for , for , for and for . The constraint is only approximately met ( at ), and a huge 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 ; there are also fast routines for projecting onto the probability simplex. Minimizing inside the unit disc with projected gradient descent reaches , the point of the disc nearest to . 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: ; the conditions are and ; .
Several constraints: ; with independent gradients.
Inequality (minimize subject to ): ; , , , ; necessary under a constraint qualification, sufficient for convex problems.
Special cases: simplex gives with ; unit sphere gives ; penalty approaches the constrained answer as .
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 ).
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 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.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
At the minimum of on a smooth constraint curve , with , which statement holds?
Along the curve the slope of is zero, so is perpendicular to the curve, and is perpendicular to the curve as well, so the two gradients lie on the same line. The gradient of is zero only if the unconstrained minimum happens to lie on the curve. A right angle between the two gradients would mean changes along the curve. Nothing makes the values of and equal.
What is the maximum of subject to ?
The conditions , and give and . Along the line , which has its top at . The point breaks the constraint (), the point gives the value which is lower, and is bounded above on this line even though it is unbounded on the whole plane.
In minimizing on , the best value is . About how much does it rise when goes from to ?
The multiplier is the rate of change of the best value with : (the exact change is ). The value is itself, not the change in the best value, and the change in the best value is not the change in unless . The rate here is , not .
Minimize subject to . At the solution the constraint is inactive (strictly ). What does complementary slackness say about its multiplier?
Complementary slackness is . With the second factor is not zero, so must be. A positive multiplier would mean a wall that pushes, which needs a tight constraint. A negative multiplier is not allowed for a minimum with (dual feasibility). The multiplier is a number, not a vector, so it is not equal to a gradient.
Take the convex function . Which statement about local minima is right?
The circle is not a convex set, so convexity of is not enough: with and with are both local minima on it. The disc is convex, so any local minimum is global: only is left, since moving inward from lowers . The claim that there are no local minima on either set is wrong because has no unconstrained minimum at all (the term lets it fall without bound), while a continuous function on a closed, bounded set such as the circle or the disc always has a minimum.
Exercises
- Minimize subject to . Find the point, and the best value.
Show answer
gives and . Then gives , the point is , and the best value is . As a check, is the squared distance from the origin to the line, . - Maximize subject to . What are the point, , and at ?
Show answer
, , so , and . For general , , so . - Find the largest and smallest values of on the circle .
Show answer
gives and . The circle gives , so . For the point is and (maximum); for the point is and (minimum). - Minimize subject to , then subject to . What are the solutions and the multipliers?
Show answer
For the unconstrained minimum is not allowed, so the answer is on the wall: , . There and , so gives . For the constraint is inactive: , and . - A die is rolled times and shows classes with counts (a three-sided die). What are the maximum-likelihood probabilities, the multiplier, and the log-likelihood compared with the uniform guess?
Show answer
and . The log-likelihood is , against for the uniform guess. - Find the direction of largest variance, and its variance, for .
Show answer
Maximizing on unit vectors gives eigenvectors. The eigenvalues are and . The maximum is along , and along 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.