Constrained Optimization and Duality
Constrained Optimization and Duality
What happens when you want to find the lowest point in a valley. But a fence blocks half of it? You cannot just walk downhill anymore. The lowest point might be right up against the fence, or at a corner where two fences meet. This is constrained optimization, and it appears everywhere in machine learning. Regularized regression, support vector machines, portfolio optimization, and even training neural networks with constraints.
Ordinary unconstrained optimization — gradient descent, Newton's method — assumes you can move freely in any direction. The real world rarely works that way. A loan model might need all its coefficients positive. A portfolio cannot invest negative dollars. An SVM must keep every data point on the right side of a margin. These are constraints, and they change the game entirely.
This lecture builds the mathematical machinery for handling constraints. Converting them into penalty terms, trading off between primal and dual formulations. And understanding why sometimes the dual is easier to solve than the primal. The core ideas — Lagrange multipliers, duality, complementary slackness. Form the backbone of modern convex optimization and reappear throughout machine learning.
15.1 Linear and Quadratic Programming
You run a small factory. Making one chair earns \$10, one table earns \$40. But you only have 100 hours of labor and 80 units of wood. How many chairs and tables should you make? That is linear programming — every relationship is a straight line. Now change one thing: making lots of chairs causes worker fatigue, so productivity drops as chair count squared. That is quadratic programming — a curve enters the picture. These two families cover most of constrained optimization.
15.1.1 Symbol Registry — Linear and Quadratic Programming
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Decision variables | scalars | ||
| Objective function | scalar | ||
| Minimization problem | operation | — | |
| Maximization problem | operation | — | |
| "Subject to" — introduces constraints | notation | — |
15.1.2 Linear Programming
Linear programming (LP) is constrained optimization where the objective function is linear AND every constraint is linear. You minimize or maximize a linear expression subject to linear bounds. The feasible region is always a convex polytope — a polygon in 2D, a polyhedron in higher dimensions. And the optimum always lies at a vertex (corner point) of this region.
A simple linear program:
The objective is linear (no powers, no products of variables). Both constraints are linear. The problem asks for values of and that make as small as possible without breaking any rule. The feasible region: from 3 upward, up to (but not including) 8. The minimum occurs at the tightest corner: , as small as possible. With no lower bound on , the minimum is pushed to , making the problem unbounded below. This is why real-world LPs always have bounded domains.
Linear programs are solved with the simplex method (moves vertex to vertex) or interior-point methods (cuts through the middle). You may have seen these in operations research courses.
Scope: Linear programming assumes every relationship is linear. If your true objective has curvature — like risk growing as the square of investment. LP will give you the wrong answer. LP also requires the feasible region to be convex (no dents). Non-convex regions break the simplex method: you can get stuck at a local optimum that is not globally best.
Visual intuition: Plot the constraints on an -plane. Each inequality is a half-plane. Their intersection is the feasible polygon. Overlay the objective as parallel level lines. Slide the line perpendicular to its gradient direction until it just touches the polygon. That touching point is the optimum. For a minimization, you slide in the direction opposite to the gradient .
Worked Example: A tiny production LP
A workshop makes chairs () and tables (). Profit per chair: \$2. Profit per table: \$5. Constraints: at most 40 labor hours, each chair takes 2 hours, each table takes 4 hours. At most 15 units of wood, each chair needs 1 unit, each table needs 1 unit.
The vertices of the feasible region: , , , and the intersection of the two lines.
Find the intersection: From , we get . Substitute into :
Evaluate profit at each vertex:
- :
- :
- :
- :
The maximum profit is at — make only tables. Sense-check: tables are higher profit per unit. And the wood constraint (15 total units) is more binding than labor (40 hours allows up to 10 tables at 4h each).
15.1.3 Quadratic Programming
Quadratic programming (QP) is constrained optimization where either the objective OR at least one constraint is nonlinear. The nonlinearities are quadratic — they involve squares of variables (, ) or products (). No cubes or higher powers. The feasible region can be curved (a circle, an ellipse). And the optimum can lie on the interior or on the boundary.
In mathematical form: the objective is where is a symmetric matrix. If is positive semidefinite, the QP is convex and has a unique global minimum. If has negative eigenvalues, the problem is non-convex and may have local minima.
Analogy — throwing a ball in a room. An unconstrained QP is like throwing a ball in an open field. It lands at the lowest natural point (the vertex of the parabola). A constrained QP is like throwing a ball in a room with curved walls. The ball might hit a wall and stop there. The wall could be flat (linear constraint) or curved (quadratic constraint like a circular pillar).
A single-variable quadratic program:
The objective is nonlinear (quadratic), and the constraint is linear. This counts as QP because something in the problem is nonlinear. A richer two-variable example:
The first constraint is nonlinear (a disk of radius ). The second constraint and the objective are linear. Because a nonlinear part appears somewhere, this is quadratic programming.
Scope: Quadratic programming does not extend to polynomials of degree three or higher. For , , or general nonlinear functions, you use numerical methods like Newton's method. Not constrained optimization with Lagrange multipliers. Constrained optimization with Lagrange multipliers specifically handles linear and quadratic programming. Higher-degree polynomials require entirely different approaches (sequential quadratic programming, interior-point methods for general nonlinear programming).
Assumption: For QP to be convex and tractable, the Hessian matrix must be positive semidefinite. If has negative eigenvalues (indefinite QP), the problem is NP-hard in general and may require branch-and-bound or specialized solvers.
Pitfalls:
- Thinking any nonlinearity makes it QP. It must be quadratic nonlinearity — degree 2, not degree 3 or higher. An term makes it general nonlinear programming, not QP.
- Forgetting to check the sign of the Hessian. A maximization QP with a positive definite is non-convex. The objective grows without bound as variables increase, so you need constraints to keep the solution finite.
- Confusing the constraint shape with the objective shape. A problem can have a linear objective and quadratic constraints — it is still QP. The classification depends on whether ANY part (objective or constraint) is nonlinear.
Linear programming = everything linear; optimum is always at a vertex. Quadratic programming = something is squared; optimum can be on a boundary or in the interior. Both fall under constrained optimization with Lagrange multipliers. Higher-degree polynomials need Newton's method instead.
15.1.4 Why Study Constrained Optimization?
Constrained optimization connects to two critical areas in machine learning:
- L1 and L2 regularization (Lasso and Ridge regression). The L1 constraint region is a diamond; the L2 constraint region is a circle. These shapes explain why L1 produces sparse solutions (coefficients exactly zero). The sharp corners of the diamond touch the axes at points where variables are zero. L2's smooth circle rarely touches an axis, so coefficients are small but rarely exactly zero.
- Support Vector Machines (SVM) — a classification algorithm that relies heavily on constrained optimization. You solve the dual of SVM rather than the primal because. (a) the dual depends on the number of data points, not the feature dimension. And (b) the dual is always convex, making it solvable with guarantees. Understanding primal and dual is the prerequisite for SVM.
Q: Why are we studying constrained optimization now? How does it connect to L1/L2 and SVM?
A: The professor introduced constrained optimization as the bridge to two upcoming topics. L1 (Lasso) and L2 (Ridge) regularization from regression are fundamentally constrained problems. You minimize a loss subject to "the coefficients can't be too large." The shape of that bound (diamond vs. circle) determines the solution's sparsity. SVM, which you will study in detail, uses duality as its core engine. The primal SVM lives in the potentially huge feature space. But the dual depends only on dot products between training points, which the kernel trick computes efficiently.
Q: In the maximization problem subject to , could go to negative infinity? Then would still be positive and large.
A: Correct. The feasible region for is everything from up to 4. The function grows in both directions as increases. Without an additional lower bound like , this problem is unbounded — the maximum is infinity. If you add a lower bound. The region becomes bounded on both sides and the maximum would occur at an endpoint.
Q: Does quadratic programming only go up to power 2? What about or ?
A: Yes, quadratic programming stops at degree 2. For higher-degree optimization, you use numerical methods like Newton's method. Constrained optimization with Lagrange multipliers is not used beyond linear and quadratic programming.
Real-World & Domain Connection. Linear programming powers supply chain logistics. Companies like Amazon and FedEx solve massive LPs daily to route millions of packages through warehouses and delivery trucks. Minimizing cost while respecting capacity constraints. Quadratic programming drives Markowitz portfolio optimization in finance. Where the objective is a quadratic risk term (variance) and constraints are linear budget limits. Together, LP and QP form the computational backbone of operations research. With applications spanning airlines scheduling crews, factories planning production, and power grids balancing load.
15.2 Lagrangian Formulation
15.2.1 The Penalty Parameter Concept
You park your car on a street with a "No Parking" sign. Park legally — nothing happens. Park illegally — and a traffic inspector writes you a ticket. The cost of parking jumps from free to expensive the moment you cross the boundary. The Lagrangian does the same thing mathematically. It turns a "fence" (constraint) into a "fine" (penalty term added to the objective). So you can solve the problem as if no fence existed.
Start with a simple constrained problem:
Without the constraint, the minimum of is 0 at . With , the smallest allowed is 2, so is the constrained minimum. The constraint cuts off part of the domain.
Why not just use gradient descent? When you have many constraints, the feasible region gets sharp corners. These corners are not differentiable — you cannot compute a gradient there. Gradient descent can get stuck at a sharp edge. Think of rolling a ball down a surface with a crease. The ball can stop at the crease even if it is not the bottom. The Lagrangian converts the sharp-cornered constrained problem into a smooth unconstrained one.
The solution: convert the constrained problem into an unconstrained one using the Lagrangian. Add each constraint directly into the objective, multiplied by a penalty parameter.
Step 1 — Standard form. Rewrite every inequality constraint in "less than or equal to zero" form. This is the universal format for all constrained optimization. For :
The expression is now exactly when . When is feasible, the constraint expression is zero or negative. When violates the constraint, the expression becomes positive.
Step 2 — Define the Lagrangian. Add the constraint (in standard form) to the objective. Multiplied by a new variable called the Lagrange multiplier:
The term is the penalty. Here is how it works:
- If (valid): , so the penalty is . Lambda cannot hurt you.
- If (invalid): , so the penalty is . Lambda can hurt you — and it will.
Expanding the Lagrangian:
15.2.2 Symbol Registry
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Decision variable | scalar | ||
| Objective function | scalar | ||
| Lagrange multiplier (penalty) | scalar | ||
| Lagrangian | scalar | ||
| Constraint in standard form | scalar | when feasible |
15.2.3 Worked Case 1 — Invalid
Choose an invalid value: . The constraint requires , so 1 is invalid.
Plug into the Lagrangian:
Now think of this as a two-player game. Player X chose (invalid). Player Lambda wants to maximize the penalty. Lambda can choose any non-negative value. To maximize , Lambda chooses .
The cost blows up to infinity. As soon as you take any invalid value. The opponent sees you crossed the boundary and can charge anything — literally infinity. The optimizer will never pick an invalid .
Sense-check: The Lagrangian successfully turns "don't go there" into "you literally cannot afford to go there." Any violation sends the cost to .
15.2.4 Worked Case 2 — Valid
Choose a valid value: . The constraint requires , so 3 is valid.
Plug in:
Player Lambda wants to maximize subject to . The best Lambda can do is , giving a maximum of 9. Any positive reduces the value.
When is valid, the penalty term vanishes — Lambda is forced to zero. You are left with just the original objective . The penalty was never there.
Sense-check: For a feasible point, the Lagrangian equals the original objective. The constraint does not add cost — it only blocks invalid points.
This is the core mechanism: stay inside the fence, pay nothing. Step outside, pay everything. The Lagrangian embeds constraints into the objective as penalty terms, making the problem unconstrained. Invalid choices become infinitely expensive, so the optimizer never picks them.
15.2.5 Two-Player Game Intuition
Think of the Lagrangian as a game between two players:
- Player X chooses to minimize the cost.
- Player Lambda chooses to maximize the penalty.
They play in sequence. The order matters enormously — and it is the difference between the primal and dual problems.
Analogy 1 — Park and inspector: You roam in a fenced park. Inside the fence, no problem. Step outside and an inspector (Lambda) charges you any fine they want. They want to maximize the fine. You, wanting to minimize your cost, stay inside.
Analogy 2 — Pill maker: You want to minimize your food cost while meeting calorie needs. A pill maker sets a pill price. The pill maker wants to maximize the pill price. But they cannot exceed your minimum food cost — or you would just buy food. The pill maker sees your choices and sets the price accordingly to extract maximum profit without driving you to food.
Analogy 3 — Chef and spicy food (turn order matters): You order three dishes but cannot handle spice. The chef, wanting to maximize spiciness, makes all three dishes as spicy as possible. If instead the chef chooses dishes first and you pick the least spicy, you have the advantage. The player who goes first is at a disadvantage — the opponent can respond optimally.
This is the primal-dual relationship. In the primal problem, X goes first (minimizes) and Lambda responds (maximizes). In the dual problem, the order reverses: Lambda goes first and X responds. The primal gives a value the dual, because whoever goes second has the advantage of seeing the first move.
Visual Intuition: Picture a bowl-shaped surface (the objective). Cut a vertical cylinder through it (the feasible region). The Lagrangian is like wrapping a rubber sheet over the bowl. The sheet is pulled down by the bowl but pushed up by Lambda wherever the constraint boundary is crossed. At the optimum, the sheet touches the bottom of the bowl right at the edge of the cylinder. The pull of the bowl (gradient of ) and the push of the constraint (gradient of the penalty) balance perfectly. That is , the fundamental Lagrange multiplier equation.
Real-World & Domain Connection. The Lagrangian formulation was invented by Joseph-Louis Lagrange in 1788 for mechanical systems. But it found its true home in economics and optimization theory. Today, Lagrangian duality underpins every SVM library (libsvm, sklearn.svm), resource allocation in cloud computing (Google's Borg scheduler). Structural engineering (minimum-weight truss design under stress constraints), and optimal control in robotics (trajectories that respect joint limits).
Pitfalls:
- Getting the sign wrong on the standard form. Always convert to form. If the constraint is , multiply by to get . A sign error flips the penalty — you end up rewarding violations instead of punishing them.
- Thinking must be positive. For inequality constraints, yes — is required. For equality constraints, (or ) can be any real number. Positive or negative — because the constraint is bidirectional.
- Forgetting that the Lagrangian is a function of BOTH and . It is not just the objective with a penalty. It is a new function that you will optimize over both variables, though in a specific order.
15.3 Primal and Dual Problems
15.3.1 Deriving the Dual
You have one problem. You create a second problem from it — swapping who moves first. You solve the second one instead. And you get the same answer. If that sounds like a magic trick, you are not alone. But the algebra backs it up, and this swap is the entire reason SVM is computationally practical.
Take the Lagrangian from the previous section:
The dual function is what you get when X plays optimally against a fixed Lambda. You find the that minimizes the Lagrangian for a given , then plug that back in. The result is a function of alone.
Step 1 — Find the best for a given . Take the partial derivative of with respect to and set to zero. This is the stationarity condition from the KKT framework — at optimality, the gradient with respect to primal variables vanishes.
This gives the optimal as a function of . When Lambda sets a penalty rate, Player X's best response is .
Step 2 — Substitute back to eliminate . Plug into the Lagrangian to get a function of only:
This new function is the dual function.
Step 3 — The dual problem. The primal minimized subject to . The dual maximizes subject to :
The primal minimizes; the dual maximizes. They are mirror problems operating on opposite sides of the same Lagrangian.
Step 4 — Solve the dual. Take the derivative and set to zero:
Plug back into the dual function:
The dual's maximum value is 4. Earlier, the primal's minimum was also 4 (at , ). The primal and dual optimal values are equal: both 4.
Step 5 — Recover the primal solution. From the stationarity condition , plug in to get . This matches the primal optimum. The dual does not just give the objective value — it gives the primal variables back.
Full dual derivation worked out:
Primal: s.t. . Standard form: .
Lagrangian:
Stationarity:
Dual function:
Dual problem:
Solve:
Optimal: , recover .
Sense-check: The primal minimum was also at . Strong duality holds. ✓
15.3.2 Symbol Registry for Duality
| Symbol | Meaning | Type |
|---|---|---|
| Primal optimal value | scalar | |
| Dual optimal value | scalar | |
| Dual function | scalar function of | |
| Partial derivative of Lagrangian w.r.t. | scalar | |
| Stationarity condition — expresses in terms of | equation |
15.3.3 Strong vs Weak Duality
The relationship between primal and dual follows a fundamental inequality:
The dual optimal value never exceeds the primal optimal value. This is always true, for any optimization problem, regardless of convexity. Two cases:
- Strong duality: . The optimal values match. The dual touches the primal at its minimum. Here, both are 4.
- Weak duality: . There is a gap — the duality gap . The dual provides only a lower bound.
Strong duality verification for the problem:
Primal: s.t. → at .
Dual: → at .
Since , strong duality holds. The dual's maximum perfectly equals the primal's minimum.
Weak duality counterexample: If we stopped at (not optimal), the dual value would be . This gap of 1 is the duality gap at a non-optimal . Only at the optimal does the gap close to zero.
Analogy — selling a house: The primal is the true market price. The dual is the highest offer your real estate agent can extract from a specific buyer pool. The agent's best offer (dual) can never exceed the true value (primal). But a good agent (strong duality) gets you exactly the market price.
Picture the primal surface as a bowl. The dual function lives below it. At the strong-duality point, the dual touches the primal at its minimum. Everywhere else there is a gap — the dual sits strictly below. If you choose any other than the strong-duality point, the dual value is always below the primal surface. This gap is the duality gap.
Scope: Strong duality is guaranteed for convex optimization problems with strictly feasible points (Slater's condition). This covers most machine learning problems: SVM, logistic regression, Lasso, Ridge. Non-convex problems — like training a neural network. Do not generally have strong duality, and solving the dual may give a different answer from solving the primal. The professor noted that SVM specifically exhibits strong duality, which is why the dual approach works.
What does strong duality prove? The opponent's best possible penalty, when you stay within the feasible region, equals your minimum cost. The best Lambda can do is meet you at your own minimum. Lambda cannot extract more than the natural cost of the problem.
15.3.4 The Min-Max Inequality
The formal relationship between primal and dual is the min-max inequality:
- Left side (primal): X minimizes first, Lambda maximizes second. This is equivalent to the original constrained problem. Lemma 6.4.1 in the standard references proves that the inner maximization sends the cost to for any infeasible . Guaranteeing only feasible points survive the outer minimization.
- Right side (dual): Lambda maximizes first, X minimizes second. This is the relaxed dual problem.
The inequality says: going first as the minimizer gives a result never smaller than the reverse order. In a two-player game, the player who goes second has an advantage. They see the first player's move and respond optimally.
If X goes first, Lambda sees and punishes any boundary-crossing by driving the penalty up. If Lambda goes first, X sees and picks the best feasible point given the penalty rate, keeping cost lower.
Exam note: The min-max inequality is exam material. Understand why the inequality points the way it does. The second-mover advantage in a sequential game — do not just memorize the symbol. At strong duality, the inequality becomes equality: both sides give the same value.
15.3.5 Visual Intuition with a 2D Constrained Region
Consider this problem:
The objective has its unconstrained minimum at with value 0. But the constraints create a band between the lines and . The point violates . So the constrained optimum is on a boundary.
Visual Intuition: Imagine an elliptical bowl sitting on a table. Its deepest point is at . Now cut two parallel vertical walls through the bowl — at and . The floor between the walls is the feasible band. Since the deepest point is outside the band, the ball rolls until it hits the nearest wall and stops there. The optimum is the point on the boundary closest to . Found by projecting onto the line .
A visualization from the class: change and watch the dual function trace an inverted parabola. As increases from 0, the dual function rises in a parabola. At the optimal , the dual's maximum touches the primal's constrained minimum — this is strong duality. For all other , the dual sits below the primal, and the vertical distance between them is the dual gap.
Real-World & Domain Connection. Duality theory underpins auction design. The Google AdWords auction runs a dual linear program billions of times a day. In mechanism design (Nobel Prize-winning work), the primal is maximizing social welfare and the dual reveals the optimal prices. In machine learning, the dual of SVM lets you replace explicit high-dimensional features with kernel functions. Which is the entire reason SVMs work on non-linear data without exploding compute costs.
15.4 Solving Constrained Optimization Problems
15.4.1 The Lagrange Multiplier Method
You now have the theory: Lagrangian, primal, dual, the game. How do you actually solve a problem? Every single constrained optimization problem — whether LP, QP, or SVM dual — follows the same five steps. Learn this sequence cold. It is the professor's most examinable method.
The 5-Step Lagrange Multiplier Method
For any constrained optimization problem:
- Write constraints in standard form — every inequality constraint as . Multiply by if needed. Equality constraints become .
- Form the Lagrangian — add each constraint multiplied by its multiplier ( for inequalities, for equalities) to the objective.
- Take partial derivatives with respect to each original variable (). Set each to zero, solve for variables in terms of the multipliers. This gives the stationarity conditions.
- Use the constraint equations to find the actual multiplier values. For active inequality constraints, complementary slackness justifies setting them to equality.
- Substitute back to get the optimal variables and optimal objective value. Sense-check the answer.
15.4.2 Symbol Registry for This Section
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Decision variables | scalars | ||
| Lagrange multiplier for constraint | scalar | ||
| Lagrange multiplier for equality constraint | scalar | ||
| Lagrangian | scalar |
15.4.3 Worked Example 1 — Equality Constraint
Problem:
Step 1 — Standard form. The equality constraint is already form: . For equality constraints, the multiplier (written as in the lecture derivation) can be any real number. No sign restriction, because the constraint is bidirectional (you cannot go above OR below the line).
Step 2 — Lagrangian. Add the constraint times its multiplier:
The term penalizes any deviation from . Since is unconstrained in sign, it can penalize in either direction.
Step 3 — Partial derivatives (stationarity conditions).
These express and in terms of the unknown multiplier . We have eliminated the primal variables as unknowns — they are now functions of .
Step 4 — Use the constraint equation. Substitute and into the constraint :
The multiplier tells us how sensitive the optimal value is to the constraint. If we relaxed the constraint to , the optimal objective would increase by approximately .
Step 5 — Optimal values.
The minimum is at .
Sense-check: The unconstrained minimum of is 0 at . With the constraint — the line — we are forced away from the origin. The point lies on the constraint and is the closest point to the origin in the metric defined by the elliptical level sets of the objective.
Visual Intuition: Plot the objective as elliptical contours centered at . Elongated in the direction (since has coefficient 1 vs. ). The constraint is a 45-degree line. The optimum is the unique point on the line where an ellipse is tangent to the line — the point . At this tangency point, the gradient of the objective is parallel to the constraint normal . Indeed , confirming .
15.4.4 Worked Example 2 — Nonlinear Constraint
Problem:
Step 1 — Standard form. .
Step 2 — Lagrangian.
Step 3 — Partial derivatives. Taking derivatives and setting to zero:
Verification: plug into the stationarity conditions: . This confirms the algebra is correct.
Step 4 — Use the constraint. At the optimum, by complementary slackness. If then the constraint must be tight (active): .
Taking the positive root (since for an inequality constraint): .
Step 5 — Optimal values.
The minimum is at .
Sense-check: The objective wants both and to be as large as possible. The constraint puts a circular cap on how large they can be. By symmetry, the point on the circle's boundary maximizes under the circle constraint, and thus minimizes . At , the gradient is parallel to the inward normal of the circle . With , giving via the Lagrange condition .
Visual Intuition: The objective is a plane sloping downward toward the northeast. The feasible region is a disk of radius centered at the origin. The lowest point of the plane within the disk touches the boundary at the northeast-most point . If the constraint were removed, the objective would go to by letting both variables increase without bound. The constraint is what keeps the problem well-defined.
15.4.5 Converting Primal to Dual — Two Constraints
Exam note: This is the most common exam-style problem — given a primal, write its dual. You may not need to solve it; just convert. From the last two to three years of exams, this format dominates.
Problem:
Step 1 — Standard form. Multiply each constraint by :
Step 2 — Lagrangian. Introduce one multiplier per constraint: .
Step 3 — Stationarity conditions.
Step 4 — Substitute to get the dual function. Replace and with and respectively:
Dual problem:
Key facts for the exam:
- The primal had variables ; the dual has (one multiplier per constraint).
- The primal minimized; the dual maximizes.
- The dual does not have explicit constraints other than — they come from the Lagrangian setup automatically.
- If asked to solve. Take partial derivatives of with respect to and , set to zero, find the optimum. , . Then , , and . Strong duality holds: this matches the primal's constrained minimum.
Sense-check: The primal wants to minimize the sum of squares while keeping and . The feasible point closest to is , with squared distance , halved gives 2.5. The dual recovers this exactly — strong duality.
Q: For each constraint, do we find a separate dual function? Or one dual with multiple Lambda parameters? A: One dual function with multiple Lambda parameters. With constraints, the Lagrangian has multipliers: . After substituting back, the dual is a function of all multipliers. Solve for them simultaneously using the constraint equations.
Q: With two constraints like and , how do you set up both? A: Convert both to form. becomes (multiplier ). becomes (multiplier ). The Lagrangian is . Take and , solve for in terms of , then use the two constraint equations to find . At the optimum, complementary slackness makes both inequalities equalities when both constraints are active.
Pitfalls:
- Forgetting the restriction for inequality constraints. If you allow negative , the penalty becomes a reward for violating constraints — the whole mechanism breaks.
- Missing a variable in the partial derivative step. If the Lagrangian has primal variables, you must take partial derivatives. Every variable gets its own stationarity condition.
- Flipping the constraint sign when converting to standard form. becomes , NOT . A sign error propagates through the entire solution.
- Treating the dual as a minimization problem. The dual always maximizes. If you set up a minimization dual, your answer will be completely wrong — the primal minimizes, the dual maximizes.
Real-World & Domain Connection: The five-step Lagrange multiplier method is the engine inside every SVM solver. When libsvm or sklearn's SVC runs, it is executing exactly these steps. Forming the Lagrangian of the SVM primal, substituting stationarity conditions, and solving the resulting dual QP. The same method appears in constrained portfolio optimization (minimize risk subject to target return). Structural engineering (minimize material weight subject to stress limits). And optimal power flow in electrical grids (minimize generation cost subject to voltage and thermal limits).
15.5 Complementary Slackness — Introduction
15.5.1 Symbol Registry — Complementary Slackness
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Lagrange multiplier for constraint | scalar | ||
| Constraint function in standard form | scalar | when feasible | |
| Vector of all decision variables | vector | ||
| Complementary slackness condition | equation | — |
15.5.2 The Core Idea
You are pushing against a wall. The harder the wall pushes back, the harder you are pressing. But step away from the wall, and it stops pushing entirely. Complementary slackness is the mathematical statement of this. At the optimum, either a constraint is actively binding (you are pressed against it. ), or it might as well not exist (you are comfortably inside, so ). They cannot both be nonzero at the same time.
Complementary slackness is a necessary condition for optimality in constrained optimization. At the optimum, for every constraint :
This single equation captures two strong statements:
- If → the constraint must be tight: . You are right on the boundary; the constraint is actively holding you back. The multiplier tells you how much the optimal value would change if you relaxed the constraint.
- If → the multiplier must be zero: . The constraint is inactive; you could remove it and the solution would not change. No penalty is needed because you are safely inside.
They are "complementary" because at most one in each pair can be "slack" (nonzero in its allowed direction). If one is strict, the other must be zero.
Why it is needed. The complementary slackness condition, together with primal feasibility (). Dual feasibility (), and stationarity (), form the four KKT (Karush-Kuhn-Tucker) conditions. For convex problems, the KKT conditions are necessary and sufficient for optimality. Satisfy all four and you have found the global optimum.
15.5.3 Connecting to Earlier Examples
At the strong-duality point, when you are fully inside the feasible region, and the penalty vanishes. This matches the valid- case from Section 15.2. Where satisfied with slack , and the optimal was forced to zero. Complementary slackness was at work: .
When you press against a constraint boundary, and . This is why, when solving problems with inequalities, you replace them with equalities at the optimum. You are applying complementary slackness even before formally learning its name. If a constraint is active, treat it as an equality.
15.5.4 What Comes Next
The full theory of complementary slackness, together with KKT (Karush-Kuhn-Tucker) conditions, gets covered in the next lecture. The KKT conditions are the formal framework that includes four components:
- Stationarity: — the gradient of the Lagrangian vanishes.
- Primal feasibility: — all constraints satisfied.
- Dual feasibility: — all multipliers nonnegative.
- Complementary slackness: — at most one slacks per pair.
Exam note: KKT conditions are NOT on this exam. They are covered in the next lecture, just before SVM. For this exam, understand complementary slackness as a concept — the product of multiplier and constraint is zero. And how it justifies setting inequality constraints to equality at the optimum.
15.5.5 Worked Connection — Nonlinear Constraint Revisited
In the example subject to , the constraint was an inequality .
At the optimum :
- The constraint is tight: , so .
- The multiplier was .
- Complementary slackness holds: . ✓
Interpretation: If we relaxed the constraint to , the optimal value would improve by approximately . The multiplier is the shadow price of the constraint — how much the objective gets better per unit of relaxation.
Visual Intuition: Think of watching the optimum point on the circle's boundary. If you slowly inflate the circle (relax the constraint). The point moves outward along the ray direction, and the objective decreases. The rate of decrease is per unit of radius. If you deflate the circle (tighten the constraint). The optimum moves inward and the objective value increases (gets worse for the minimization). The multiplier is the instantaneous rate of change of the optimal value with respect to the constraint bound.
Real-World & Domain Connection. Complementary slackness appears in economics as the concept of shadow prices. The Lagrange multiplier is the marginal value of relaxing a resource constraint by one unit. In SVM, the complementary slackness condition identifies the support vectors. Data points with are the ones that define the margin. Points with are irrelevant to the decision boundary and could be dropped without changing the classifier. This is why SVMs are sparse — most training points end up with and contribute nothing.
Pitfalls:
- Thinking complementary slackness means BOTH and are zero. It means their product is zero — at most one can be nonzero. They can both be zero (a just-barely-active constraint with zero shadow price), but they cannot both be nonzero.
- Forgetting that is a prerequisite. Complementary slackness pairs with dual feasibility. If you find a negative satisfying , it is not a valid optimum — dual feasibility is violated.
- Not checking ALL constraints. Every constraint gets its own complementary slackness condition. Missing one can lead to an incorrect solution.
15.6 Connection to Support Vector Machines
15.6.1 Symbol Registry — SVM Context
| Symbol | Meaning | Type | Domain |
|---|---|---|---|
| Data point vector | vector | ||
| Dot product (scalar product) | scalar | ||
| Cosine similarity | scalar | ||
| Euclidean norm (length) | scalar | ||
| Probability (in logistic regression context) | scalar |
15.6.2 Why SVM Uses the Dual
Imagine you have data in 2D — a ring of red points encircling blue points. No straight line can separate them. You project into higher dimensions — maybe 10D, 100D, or even infinite-D — where a linear boundary finally works. But now your optimization has 100 variables instead of 2. That is the SVM primal. The dual, by contrast, depends on the number of data points, not the number of dimensions. Three hundred data points in 1000 dimensions? The dual has 300 variables, the primal has 1000. And the dual is always convex. That is why we dualize.
SVM (Support Vector Machine) finds a maximum-margin hyperplane separating two classes. The primal SVM optimizes over the weight vector , where is the feature space dimension. After a kernel-induced feature map, can be enormous — even infinite. The primal has variables, making it expensive or impossible to solve directly.
The dual SVM reformulates the problem using Lagrange multipliers (one per training point). The dual depends on dot products between training points, not on the dimension of the feature space:
subject to and other constraints. This has variables (one per data point), not variables (one per dimension).
Three reasons the dual beats the primal for SVM:
- Dimensionality: The primal has variables (feature dimension). The dual has variables (number of data points). When , the dual is much smaller. With the kernel trick, can be infinite while stays finite — the dual is the only tractable approach.
- Convexity: The primal SVM can be non-convex in the original space, especially with nonlinear feature maps. But the dual is always convex — a quadratic maximization problem with a positive semidefinite kernel matrix. You can always solve a convex problem reliably. At strong duality, the dual's maximum equals the primal's minimum. So maximizing the convex dual is equivalent to minimizing the non-convex primal.
- Kernel compatibility: The dual is expressed entirely in terms of dot products . This is what makes the kernel trick possible. Replacing the dot product with a kernel function that computes the dot product in high-dimensional space without ever going there. The primal form cannot use the kernel trick because it operates on individual weight components , not dot products.
Analogy — sending a package overseas. The primal is like physically carrying the package yourself. You deal with every dimension (every mile of the journey). The dual is like hiring a shipping service. You only interact with the endpoints (sender and receiver), and the service handles the complex routing. The kernel trick is the shipping service that magically delivers through higher-dimensional space without you ever seeing the route.
Visual Intuition: Picture an SVM problem in the primal space. The decision boundary might be a complex curved surface. Each Lagrange multiplier in the dual tells you which data points are support vectors. The ones that define the boundary:
- : the point is correctly classified, far from the margin. It contributes nothing to the boundary. Complementary slackness in action.
- : the point is on or inside the margin. It actively shapes the boundary. These points are literally supporting the decision hyperplane.
The decision function becomes . Only support vectors () matter in the sum.
15.6.3 Dot Products and the Kernel Trick — Preview
In SVM, the dual depends on dot products between data points. For 2D points and :
The dot product measures similarity. It is large when vectors point in the same direction. Zero when perpendicular, and negative when they point in opposite directions.
The kernel trick replaces the dot product with a kernel function:
where is a (possibly infinite-dimensional) feature map. The kernel computes the high-dimensional dot product directly from the original coordinates, never explicitly computing . This is the computational magic: you get the benefit of high-dimensional separation without the cost of high-dimensional computation.
Common kernels:
- Linear: (standard dot product)
- Polynomial: (captures feature interactions)
- RBF/Gaussian: (infinite-dimensional, flexible)
Pitfalls:
- Thinking the dual is always smaller. If you have 10 features and 1 million data points. The primal (10 variables) is smaller than the dual (1 million variables). The dual wins when .
- Confusing strong duality guarantee. For SVM, strong duality holds because the problem satisfies Slater's condition (strictly feasible points exist). The dual solution equals the primal solution. This is not true for all ML problems.
- Assuming all points are support vectors. Most points end up with due to complementary slackness. Sparsity is a key practical advantage — prediction uses only support vectors.
Q: In SVM, are the objectives the ones we want to achieve, and the constraints the separating planes? A: The primal SVM objective is to maximize the margin (equivalently, minimize ) while classifying all points correctly. The constraints ensure every point lies on the correct side of the margin boundary. The dual reformulates everything in terms of Lagrange multipliers . Solving the primal directly is hard because of possible non-convexity and high dimensionality. The dual, being convex and kernel-compatible, is the practical approach.
Q: How does the regularization parameter (not in SVM convention) affect the decision boundary in SVM? A: In the soft-margin SVM primal, the objective is , where are slack variables allowing misclassification. A large heavily penalizes violations → narrow margin, few misclassifications, risk of overfitting. A small tolerates violations → wide margin, more misclassifications, better generalization. In the dual, appears as an upper bound on the Lagrange multipliers: . This box constraint directly limits each point's influence on the boundary. Points with are misclassified or inside the margin. Points with are correctly on the margin (support vectors); points with are correctly classified outside the margin.
Q: Is the dot product the same as cosine distance? How are they related? A: The dot product sums component-wise products: . Cosine similarity normalizes this: . The dot product captures both magnitude and direction; cosine captures only direction (values in ). In SVM, the dual formulation uses dot products because it is the natural quantity that appears when substituting the stationarity conditions. The kernel trick extends dot products to nonlinear feature spaces, enabling SVMs to learn complex boundaries.
Real-World & Domain Connection. SVMs powered the first generation of handwritten digit recognition systems (USPS postal code readers in the 1990s). Face detection in digital cameras, and gene expression classification in bioinformatics. The kernel trick, specifically. Made it possible to classify non-linear patterns (like a circle of one class surrounding another) without explicitly constructing high-dimensional feature spaces. Modern large-scale systems often prefer neural networks. But SVMs remain the gold standard for small-to-medium datasets where interpretability (knowing exactly which points define the boundary) matters. Medical diagnosis, fraud detection, and any domain where you need to explain why a decision was made.
Exam Guidance Summary
Exam note: About 70% chance that a problem from primal-dual duality will appear on the examination. The professor stated this expectation early in the class. This topic is heavily weighted.
The types of problems you should expect:
Type 1 — Convert a Primal to Its Dual Form (Most Common)
Given an objective with one or more constraints:
- Write constraints in standard form.
- Form the Lagrangian with one multiplier per constraint.
- Take partial derivatives with respect to all primal variables.
- Substitute back to express everything in terms of multipliers.
- Write the dual: maximize the resulting function subject to .
This is the most common exam format from the last two to three years. You may not need to solve it — just produce the dual function and state the dual problem. The example from Section 15.4.5 (two-constraint dual) is your template.
Type 2 — Solve a Dual Problem
When the dual has only one variable, take the derivative, find the critical point. Compute the optimal value, and recover the primal variables using the stationarity conditions. If the dual has two variables, they may only ask you to write the form, not solve it.
The full derivation in Section 15.3.1 — from Lagrangian to dual to optimal — is your reference example.
Type 3 — Understand the Min-Max Inequality
Know the inequality:
Understand why it points the way it does — the second-mover advantage in a sequential game. X goes first in the primal, Lambda punishes mistakes, so the primal value is higher (or equal). Lambda goes first in the dual, X responds optimally, so the dual value is lower (or equal). Be ready to explain this in words.
Type 4 — Identify Strong vs Weak Duality
- Equality () means strong duality.
- Strict inequality () means weak duality with a duality gap.
Know the conditions for strong duality: convex objective, convex constraints, and a strictly feasible point exists (Slater's condition). Know that SVM and logistic regression both satisfy strong duality.
Key Notes
- Do not memorize formulas in isolation. Understand the two-player game concept and the five-step method. If you understand why the steps work, you can reconstruct any specific formula.
- The five-step method is your universal template: standard form → Lagrangian → derivatives → constraint equation → substitute back.
- KKT conditions are NOT on this exam. They will be covered in the next lecture, just before SVM. Do not spend time memorizing them now.
- Focus your study on: the Lagrangian method (Section 15.2-15.4), primal-to-dual conversion (Section 15.4.5), and conceptual understanding of duality (Section 15.3).
Study Advice from the Professor:
- Practice each worked example step by step, on paper, without looking at the solution. The five-step method must become automatic.
- Be extremely comfortable writing constraints in standard form — errors most often happen at this first step. A sign error propagates through the entire solution.
- For problems with multiple constraints, introduce a separate for each. One multiplier per inequality constraint.
- When you solve for variables in terms of multipliers (Step 3), double-check each derivative. A missed factor of 2 or a sign error in the derivative makes the whole problem unsolvable.
- If you get stuck on a two-constraint dual. Work through the single-constraint case first to check your understanding, then add the second constraint.
Key Industry Applications
Support Vector Machines (SVM)
The duality framework is the mathematical foundation of SVMs. SVMs are used in:
- Medical diagnosis: Cancer detection from patient features (gene expression, imaging biomarkers), diabetic retinopathy screening, EEG-based seizure detection.
- Text classification: Spam detection, sentiment analysis, document categorization — particularly effective when combined with TF-IDF features.
- Image recognition: Handwritten digit recognition (USPS postal codes), face detection, object categorization from histograms.
- Bioinformatics: Protein fold recognition, gene function prediction, disease subtype classification from microarray data.
Logistic Regression
A baseline linear classifier for binary classification problems:
- Credit scoring: Predicting probability of loan default from applicant features.
- Churn prediction: Identifying customers likely to cancel subscriptions based on usage patterns.
- Medical screening: Estimating disease probability from risk factors and lab values.
- Marketing: Predicting purchase probability from demographic and behavioral data.
SVM handles cases where logistic regression fails — specifically when data is not linearly separable in the original space. If logistic regression gives poor accuracy on non-linear data, SVM with a kernel is the natural next step.
Linear Programming (LP)
Used extensively in operations research and business optimization:
- Supply chain optimization: Minimizing shipping costs across a network of warehouses, factories, and retail locations under capacity constraints.
- Logistics: Routing delivery fleets, scheduling airline crews, planning production lines.
- Resource allocation: Assigning limited resources (budget, personnel, machines) across competing projects to maximize total return.
- Portfolio optimization: Maximizing expected return under linear risk constraints (simpler than the quadratic Markowitz model).
- Telecommunications: Network flow optimization, bandwidth allocation, call routing.
Quadratic Programming (QP)
Appears whenever the objective or constraints have quadratic curvature:
- Portfolio optimization (Markowitz mean-variance): Minimize portfolio variance (a quadratic function of weights) subject to a target return (linear constraint). This is the canonical QP in finance.
- Support Vector Machines: The SVM dual is a convex QP. Every SVM solver (libsvm, sklearn.svm, SVMlight) solves a QP internally.
- Model Predictive Control (MPC). Optimize control inputs over a receding horizon for robots, autonomous vehicles, and industrial processes. The objective penalizes squared tracking errors and squared control effort.
- Signal processing: Constrained least-squares filtering, beamforming, and spectrum estimation.
Gradient Descent / Ascent with Constraints
Constrained optimization explains why unconstrained gradient methods fail on problems with sharp feasible regions:
- The Lagrangian converts constrained problems into unconstrained ones, enabling gradient-based solvers.
- Projected gradient descent handles box constraints (coefficient bounds) and is the workhorse of large-scale constrained ML.
- In deep learning, constraints appear as weight normalization, spectral normalization, and Lipschitz constraints on discriminators (GANs).
L1/L2 Regularization (Lasso/Ridge)
Both are fundamentally constrained optimization problems — minimize a loss function subject to a norm bound on the coefficients:
- L1 (Lasso): creates a diamond-shaped constraint region in coefficient space. The sharp corners (where one or more coordinates equal exactly zero) produce sparse solutions — automatic feature selection. Used in genomics (identifying relevant genes among thousands), compressed sensing, and sparse signal recovery.
- L2 (Ridge): creates a circular constraint region. Smooth boundary means coefficients shrink toward zero but rarely reach exactly zero. All features contribute, but large coefficients are heavily penalized. Used when all features are expected to be relevant, but overfitting is a concern.
- The geometric insight from this lecture: L1's diamond has vertices on the axes where some . The loss function's elliptical contours are more likely to first touch the diamond at a vertex than along a face. That is why L1 gives zeros. The circle has no sharp corners, so the contact point is almost never on an axis.
Newton's Method
The numerical method for optimization beyond quadratic degree. When objective or constraint functions involve , , exponentials, or logarithms, Lagrange multiplier theory no longer applies directly. Newton's method (and its constrained variants like sequential quadratic programming) handles general nonlinear programming by iteratively solving quadratic subproblems. Used in:
- Logistic regression training (iteratively reweighted least squares is a Newton variant).
- Maximum likelihood estimation for complex statistical models.
- Trajectory optimization in robotics and aerospace.
MFML Lecture 15 notes · Constrained Optimization and Duality
Sections Breakdown
LP and QP definitions, feasible regions, and where each optimum lies.
Turning constraints into penalty terms with the Lagrange multiplier.
Deriving the dual, strong vs weak duality, and the min-max inequality.
The five-step Lagrange multiplier method with worked examples.
The condition lambda_i g_i(x)=0 and its role in KKT.
Why SVM uses the dual and the kernel trick.
Expected exam problem types and study advice.
Where constrained optimization is used in industry.
Exam Revision Notes
Below is the distilled, exam-ready core of this lecture. Every entry is built from the full textbook notes above. Use this section for rapid review — but if something doesn't make sense, go back to the full explanation in the main content.
Linear and Quadratic Programming
Must-know: Linear programming has a linear objective and linear constraints; its optimum is always at a vertex. Quadratic programming has at least one quadratic (degree-2) term and can have its optimum on a boundary or in the interior. Higher-degree polynomials are NOT QP.
Top pitfall: Calling any nonlinear problem 'quadratic'. A cubic or higher term means general nonlinear programming, not QP — use Newton's method instead.
Self-check: Why does an L1 (diamond) constraint region tend to give sparse solutions while L2 (circle) does not?
Connects to: Lagrange multipliers, Support Vector Machines, L1/L2 regularization.
Lagrangian Formulation
Must-know: The Lagrangian folds each constraint into the objective as a penalty, multiplied by a multiplier. Feasible points pay nothing; infeasible points become infinitely expensive, so the optimizer never picks them.
Top pitfall: Getting the sign of standard form wrong. Always write constraints as g(x) <= 0. For x >= a, use a - x <= 0; a sign error rewards violations instead of punishing them.
Self-check: For an equality constraint, can lambda be negative? Why or why not?
Connects to: Primal and dual problems, The Lagrange Multiplier Method, Complementary Slackness.
Primal and Dual Problems
Must-know: The dual is built by minimizing the Lagrangian over x for a fixed lambda, then maximizing the resulting dual function g(lambda). The primal minimizes; the dual maximizes the same Lagrangian.
Top pitfall: Forgetting that the dual MAXIMIZES while the primal minimizes. Setting up a minimization dual gives a completely wrong answer.
Self-check: After finding the optimal lambda, how do you recover the original primal variables?
Connects to: Lagrangian Formulation, Strong vs Weak Duality, Min-Max Inequality.
Strong vs Weak Duality
Must-know: Always . Strong duality () holds for convex problems with a strictly feasible point (Slater's condition). Weak duality leaves a duality gap. SVM and logistic regression both enjoy strong duality.
Top pitfall: Assuming strong duality always holds. Non-convex problems such as training a neural network generally do NOT have strong duality.
Self-check: What condition guarantees strong duality, and which ML models satisfy it?
Connects to: Primal and Dual Problems, Min-Max Inequality, Support Vector Machines.
Min-Max Inequality
Must-know: The primal (min over x, then max over lambda) is always at least the dual (max over lambda, then min over x). The gap is the second-mover advantage in the sequential two-player game.
Top pitfall: Memorizing the symbol without understanding direction. At strong duality the inequality becomes an equality; otherwise the primal side is strictly larger.
Self-check: In the two-player game, who has the advantage — the player who moves first or second? Why?
Connects to: Primal and Dual Problems, Strong vs Weak Duality.
The Lagrange Multiplier Method
Must-know: Every constrained problem follows five steps: standard form (<=0), form the Lagrangian, take partial derivatives (stationarity), use the constraint equations, substitute back and sense-check.
Top pitfall: Missing a partial derivative, or flipping a constraint sign in standard form. A sign error or a missed factor of 2 propagates through the whole solution.
Self-check: In a problem with k inequality constraints, how many multipliers does the dual have?
Connects to: Lagrangian Formulation, Complementary Slackness, Primal and Dual Problems.
Complementary Slackness
Must-know: At the optimum, for each constraint either the multiplier is zero (constraint inactive) or the constraint is tight (lambda_i > 0). Their product is always zero. This is one of the four KKT conditions.
Top pitfall: Thinking both lambda and g must be zero. Only their PRODUCT is zero; at most one can be nonzero. Also lambda_i >= 0 is required (dual feasibility).
Self-check: If a constraint is slack (g_i(x) < 0), what must its multiplier be, and why?
Connects to: The Lagrange Multiplier Method, Primal and Dual Problems, Support Vector Machines.
Support Vector Machines and the Kernel Trick
Must-know: SVM solves the dual, not the primal, because the dual depends on the number of data points (not feature dimension), is always convex, and is expressed in dot products — which the kernel trick exploits.
Top pitfall: Thinking the dual is always smaller. It wins only when the number of points m is far less than the feature dimension d; with m >> d the primal is smaller.
Self-check: How does the kernel trick let SVM use an infinite-dimensional feature space without computing it?
Connects to: Primal and Dual Problems, Strong vs Weak Duality, Complementary Slackness.
Was this lecture useful?
BitsNotes AI Assistant
Subject Notes AssistantConfigure AI Chat
Choose how to access the chatbotSigned in as
Powered by BitsNotes — 20 messages per day. No API key needed. Want unlimited access? Use "Bring Your Own Key" mode.
Sign in to use AI Chat
Get 20 free AI messages per day to ask questions about your lecture notes. Sign in with Google or GitHub — it takes 5 seconds.
Sign In to BitsNotesSwitch to "Bring Your Own Key" tab above for unlimited access with any OpenAI-compatible provider.