9 Convex optimization

In this last chapter we will deal exclusively with convex optimization problems.
Recall that a convex optimization problem has the form
written in the compact notation from Definition 4.6 : the constraint lives under and the function to be minimized follows. Here is a convex subset (see Definition 4.21 ) and a convex function (see Definition 4.26 ). We will mainly deal with the case, where is differentiable defined on all of in addition to just being convex defined on . Why single out the convex problems? Because the previous chapters showed how unwieldy optimization is in general. Gradient descent (Section 7.5.1 ) walks downhill to some point where the gradient vanishes, with no way of knowing whether a deeper valley hides behind the next ridge — training the digits network in Section 7.9 was exactly such a leap of faith. Newton's method is fast, but in Example 8.6 it cheerfully delivered a critical point that turned out to be a local maximum, and every critical point it finds costs a Hessian analysis before we know what we are looking at. Worst of all: having found a local minimum of a general function, no computation at that point can rule out that a better one exists somewhere else.
Convexity removes all of these obstacles in one stroke. A differentiable convex function has no saddle points and no local maxima — a critical point can only be a minimum — and a local minimum is automatically a global minimum (Theorem 6.13 ). Better still, as this chapter will show, a proposed solution can be certified optimal by checking finitely many conditions at that single point, without looking anywhere else. This is why convex problems form the largest class of optimization problems that can be solved reliably and at scale, and why applied mathematicians work hard to model their problems as convex ones — the fire station problem below is a first taste of such modeling.
This final chapter asks three questions about such a problem, and its parts answer them in turn. What is it good for? We derive the optimal hyperplane separating labeled data and meet the support vector machine, one of the most celebrated algorithms of machine learning (Sections 9.1 and 9.2 ). How does a machine solve it? Interior point methods built on logarithmic barrier functions (Section 9.3 ). And how do you recognize — and certify — an optimal solution exactly? A geometric criterion and the famous Karush-Kuhn-Tucker conditions (Sections 9.4 and 9.5 ).
Below is an example of a convex optimization problem in the plane .
where is the subset of points in satisfying
Sketch the subset in Example 9.1 . Show that Example 9.1 really is a convex optimization problem and solve it.
Keep Example 9.1 in mind: it returns as a running example when we write down the KKT conditions in Section 9.5 .
Below is an example of a convex optimization problem modelling the real life problem of placing a fire station (center of circle) so that the maximal distance to the surrounding houses (points to be enclosed) is minimal.
Given points , what is the center and radius of the smallest circle containing these points?
We can write this optimization problem as
where
Upon rewriting this turns into the optimization problem
where
and .
Prove that (9.1) and (9.2) both are convex optimization problems. Explain how (9.1) is rewritten into (9.2) .
Hint
Expand
and put .
The rewriting (9.2) may look unmotivated now, but it earns its keep in Section 9.3 , where an interior point method computes the optimal fire station location.

9.1 The optimal separating hyperplane

In section 5.3.2 we were presented with labeled data
where and . The task at hand was to separate differently labeled data by a hyperplane , such that
for . Please browse back to Definition 4.40 for the definition of a hyperplane in .
Such a hyperplane need not exist: for the points with label and with label , the four inequalities in (9.4) contradict each other, as you showed in Exercise 5.9 . Separability is a genuine assumption on the data — we return to what can be done without it with the kernel functions of Section 9.2 .
If the data in (9.3) can be separated according to (9.4) , we may find a hyperplane , such that
How do you go from (9.4) to (9.5) ?
Suppose that
Let
Show that and . How can and be applied in constructing and ?
Consider
What is special about ?
What does optimal hyperplane mean in this setting? It is the one maximizing the width of the strip between the two labeled clusters.
Figure from the Cortes and Vapnik paper: Support vector networks, Machine Learning, 1995.
The inequalities (9.5) describe this strip precisely. The two parallel hyperplanes
bound a strip containing no data points: by (9.5) the points labeled lie on or beyond and the points labeled on or beyond . The separating hyperplane given by runs down the middle of the strip. This is exactly the picture above: is the solid line, and the dashed ones.
Here lies a crucial insight, only implicit in the paper by Cortes and Vapnik: the normalization to in (9.5) costs nothing — rescale and , as in the exercise above — and it makes the width of the strip visible in alone.
Indeed, the distance from a point to the hyperplane is
by Exercise 9.7 below. A point on satisfies and therefore has distance to , and the same holds on . The strip therefore has width
and the optimal hyperplane is the one making as small as possible subject to (9.5) . Since minimizing is the same as minimizing — and the square is a differentiable (convex!) function — we have arrived at a convex optimization problem.
Let be the hyperplane in given by and let . The point closest to in can be found by solving the optimization problem
Explain why (9.6) is a convex optimization problem.
Show how Theorem 7.39 can be used to solve this optimization problem by first deducing the equations
for the Lagrange multiplier . Notice here that above really contains equations, whereas is only one equation in , where . Solve the equations (9.7) for and . How can we be sure that really is a minimum in (9.6) ?
Finally show that the distance from to is given by the formula
Summing up, we have proved the following result.
Let the points be labeled by . Then the optimal hyperplane separating the points is given by the optimization problem
for .
The vectors among the data points satisfying or are called support vectors.
An optimal solution always has support vectors. If no data point satisfied its constraint with equality, all the numbers would exceed by a common factor , and dividing both and by would preserve the constraints in Theorem 9.8 while shrinking — so the strip was not the widest after all. A little more thought (shift to re-center the strip, then rescale) shows that both dashed lines must carry support vectors, just as in the figure above.
Let us explicitly write up the optimization problem in Theorem 9.8 in a very simple situation: finding the best line separating the points and . In the notation of (9.5) , we have (without the stars on and )
so that
The points are
where and .
Therefore the optimization problem in Theorem 9.8 becomes
Solve the optimization problem (9.8) and verify that the best line from the optimization problem is the one we expect it to be. Also, check how WolframAlpha solves this optimization problem.
Hint
You could maybe use Fourier-Motzkin elimination to show that
implies .
Notice that the optimization problem in Theorem 9.8 has number of constraints equal to the number of points to be separated. Notice also that it has no solution at all when the data cannot be separated — the constraints are then contradictory. The remedy, called the soft margin, is stated precisely when we meet the parameter C of sklearn in the next section.
Usually one does not use the optimization problem in Theorem 9.8 , but rather its socalled (Lagrange) dual for finding the optimal hyperplane. This dual optimization problem uses that the normal vector is a linear combination
of the support vectors weighted by their labels. It is an optimization problem in from (9.9) and looks like
where is the vector of labels attached to the points and is the symmetric matrix given by
Notice that the dual optimization problem is an optimization problem in , where is the number of data points. This can be in stark contrast to the original optimization problem in Theorem 9.8 , which is an optimization problem in , where is the dimension of the data points. Sometimes the data points are high dimensional and it pays to solve the dual optimization problem.
Let us write down the dual optimization problem for the points in Example 9.9 . Here
so that the dual optimization problem becomes
This reduces to the optimization problem of maximizing subject to , which has the solution . Therefore the optimal hyperplane has normal vector
The constraints hold with equality at the two support vectors, so and the optimal hyperplane is the line — the perpendicular bisector between the two points, exactly as geometry demands.
The dual optimization problem (9.10) can be derived formally from the original optimization problem in Theorem 9.8 . This is, however, beyond the scope of this course (see section 2.1 of the Cortes and Vapnik paper).

9.2 Support vector machines

The optimization problem of Theorem 9.8 , its dual (9.10) and the kernel functions introduced below make up one of the most celebrated algorithms of machine learning: the support vector machine (SVM) from the Cortes and Vapnik paper cited above. You do not have to implement it yourself: the python library sklearn ships an industrial implementation in sklearn.svm, and with kernel="linear" and a very large parameter C it solves exactly the optimization problem of Theorem 9.8 . The parameter C is the price of violating the margin, and we can say precisely what that means: for any labeled data — separable or not — sklearn solves the soft margin problem
for , from section 3 of the Cortes and Vapnik paper. The new slack variable measures how far the point falls short of its margin constraint (for the constraint is Theorem 9.8 's, with the two label cases abbreviated into one inequality), and the objective charges per unit of shortfall. A huge C makes slack unaffordable and recovers the hard margin of Theorem 9.8 ; a moderate C buys a wider strip on messy data, at the price of points inside the strip or even on the wrong side — the Gaussian kernel cell later in this section runs with C=10 in exactly this spirit. In the dual, C shows up as the extra constraint : a cap on how much influence any single data point can buy.
Three small observations that explain what sklearn is doing.
  1. Check that for the constraint is exactly the constraint of Theorem 9.8 , for both values of the label .
  2. Show that the soft margin problem is feasible for any labeled data — no separability needed. So unlike the problem in Theorem 9.8 , it always has something to optimize.
  3. Suppose the data can be separated, and let be the optimum of Theorem 9.8 . Show that the slack at the soft margin optimum satisfies
    so the total slack vanishes as grows — the hard margin reappears.
Hint
For the second part: , and satisfy every constraint. For the third: with all is one candidate in the soft margin problem, so the optimum costs at most — and the term is part of that cost.

9.2.1 Two clusters in the plane

The cell below separates two clusters of points. It prints the optimal and , draws the optimal hyperplane (solid) with the two margin lines (dashed), and circles the support vectors. Look closely at the printed numbers: at the support vectors, equals exactly — these are the constraints of Theorem 9.8 holding with equality, computed numerically.

Live Python

Only the circled points matter: move any other point a little (rerun and try!) and the optimal hyperplane does not budge. The hyperplane is carried entirely by its support vectors — hence the name.
Suppose the labeled points can be separated by a hyperplane. Which of the following statements are true?
The optimal separating hyperplane is completely determined by its support vectors.
Any four points in the plane, two labeled and two labeled , can be separated by a line.
The dual optimization problem (9.10) has one variable per data point.
Moving any of the data points a little always changes the optimal hyperplane.

9.2.2 Reading handwritten digits

Support vector machines are not a museum piece. Before the deep learning era they were the state of the art for tasks like text classification and protein classification, and for small data sets with many measurements per data point they remain a favorite — this is exactly the situation of Remark 9.11 , where the dual problem has one variable per data point rather than one per dimension.
Here is an example you already know: the handwritten digits that the neural network of Section 7.9 read in the previous chapter — every digit its vector of pixel values, a data point in . We ask the machine the honest yes/no question of practice: is this digit a ? Label every with and everything else with , and Theorem 9.8 applies unchanged. Note what just happened: the "two clusters" of the theorem are two labels, nothing more. The class is a motley union of nine kinds of digit, and the mathematics does not blink — the two-blob pictures we have drawn are visual aids, not hypotheses. This one-against-the-rest trick is also how binary classifiers handle many classes in practice: train ten machines, one per digit, and let the largest decision value win.
It is far from obvious that a single hyperplane in can separate the fives from the nine-digit crowd — but for these training digits it can, so we demand the hard margin (a huge C) and get exactly the optimal hyperplane of Theorem 9.8 .
The best part is the picture: the support vectors are themselves digits, and they are the machine's entire concept of five-ness. The optimization problem singles out a handful of borderline fives (top row below) together with a gallery of five-impersonators — digits of other classes that flirt with looking like a , shown with their true labels in the middle row. When we ran it, the impersonators were mostly 9s, 7s, 3s and 6s: exactly the digits that share strokes with a five. The bottom row shows some of the ignored, neatly written majority — move any of those and the hyperplane does not budge. The cell prints your exact counts, which may drift slightly with the library version.
Better still, the number measures how manifestly a digit is a . Recall from (9.5) that the optimal hyperplane was normalized to give values on one cluster and on the other, with the margin strip in between. So a digit with is manifestly a five — it clears the margin — while a value near means the machine is honestly unsure. The cell sorts the unseen digits by and displays the extremes and the ambiguous middle. When we ran it, every unseen five landed on the correct side — nearly all manifestly, a couple hesitantly inside the margin — at the price of a couple of false alarms among the non-fives; again the cell prints your exact counts.

Live Python

Study the strip: on the far left (large negative ) unmistakably not fives, on the far right textbook fives, and in the middle handwriting that would make a human hesitate too. Note the family resemblance to the Challenger neuron of the previous chapter: there the same affine expression was fed through the sigmoid to become a probability; here it is left raw and read against the margin.
Compare with the previous chapter, too: there, reading digits took a -parameter neural network and thousands of gradient descent steps. Here the single yes/no question is it a five? is answered by one convex optimization problem carried by a few dozen support vectors, with the guarantee from Theorem 6.13 that the hyperplane found is globally optimal.

9.2.3 Separating sentences

Digits were easy to feed to the machine: an image is born a vector. But most of what the world wants classified is text — support requests, product reviews, spam. Chapter 5 already showed the way in: after the one-hot encoding (5.16) came its modern replacement, the folded cell of words embedded by the small language model all-MiniLM-L6-v2 — the model behind Ask the book on this very page — which turns any sentence into a learned vector in whose geometry carries meaning.
That is one half of the modern recipe for classifying text. The other half is this chapter. Take a big pretrained model, freeze it, embed your sentences, and train nothing but a separating hyperplane on the resulting vectors. Practitioners call this a linear probe, and it is everyday industrial machine learning: under many a spam filter, content moderator and ticket router sits exactly the soft-margin problem of Exercise 9.13 , working on top of somebody else's embeddings.
Let us run the recipe, honestly and end to end. The task: do film reviews express enthusiasm or disappointment? Below are short reviews written for this book — the first enthusiastic, the next disappointed, and a final held back as unseen test sentences. A language model is far too large to run inside a web page, so the reviews were embedded once, in advance, and their vectors travel with this page exactly like the words of Chapter 5: -bit integers, one scaling factor per vector. Open the fold and you are looking at rows of ; run the cell to decode them into the matrix VECS.
Python: 46 film reviews as learned vectors in dimension 384

Live Python

Now the machine of this chapter takes over: a soft-margin hyperplane in , computed from the labeled training reviews. For the digits we could insist on the hard margin; here we deliberately keep sklearn's default soft margin () — you will see why in a moment. The six unseen reviews are then judged by the sign of alone. The machine never sees their labels; read its verdicts and judge it yourself.

Live Python

Read the strip of verdicts as you read the strip of digits: at the bottom, confident disappointment; at the top, confident enthusiasm; in the middle, hesitation. In our run the machine judges five of the six unseen reviews correctly and hesitates exactly where a human must read twice — "Ninety minutes I will never get back" contains not a single negative word. The one it gets wrong, "I want to watch it again tomorrow", is the same phenomenon in a purer form: its warmth is entirely implication, and this small embedding model reads vocabulary more fluently than implication. Look also at the training reviews the soft margin gives up on — "Two hours flew by; I did not look at my phone once" is enthusiasm expressed in the words of boredom. The machine's failures are not random noise; they trace the precise boundary of what its embedding understands. (The embeddings inside today's large chatbot models draw that boundary much further out.)
One number above deserves a hard look: nearly every training review is a support vector — of in our run, against a few dozen of for the digits. This is the signature of high dimension. Forty points in have so much room that a hyperplane can do almost anything — separating them is nearly free, the way a degree- polynomial fits any points of Chapter 2 effortlessly — so the optimal hyperplane ends up leaning on almost all of them, and a perfect fit to the training data proves nothing. That is why the six held-out sentences are the only honest measure in this subsection, and why we kept the soft margin: the two training reviews it refuses to honor are genuinely misleading sentences, and forcing the hyperplane to honor them anyway is possible — but you pay for it on the unseen six (see the exercise below).
An embedding, then, is a learned lift: raw text has no coordinates at all, and the language model supplies of them — so good that a plain hyperplane suffices. Creating coordinates to create separability is precisely the theme of the next subsection, where, instead of borrowing a lift learned from text, we build one by hand from polynomials.
In the training cell, replace the machine by SVC(kernel="linear", C=1e6) — the hard margin of the digits example — and rerun.
  1. Check that the list of sacrificed training reviews is now empty: all training reviews are on their correct sides.
  2. Now read the verdicts on the six unseen reviews. Compare with the soft margin's verdicts. Which figure of Chapter 2 does this pair of observations redraw (see Figure 2.41 )?
The machine misjudged "I want to watch it again tomorrow". Fix it the practitioner's way: move that review into the training data,

Xtr = VECS[:41]
ytr = np.array([1]*20 + [-1]*20 + [1])
Xte = VECS[41:]

and retrain. The repaired review is now judged correctly — but watch the two hesitant negative reviews in our run drift across to the wrong side. Explain how adding a single training point can move the boundary against other points, and why the honest cure is more data rather than one patch per mistake.
Hint
The new point lands inside the old margin on the wrong side, so the optimization must tilt the hyperplane to accommodate it — and a tilt moves the decision value of every sentence, including the ones that were barely correct. A machine patched one complaint at a time plays whack-a-mole; a machine trained on hundreds of reviews pins the hyperplane down from all sides at once.
Why is almost every review a support vector, when only a few dozen of the digits were? Explain in terms of the dimension and the number of data points, using the polynomial analogy above: separating labeled points in leaves a hyperplane enormous freedom, just as threading a degree- polynomial through data points is always possible (Chapter 2). What would you expect to happen to the fraction of support vectors if the training set grew to thousands of reviews?

9.2.4 Separating by non-linear functions

Sometimes no line can separate the data — we promised in Section 9.1 to deal with this. The remedy is not to bend the line. It is to move the points.
If no hyperplane separates the data, map the data into a higher dimensional space, where a hyperplane can do the job.
Here is the idea in dimension one, where a hyperplane is just a point. The numbers with labels cannot be separated by any point on the line. Now lift the numbers to the parabola in the plane using
The lifted points and can be separated — for example by the line , as the cell below shows.
And a separation upstairs is a separation downstairs: the number is classified by the sign of
which is positive at and and negative at . A hyperplane in the plane became a polynomial on the line.

Live Python

The four points from Section 9.1 that no line could separate — labeled and labeled — surrender to the same trick, and here a single extra number suffices: the product
equals on the first pair and on the second. Keep this little product in mind; you will meet it again inside the kernel of Example 9.18 .
For a taste of the geometry, consider the five points
where is to be separated from the four corners. No line can do it, but a circle
certainly can:
Under the map something drastic happens: all four corners land on the same point , while stays put. Separating two points is no challenge — and pulling a separating line back through gives exactly the circle (9.12) . The right map does not just help; it can make the problem trivial.
The general recipe is now clear: find a map
such that the transformed data
becomes linearly separable, and run the machinery of Theorem 9.8 in . When the coordinates of are monomials, the optimal hyperplane upstairs is an intricate polynomial curve downstairs.
The cell below shows the recipe at full power. It scatters random points in the plane, labels them by which side of the snaky cubic curve they fall on, lifts them to using all monomials of degree at most three,
and hands the lifted points to the support vector machine with kernel="linear" — a plain hyperplane in , nothing we have not seen before. Pulled back to the plane, that hyperplane is the black cubic curve in the plot, hugging the gap in the data and separating the two clusters perfectly — carried, as always, by a handful of support vectors.

Live Python

There is a catch. For interesting data the dimension explodes: degree three in two variables already took coordinates, and higher degrees in more variables quickly outgrow any computer.
The dual optimization problem comes to the rescue. In (9.10) the number of variables is the number of data points — not — and the transformed data enter only through the matrix
The dimension appears nowhere, provided we find a clever way of getting our hands on the dot products in (9.13) without ever computing itself. Here an old concept from pure mathematics called kernel functions helps us.

9.2.5 Kernel functions

A kernel function is a function , that is a hidden dot product in the following sense: there exists a function
such that
Let be given by
Then
One gleans from (9.15) that is a kernel function, since (9.14) is satisfied for given by
Once we have a kernel function for we can replace the matrix in (9.13) by
and proceed to solve the optimization problem without worrying about the sometimes insurmountable size of .
The kernel of Example 9.18 is built into sklearn as kernel="poly", degree=2, coef0=1. The cell below turns it loose on the five points from the beginning of this subsection, where had to be separated from the four corners. The support vector machine — solving the dual optimization problem with the kernel in place of the dot product — finds a closed separating curve, and we never leave to compute in .

Live Python

Compare the black curve with the circle (9.12) you would draw by hand — and with the curve you will compute in the kernel perceptron exercise below.

9.2.6 The Gaussian kernel and infinite dimension

The most famous kernel of all is the Gaussian kernel
known to sklearn as kernel="rbf" (for radial basis function). Which map hides behind this one? Let us look in dimension one, where the answer is both elementary and dizzying. Using the series of the exponential function on the last factor in , we get
This says precisely that for
— one coordinate for every power of .
The feature space behind the Gaussian kernel is infinite dimensional. No computer could store a single vector , let alone find a separating hyperplane among such vectors. And none has to: the dual problem only ever asks for the numbers — one exponential each. The support vector machine quietly optimizes over an infinite dimensional space while your laptop multiplies small matrices. A similar expansion works in for every .
There is also a completely down-to-earth way of viewing the resulting classifier. As in (9.9) , the optimal normal vector is a linear combination of the transformed support vectors, so a new point is classified by the sign of
for suitable numbers , non-zero only at the support vectors: a landscape of Gaussian hills (where ) and valleys (where ), with the separating curve at sea level. With enough hills and valleys any coastline can be traced, which is why the Gaussian kernel separates essentially any labeled data set.
The cell below turns it loose on data that would humiliate any polynomial of modest degree: two interlocking spirals. The background coloring is exactly the landscape , and the black curve is sea level.

Live Python

Zero training errors on the two spirals, and the landscape in the picture is built from one Gaussian hill or valley per support vector — the cell prints how many there are (a substantial share of the points; wiggly boundaries are expensive). Everything computed in , everything happening in .

9.2.7 The kernel perceptron algorithm

Recall the stunningly simple perceptron algorithm from section 5.3.2 . This algorithm can be modified to handle non-linear separation too by using kernel functions. In fact, this modification was one of the inspirations for the development of the support vector machines described above.
After having mapped a set of vectors with labels to , via , we are looking for a vector , such that
Such a vector is expressible as
The (dual) perceptron algorithm works adjusting the coefficients successively as follows: if is wrong about the placement of in (9.16) i.e., if , then let
If we have a kernel function for , then
and we can use the kernel function in the algorithm without resorting to computing and the inner product in .
Use the kernel function in Example 9.18 and the kernel perceptron algorithm to separate
Sketch the points and the separating curve.

9.3 Interior point methods

The support vector machines of the previous section simply called sklearn, which solved the optimization problem of Theorem 9.8 for us in milliseconds. But how? For the record, sklearn attacks the dual problem (9.10) with sequential minimal optimization (SMO): repeatedly pick two of the multipliers — two at a time, since the constraint must be preserved — and improve them by solving the resulting two-variable problem, for which there is a closed formula. That the dual has one variable per data point and touches the data only through the matrix is precisely what makes this fast, kernels included. So the dual problem of Section 9.1 is not just theory; it is what actually runs on your machine.
In this section we develop a different, completely general method for constrained convex optimization — the classical workhorse known as the interior point method. There is a very nice trick (probably going back to von Neumann) for solving constrained optimization problems of the form
where is defined by the differentiable functions as
The functions define the boundary (or barrier) of . We use them to define the logarithmic barrier function
defined on the interior
The boundary of is
You can see that the logarithmic barrier function explodes (becomes unbounded), when a vector approaches , since is unbounded as for .
The cool idea is to consider the function
for . This function has a global minimum .
Prove that is a convex function if and are convex functions.
Hint
Prove and use that if is a decreasing convex function (in one variable) and is a convex function, then is a convex function, where we assume the composition makes sense.
The upshot is that as . This is the content of the following theorem, which we will not prove.
Let be a point in with
for and . Then
and as . If (9.17) has a unique optimum , then by using we obtain a sequence as .
We move on to give concrete examples of Theorem 9.21 in action.

9.3.1 Quadratic function with polyhedral constraints

A much used setup in optimization is minimizing a quadratic functions subject to polyhedral constraints. This is the optimization problem
where is a matrix, is an matrix, and .
Certainly the constraints define a convex subset of , but the function is not strictly convex unless is positive definite. If is not positive semidefinite (9.19) is difficult.
If is positive semidefinite, the interior point method outlined above usually works well.
The optimization problem (9.2) has the form (9.19) , when we put
Show that the optimization problem in Theorem 9.8 also has the form (9.19) by writing up the matrices and and the vectors and for the labeled points with .
Quadratic optimization problems, such as the one in Theorem 9.8 , can be solved numerically in python. The code below uses the function minimize from scipy. It attempts (in general) to solve the optimization problem
In the cell below the optimization problem
has been entered.

Live Python

Take a look at the input format in Example 9.24 . Can you tell which optimization problem in this chapter is solved below? Compare the numerical solution with your solution to the exercise below Example 9.9 .

Live Python

Let us watch Theorem 9.21 in action on the fire station problem of Example 9.3 : find the smallest circle enclosing the seven houses
The cell below minimizes the barrier function from (9.18) for the constraints of (9.2) with
each unconstrained minimization done by minimize from scipy as in Example 9.24 , and each starting from the minimum found for the previous — a warm start, which is how interior point methods work in practice. Watch the printed output converge to the exact solution: the circle of radius centered at , touching the three houses , and . The plot shows the shrinking dashed circles closing in on the optimal solid one, and in red the path — the celebrated central path of interior point methods.

Live Python

If you are curious about the real algorithmic machinery — Newton's method from the previous chapter with exact line search applied to — see Section 10.5.1 of my book Undergraduate Convexity.
Solve the two optimization problems in each of the Exercises 7.48 , 7.49 and 7.50 numerically with minimize from scipy as in Example 9.24 (a maximum is found by minimizing ). Check the numerical output by actually solving the exercises.
Compute the best line separating the labeled data

((1, 0), +1), ((2, 0), +1), ((3, 0), +1), ((3, 2), +1), ((1, 1), -1), ((2, 2), -1).

using the support vector machine cell from Section 9.2 . Which of the six points are the support vectors?
The interior point method delivers approximations marching toward the optimum. The rest of the chapter treats the complementary, exact question: given a point , how do we recognize — and certify with a proof — that it is optimal?

9.4 A geometric optimality criterion

Consider the general optimization problem
where is a subset of .
Suppose that is a convex subset and a differentiable function in (9.20) . If is an optimal solution of (9.20) , then
If in addition is a convex function, then (9.21) implies that is optimal.
Proof
If is an optimal solution and , then
for every with , where denotes the epsilon function in the definition of differentiability (see Definition 7.3 ). Therefore
for . This is only possible if . We have silently applied the convexity of and the differentiability of at .
If in addition is convex and (9.21) holds, then Theorem 8.23 shows that is an optimal solution.
A nice application of Proposition 9.28 is where the constraints in are linear. Then you can test if is an optimal solution by solving the linear program
for . If the optimal value is , then is an optimal solution.
Let us test drive this on the convex optimization problem
where and . The constraints are linear: is the triangle with vertices , and .
Is the vertex an optimal solution? Here , so the linear program to solve is
A linear function attains its minimum over the triangle at a vertex (this is the content of the exercise below), so we only have to check three points: takes the values , and at , and . The optimal value is smaller than , so the test fails — and it fails informatively. For we have , so by Proposition 9.28 the vertex is not optimal: decreases along the edge from toward .
Let us instead try , which lies on the same edge. Now and the linear program is
with the values , and at the three vertices: the optimal value is . Since
the test succeeds and Proposition 9.28 (here we use that is convex) certifies that is an optimal solution — no further theory needed, just one linear program.
The cell below shows both verdicts geometrically. The level sets of are circles around the unconstrained minimum . The dotted red circle is the level set through : it dips into the triangle, so contains points with smaller -value and cannot be optimal — the red arrow is the descent along the edge found by the failed test. The green circle is the level set through : it only touches the triangle. It is tangent to the edge , and the tangent line is exactly the hyperplane from Proposition 9.28 — compare with the picture for a curved boundary in the next example.

Live Python

Proposition 9.28 also applies when the boundary of is curved, as in the optimization problem
Here Proposition 9.28 shows that is optimal: with , the hyperplane
which is the line , touches the boundary of
exactly at , and lies on the side where — as sketched below.
Sketch how Proposition 9.28 applies to show that an optimum in a linear programming problem
in the plane always can be found in a vertex.
Let be a differentiable convex function and
Suppose that for . Prove that is a minimum for defined on .
Guess the solution to the optimization problem
Show that your guess was correct!

9.5 The KKT conditions

The KKT in the title of this section is short for Karush-Kuhn-Tucker.
We will limit ourselves to a convex optimization problem of the form
where is defined by the differentiable convex functions for as
and is a convex function.
To the optimization problem (9.22) we associate the (famous) Karush-Kuhn-Tucker (KKT) conditions:
Notice that the KKT conditions consist of inequalities and equations in the unknowns . The KKT conditions form a surprising theoretical foundation for optimization problems of the type in (9.22) . You should take a peek back to the theory of Lagrange multipliers in section 7.10 and compare with (9.23) .
The KKT conditions associated with the convex optimization problem in Example 9.1 are
Verify that the KKT conditions of the optimization problem in Example 9.1 are the ones given in Example 9.34 .
To state our main theorem we need a definition.
The optimization problem (9.22) is called strictly feasible if there exists with
Below is the main result in our limited convex setting. We will not go into the proof, which can be found in my book Undergraduate Convexity.
  1. Let be an optimal solution of (9.22) . If (9.22) is strictly feasible, then the KKT conditions are satisfied at for suitable .
  2. If the KKT conditions are satisfied at for some , then is an optimal solution to (9.22) .
Let us now touch base with a rather simple example. Consider the optimization problem
Here and in (9.22) . Therefore the KKT conditions in (9.23) are
Before even thinking about reading on, you should attempt to find a solution to the above KKT conditions (inequalities) and then verify using Theorem 9.37 (ⅱ) that is optimal. Also, try only using Theorem 9.37 (ⅰ) and (9.25) to show that is not a solution to (9.24) .
Consider the convex optimization problem (9.22) and the KKT conditions (9.23) . Which of the following statements are true?
If in a solution of the KKT conditions, then the -th constraint is active i.e., .
If is an optimal solution, then the KKT conditions are satisfied at , even when (9.22) is not strictly feasible.
The KKT conditions can be satisfied at only one point .
If the KKT conditions are satisfied at , then is an optimal solution — no strict feasibility needed.
Give an example of a convex optimization problem as in (9.22) , which is not strictly feasible and with an optimal solution that does not satisfy the KKT conditions. Such an example shows that strict feasibility is necessary in Theorem 9.37 (ⅰ) .

9.5.1 Strategy

A general strategy for finding solutions to the KKT conditions in (9.23) is zooming in on (the Lagrange multipliers) testing each of them for the two cases and .
One important point, which you can read from (9.23) , is that if . To further elaborate, if , then an optimal solution must satisfy .
So where exactly in (9.23) is the above claim verified?
The condition simplifies the equations
in (9.23) .
In principle to solve the KKT conditions, one has to try out all the possibilities coming from or for .
Why possibilities above?
How do you solve the optimization problem (or decide there is no solution) if ?

9.5.2 Example

Let denote the set (see Figure 9.44 ) of points with
We will illustrate the mechanics of solving the KKT conditions in finding an optimal solution for
The convex set with optimal solution for (9.26) marked.
Putting
and , we are in a position to apply Theorem 9.37 , since are convex functions and for . This means that an optimal solution of (9.26) satisfies the KKT conditions. The same theorem tells us that the in a solution of the KKT conditions is an optimal solution (here we also use that is a convex function). The full set of KKT conditions in are
A strategy for finding a solution to the KKT conditions is trying (the eight) different combinations of strict inequalities in . You can see from the last two equations that is impossible. The condition shows that an optimal solution has to occur on the lower arc in Figure 9.44 . If , then and by the last two equations. This implies violating . Therefore . If , then and by and the last two equations. Therefore . So we are left with the case and giving
Inserting this into we end up with (see Figure 9.44 )
Theorem 9.37 is beautiful mathematics. Going through the KKT conditions as above can be quite lengthy if not impossible in practice. As we have seen, there are other methods for (at least) approximating an optimal solution.

9.5.3 Solving the KKT conditions by computer

Lengthy for a human — but look again at the strategy: cases, and each case is nothing but a system of equations together with some sign checks. That is a job for a computer, and sympy can do it with exact arithmetic. The program below is the strategy of this section made executable. For each of the cases it decides, for every constraint, between and (complementary slackness!), solves the resulting equations together with stationarity
and keeps only solutions passing the remaining KKT inequalities and .

Live Python

Compare with the hand computation above: seven of the eight cases die — for exactly the reasons we found — and the surviving case , delivers
the same numbers in a different radical costume, together with the optimal value . The program is not tied to this example: replace and the list (and the symbols) with your own convex optimization problem and it will grind through the cases for you — bearing in mind that the number of cases doubles with every constraint, which is precisely why practical solvers use the barrier and descent methods of the earlier sections instead. You are welcome to check your hand computations in the exercises below against it.

9.5.4 Closing the circle: KKT and the optimal hyperplane

This chapter opened with the optimal separating hyperplane and ends with certificates of optimality — and the two meet. The dual problem (9.10) was presented without derivation, and its two most mysterious ingredients were the linear combination (9.9) and the constraint . Both fall out of the KKT conditions, and for the two points that Example 9.12 treated with the dual, every step can be done by hand.
Return to the two points of Example 9.9 : with label and with label . This time we keep all three variables and of Theorem 9.8 and treat the problem as (9.22) with
and the two convex constraint functions
The problem is strictly feasible — the optimal line scaled up, say and , satisfies both constraints strictly — so by Theorem 9.37 the KKT conditions characterize the optimum exactly.
The gradients with respect to the three variables are
so the last KKT condition splits into two parts. The -part reads
— the mysterious linear combination (9.9) ! That the normal vector is built from the data points, weighted by multipliers and labels, is not an assumption of the dual; it is forced by the KKT conditions. The -part reads
which is exactly the dual constraint .
Next, complementary slackness. The multipliers cannot vanish: if , the -part would give , and then and would demand and at once. So , and forces both constraints to hold with equality:
These are the support vector equations. The claim that both dashed lines carry data points — argued after Theorem 9.8 with a paragraph of shifting and rescaling — is here simply complementary slackness.
The rest is arithmetic. Write . The -part gives , and subtracting the two support vector equations gives , that is , so . Then
and by Theorem 9.37 (ⅱ) the line is certifiably optimal — the same answer as the dual computation in Example 9.12 , now with a certificate attached. (The multiplier is twice the dual variable found in Example 9.12 ; the factor is a bookkeeping constant coming from the objective versus , absorbed by (9.9) .)
Every mystery of the dual has now been witnessed at small scale: the linear combination (9.9) is the -part of KKT stationarity, the constraint is its -part, and the support vectors are complementary slackness in action. The general derivation of (9.10) — the one we referred to the literature for — is exactly the computation above with points in place of two.

9.6 Optimization exercises

Below are some exercises especially related to the KKT conditions. In some of the exercises the minimization problem
is denoted
This should cause no confusion.
Consider the optimization problem
  1. Show that (9.27) is a convex optimization problem.
  2. Sketch the set of constraints in and show that cannot be an optimal solution to (9.27) .
  3. Write up the KKT conditions for (9.27) and explain theoretically (without actually solving them) why they must have a solution.
  4. Now solve (9.27) . Is the solution unique?
Consider the function given by
  1. Show that is strictly convex.
  2. Let denote the subset of points satisfying
    Show that is a closed convex subset.
  3. Solve the optimization problem
Let , where
  1. Why does the optimization problem
    have a solution?
  2. Find all optimal solutions to (9.29) .
  3. Let , where at least one of is non-zero. Show that an optimal solution to
    belongs to .
Let
  1. Use the KKT conditions to solve the minimization problem
  2. Use the KKT conditions to solve the minimization problem
Solve the optimization problem
Let and .
  1. State the KKT conditions for for .
  2. Suppose now that . For which and does have optimum in ? State the KKT conditions when .
Let be given by
  1. Show that is a convex function.
  2. Find . Is this minimum unique? Is a strictly convex function.
    Let
  3. Apply the KKT-conditions to decide if is an optimal solution to
  4. Find
    and
Let be given by
and let
  1. Show that is not a convex function.
  2. Show that is a convex function on the open subset
    and conclude that is convex on .
  3. Show that is an optimal solution for the optimization problem . Is a unique optimal solution here?
Let be given by
and by
  1. Show that is a convex function. Is strictly convex?
  2. Show that is a convex subset of .
  3. Does there exist an optimal point for the minimization problem
    with ?
  4. Does there exist an optimal point for the minimization problem
    with ?
Let
and
Solve the optimization problem
Let be given by
Below, the minimization problem
is analyzed for various subsets .
  1. Show that is a convex function
  2. Let
    Show that cannot be an optimal solution to (9.30) . Find an optimal solution to (9.30) .
  3. Find an optimal solution in (9.30) for
  4. Are the optimal solutions in (2) and (3) unique?
Let be given by
  1. Show that is a convex function and solve the minimization problem .
    Now let
    and consider the minimization problem (P) given by
  2. Show using the KKT conditions that is not optimal for (P).
  3. Find an optimal solution for (P). Is it unique?