Support vector machines
Among all separating hyperplanes, the widest band: hard and soft margin, hinge loss plus L2, what the dual says about each training point, the role of C, and why a wide margin generalizes.
Which separating line
The topic Classification metrics taught us to judge a trained classifier. It does not say which classifier to train. When the classes in the training set are separable, infinitely many hyperplanes have zero training error, and every metric on the training set calls them perfect. The logistic loss sends the weights to infinity on such data (see Logistic regression). The hinge loss drops to zero once every margin is at least and stops telling the solutions apart. The support vector machine (SVM) answers with geometry: take the hyperplane that stays as far as possible from the nearest training points.
Classes in this topic are . Recall two quantities from Linear classifiers and surrogate losses. The distance from a point to the hyperplane is
and the margin of an object is . It is positive when the object is classified correctly. For a hyperplane that classifies every point correctly, . So the margin of the hyperplane, its distance to the nearest training point, is
The running example comes from the topic Duality of the course Mathematics for ML. The negative points are and , the positive ones and . The line separates them without errors, but passes from and . The line makes no errors either, and its nearest points, , and , are at distance . A new negative object just above lands on the wrong side of the first line and on the right side of the second.
The SVM idea is to maximize . The intuition: a decision that does not change when every training point is nudged a little is less tuned to the accidents of the sample. The formal argument comes in the last block.
The hard margin
Multiply and by the same positive number. The classifier does not change, and every and are multiplied by that number, so stays the same. The scale can therefore be fixed for free. The SVM fixes it so that the nearest points have . Then every point satisfies , and the margin is .
Between the hyperplanes and lies a band of width with no training points inside. Maximizing the margin means minimizing . Squaring it and adding a factor makes the objective smooth:
This is the hard-margin SVM. The objective is strictly convex in and the constraints are linear. So on separable data the optimal is unique, and the problem is a quadratic program that standard solvers handle.
In the example the negative points fill the segment on the axis, and the nearest positive point to it is , at distance . No line can be farther than half of that from both classes. The line achieves it. In the SVM scale this is and : , and . In the topic Duality the same answer came out as the perpendicular bisector of the shortest segment between the convex hulls of the classes. Here we need the dual for something else: it tells what role each training point plays.
Soft margin: slack and the hinge loss
Add two points to the example: a negative and a positive . The classes are still separable, but barely. The hard margin now gives and , and the band width drops to , times narrower than before. Two points dictate the whole solution. If they are noise, say a customer with a wrong label, we would rather give them up. And when the classes overlap, no satisfies all the constraints .
The soft-margin SVM lets each point violate its constraint by a slack and pays per unit of slack:
With the point lies on its class's edge of the band or farther from the hyperplane. With it is inside the band but still on its own side. With it is on the hyperplane itself, and with on the wrong side. Every error adds at least to , so the total slack bounds the number of training errors from above.
For fixed and the best slack is the smallest feasible one, . Substitute it, and the constraints disappear:
The first term is the hinge loss, the second the ridge penalty of Regularization. So the SVM is not a new kind of model but a linear classifier trained with a particular surrogate loss and an L2 penalty. Dividing by brings it to the familiar form "mean loss plus ": large means weak regularization.
The topic Linear classifiers and surrogate losses promised to derive what the hinge loss estimates. Let . The expected loss of a score at the point is . On it is the straight line , and outside that interval it only grows. The minimum is at when and at when . That is the sign of the Bayes classifier and nothing more. SVM scores are not probabilities; when probabilities are needed, they are fitted on held-out data with Platt scaling from Logistic regression.
On the six points with the solution is , , with a band width of . The band is times wider than the hard one. The price is two points: falls inside the band with , and ends up on the wrong side with .
The dual with a ceiling C
The topic Duality derived the dual of the hard margin, and Lagrange multipliers and KKT conditions gave the optimality conditions. The soft margin adds one detail. Give a multiplier to each margin constraint and a multiplier to each constraint :
Minimizing over and gives what it gave before: and . The new part is the derivative in :
The Lagrangian is linear in , so with a nonzero slope the dual function is . Hence , and together with this caps from above. After substitution the terms with and vanish, and the dual problem remains:
It is the hard-margin dual with a ceiling added. The constraints are affine and the problem is feasible: , , . So, as in Duality, strong duality holds: the primal and dual optima coincide, and on the six points with both equal . The classifier is recovered from :
In scikit-learn these numbers can be read off directly. The field support_ holds the indices of the points with (grouped by class), dual_coef_ the products , and coef_ the vector :
import numpy as np
from sklearn.svm import SVC
X = np.array([[0, 0], [2, 0], [1, 2], [3, 3], [0, 1], [1, 1]])
y = np.array([-1, -1, 1, 1, -1, 1])
m = SVC(kernel="linear", C=1).fit(X, y)
print(m.support_)
print(m.dual_coef_.round(3))
print(m.coef_.round(3), m.intercept_.round(3))[1 4 2 5]
[[-0.6 -1. 0.6 1. ]]
[[0.4 1.2]] [-1.8]Three kinds of points
What does the dual say about each point? The answer comes from complementary slackness, one condition per constraint:
The second is after substituting . Together they sort the training points into three groups.
- . Then , so and : the point is on the edge of the band or beyond it. It does not enter .
- . Then gives , and gives : the point lies exactly on an edge of the band. Such points give the bias. From and we get ; in practice this value is averaged over all such points.
- . Then , the slack may be positive, and : the point is on the edge, inside the band or on the wrong side.
The points with are called support vectors. Here are the six points with :
| point | ||||||
|---|---|---|---|---|---|---|
and are far beyond the edges of the band, and their multipliers are zero. and sit on the edges with . The point gives , and gives . and violate their constraints and hit the ceiling .
The solution rests on the support vectors
The solution is a weighted sum of the support vectors alone. This has three consequences.
The other points can be thrown away. Delete a point with . The same , and remaining still satisfy the KKT conditions, and for a convex problem that is enough. The solution does not change: without and we get the same and . Deleting a support vector does change it. Without the answer becomes , : the line of the four-point example.
A leave-one-out bound. Leave-one-out is the -fold cross-validation of Validation and overfitting with . A point with , when held out, is classified correctly: the model without it is the same and keeps it on the edge of the band or beyond. So the leave-one-out error is at most the fraction of support vectors. The fine print: the solver must return the same solution. And this bounds a procedure on samples of size , not the risk of one final model.
The margin from the dual alone. With a hard margin, sum over all points. This gives . The left side equals , so
In the four-point example , , the sum is and .
Compare with logistic regression. There every training point enters the gradient with weight , and none drops out. In the SVM each point's contribution to is capped by , and points beyond the band contribute nothing.
How C trades margin for errors
is the exchange rate between band width and violations. On the six points:
| band width | support vectors | of them with | training errors | ||
|---|---|---|---|---|---|
At we already have the hard-margin solution, and larger do not change it. Here has and : the ceiling also allows a point exactly on the edge. On separable data the hard margin is the limit . On overlapping data the hard-margin problem has no feasible point at all, and a large only makes the unavoidable slack more expensive.
Real data show where this ends. Take the breast cancer data from scikit-learn: 569 tumours, 30 standardized features, 398 objects for training and 171 for testing.
| support vectors | of them with | band width | train accuracy | test accuracy | |
|---|---|---|---|---|---|
With small almost every support vector sits at the ceiling: the band is wide and many points are inside it. As grows the band narrows, the training accuracy reaches , and the test accuracy falls back to . Large is weak regularization, and the model overfits, as with a small ridge penalty.
So is chosen by cross-validation on a logarithmic grid, as in Validation and overfitting. The band width is measured in the units of the features, so the features are standardized first. Otherwise the feature with the largest scale dominates .
How this is solved in practice. SVC in scikit-learn is built on LIBSVM. Because of the constraint , at least two multipliers must change at once, and SMO (sequential minimal optimization) repeatedly solves the problem for a pair of in closed form. On millions of objects a linear SVM is better trained in the primal: hinge loss plus L2, stochastic subgradient steps, as in Stochastic and adaptive optimizers.
Why a wide margin generalizes, and what next
Why should a wide margin generalize? The first generalization bound came from the topic Inequalities and concentration of the course Probability Theory. For models the gap between the sample error and the true error grows like . There are infinitely many hyperplanes, and the classical replacement for grows with the dimension . In high dimension the mere fact that the sample could be separated says almost nothing.
The margin removes the dimension. Suppose for every object, and the distribution is separable with margin by a hyperplane through the origin. Then with probability at least over a training sample of size , the 0–1 risk of the hard-margin SVM is at most (Shalev-Shwartz and Ben-David, 2014, Theorem 15.4)
The dimension does not appear, only the ratio of the data radius to the margin. With , and the bound is . It is crude, like every bound of its kind, but it holds in a million dimensions as well as in two.
To sum up. Among the separating hyperplanes the SVM picks the widest band. The soft margin is the hinge loss plus an L2 penalty, with setting their balance. The dual sorts the points into three groups, and the solution rests on the support vectors alone.
But for any the boundary is still a hyperplane in the original features. XOR, four points that no line separates, is beyond it. Two facts of this topic point the way out. The dual and the classifier touch the data only through inner products . And the margin bound does not depend on the dimension. So we could map into a space of huge dimension, separate the data there with a wide margin, and compute nothing but inner products. That is the programme of the next topic, Kernels.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.