Here are two groups of points that a straight line can separate. A line close to the left group separates them. So does a line close to the right group, and so do a thousand lines in between. They all make zero mistakes on the training data. Which one should we keep? This lesson gives one clear answer: keep the line with the widest empty street between the two groups. That choice is the support vector machine (SVM), and it leads to some of the most useful ideas in classic machine learning: a solution held up by only a few points, a penalty that lets a few points break the rules, and a loss function that is exactly zero for points that are safely classified.
This lesson uses the linear classifier of P3.A7, the dot product and the fact that is perpendicular to the line (P1.B3), and the constrained optimization of P1.F7. P3.B7 then bends the line with the kernel trick.
Many lines, one street
A linear classifier predicts the class from the sign of a score:
The points with form the decision boundary: a line in two dimensions, a plane in three, a hyperplane in general. This lesson labels the classes and instead of and , because then “correct” has a one-line test: .
If the classes can be separated, many get every training point right. Picture the line as the centre of a street. A line that passes very close to a training point has a thin street: a little noise in that point could push it across. A line with a wide empty street leaves room on both sides. The SVM chooses the line whose street is widest. The street width is called the margin. Statistical theory links wide margins to better bounds on the error on new data, but a bound is not a guarantee. The practical reasons are simpler: the problem is convex, so the answer is unique, and the answer ignores points that are far from the boundary.
The picture: drag the points
The widget shows the six training points of the worked example below. Class is a blue circle, class a pink square. The solid line is the boundary, the dashed lines are the street edges, and a ring marks a support vector. Start with the penalty slider at its right end, “hard margin”. The readouts show , , the street width and how many points are support vectors.
Things to try:
- The defaults. , , street width , three rings. Drag the point at anywhere to the right of the dashed edge at , or the point at left or up: nothing changes. Nudge a ringed point and the whole line moves.
- A stray point. Press “One stray point” with the slider at the hard margin: a single pink square near the blue group squeezes the street from width to (, ). Now lower the slider to : the width returns to , but the stray point is now on the wrong side, with a red slack segment. Lower to and the street widens to with four points inside it or beyond it.
- Overlap. On “Overlapping” the hard margin has no solution and the widget says so. At the width is and two points are misclassified.
- The P1.F7 points. “P1.F7 points” loads the three points of the constrained optimization lesson on one horizontal line: , , width , and only two rings.
- Keyboard. Tab to a point and use the arrow keys (Shift moves four steps). There are at most 14 points.
Distance and the scaling freedom
P3.A7 and P1.B3 gave this: the distance from a point to the hyperplane is . The closest point on the plane to is , because is perpendicular to the plane (P1.B3). It lies at distance . Dividing by is essential: the score alone is not a distance. Check it with , (the vertical line ) and the point : , , so the distance is , the horizontal gap from to .
For a labelled point, the signed distance is positive when the point is on the correct side. The geometric margin of a data set is the smallest of these over all training points. The SVM maximizes it.
There is a freedom to remove. The pairs and describe the same line. Multiplying and by any positive number changes the scores but not their signs, and not the distances, because the factor cancels in . To fix the freedom, scale the pair so that the closest point has . Then every training point satisfies
with equality for the closest points. Their distance to the line is , one on each side, so the street between them has width
To derive it, take a closest point of class and a closest point of class , so and . Subtracting gives . The width is the length of the part of along the direction , which is . A wide street is therefore a short .
The hard-margin SVM
Maximizing is the same as minimizing , or (the square removes the root and the tidies the derivative). The hard-margin SVM is
This is a convex quadratic objective with linear constraints, a quadratic program (P1.F2, P1.F7). Convexity has two consequences: no local minima to get stuck in, and, since is strictly convex, one answer for . If the data cannot be separated, no satisfies all the constraints and the problem has no solution; the soft margin below repairs that.
The 1-D example of P1.F7. Take labelled , labelled and labelled . The constraints are , and . The answer is , : the first two hold with equality (, and ) and the third has . The street between and has width . P1.F7 gave the multipliers and : they satisfy and rebuild the weight, .
A 2-D example. Six points: class at , , ; class at , , . Guess that the points , and touch the street, so their constraints hold with equality:
Subtracting the last two gives , so . Subtracting the first from the second gives , so and . The line is , with and width . Now check the guess against the other three constraints: has , has and has , all above . The guess is consistent with the other three constraints. To be sure it is the minimum we also need positive multipliers, which come next. Together these are the KKT conditions (P1.F7), and for a convex problem they are enough. The multipliers come from the conditions and : they are for , for and for , all positive, and for the other three. (Check: .) The two optimal values agree: and (the duality of P1.F7).
Support vectors: only the touching points count
A constraint is active when it holds with equality. The points whose constraints are active sit on the edge of the street. These are the support vectors, the points that carry weight: the points with a positive multiplier (complementary slackness, P1.F7: a constraint that is not active has multiplier ). In a rare degenerate case a point can touch the street edge and still have multiplier ; such a point is not counted, and removing it changes nothing. In the example they are , and .
The solution is built only from them: , and the sum has non-zero terms only for the support vectors. Two things follow, and the widget shows both:
- Moving a non-support point changes nothing, as long as it stays outside the street. Moving to leaves , . Deleting it changes nothing either.
- Moving or deleting a support vector changes the line. Moving to gives , and width . Deleting gives and a wider street, .
At prediction time too, only the support vectors are needed: . This is the form P3.B7 uses: the data enter only through dot products.
Go deeper The dual problem
Give each constraint a multiplier and form the Lagrangian . Setting the derivative with respect to to zero gives , and with respect to gives . Substituting back leaves a problem in alone:
The data appear only through the dot products , which is what lets a kernel replace them (P3.B7). In the soft margin below the only change is the extra bound . The conditions on the multipliers are: means ; means (on the street edge); means (inside the street or on the wrong side).
The soft margin: allowing mistakes
Real data overlap, and one stray point can ruin a hard margin, as the widget showed. The soft margin lets each point break its constraint by an amount , called its slack:
A point with is outside the street or on its edge; is inside the street but on the right side; is on the wrong side. Slack is not free: the problem is
The penalty C sets the price of slack. It is still a convex quadratic program. The two ends of the dial:
- Large C: slack is expensive, so the line works hard to classify every point and the street narrows. As the soft margin approaches the hard margin.
- Small C: slack is cheap, so the street stays wide even if several points are inside it or on the wrong side.
Take the six points plus a stray class point at (the widget’s “One stray point”). The exact solutions:
| width | slack above 0 | misclassified | |
|---|---|---|---|
| 0.1 | 3.92 | 4 | 1 |
| 0.5 | 2.12 | 2 | 1 |
| 1 | 2.00 | 1 | 1 |
| 5 | 0.80 | 1 | 0 |
| 10 (and any larger) | 0.50 | 0 | 0 |
At the line is again , , the stray point has , so its slack is , and the objective is . Above the stray point is classified correctly and the street is a quarter of the width it had at . Which is better depends on whether the stray point is a real example or a labelling error. That is a question for validation data (P3.A4): is a hyperparameter, usually searched on a logarithmic grid.
Points with are support vectors too: with . The widget counts them in the rings.
Hinge loss and the unconstrained form
For a given the best slack of a point is the smallest allowed one, . This function of is the hinge loss:
It is once the point is outside the street or on its edge (), and then grows in a straight line as falls, passing through at (on the boundary). Substituting the slack removes the constraints, and dividing the objective by for examples gives
The two have the same minimizer, because one objective is the other divided by the positive number . This is a regularized loss of the kind in P3.A6: the first term is an L2 penalty (with a penalty written instead, ). Check with the stray-point data at : , ; the objective divided by is , and . So a large means a small , a weak penalty and a flexible fit. Remember that multiplies the data-fit term, so it goes the opposite way from . The bias is not penalized in this form.
Hinge versus logistic loss
Logistic regression (P3.A7) uses on the same score. Both are convex functions of that fall as the score gets more correct; the zero-one loss, which counts a mistake as , is not convex.
| hinge | logistic (ln) | |
|---|---|---|
| 2 | 1.3133 | |
| 0 | 1 | 0.6931 |
| 0.5 | 0.5 | 0.4741 |
| 1 | 0 | 0.3133 |
| 2 | 0 | 0.1269 |
| 3 | 0 | 0.0486 |
The difference is in the tail. The hinge loss is exactly zero from on, so a point that is safely classified has a zero gradient and stops affecting the line: this is why the solution depends on few points. The logistic loss is never exactly zero, so every point keeps pulling a little, however well it is classified. In exchange, logistic regression models a probability, . The SVM score is a signed distance (scaled by ), not a probability. To get probabilities one fits a mapping from scores to probabilities on held-out data, for example Platt scaling (a logistic curve fitted to the scores), and checks calibration (P3.A10). scikit-learn’s SVC(probability=True) does this with an internal cross-validation, which makes training slower.
Training an SVM
Subgradient descent on the hinge form. The hinge loss has a corner at , so it has no gradient there, but it has a subgradient: for take , otherwise . Full-batch subgradient descent on uses the step , capped at (the first steps would otherwise be huge), which suits a strongly convex objective (stochastic versions such as Pegasos use the same idea). The cell below runs it on the stray-point data and reaches the exact answer , to about three decimals.
Quadratic-programming solvers. For the exact answer the dual problem is solved by a specialized method; the common one is sequential minimal optimization (SMO, Platt 1998), which repeatedly picks two multipliers and solves for them exactly. It is what the widget uses, and what scikit-learn’s SVC does through the LIBSVM library. For the dual QP the cost grows faster than linearly in the number of examples (scikit-learn’s documentation says the fit time scales at least quadratically and may be impractical beyond tens of thousands of examples), so kernel SVMs become slow at tens of thousands of examples and more. LinearSVC uses the LIBLINEAR library and scales to far larger data.
Practical matters
Scale the features. The street is measured with the ordinary distance, so a feature measured in large units dominates it. Shrinking feature 1 by a factor of in the stray-point data, with , turns the fit from (four support vectors) into in the original units (six support vectors): the same data in other units gives a different classifier. Standardize the features, fitting the scaler on the training set only (P3.A11).
More than two classes. An SVM is binary. One-vs-rest trains one classifier per class (class against all others), so classifiers, and predicts the class with the highest score. One-vs-one trains one per pair of classes, classifiers (3 for 3 classes, 45 for 10), and takes a vote. scikit-learn’s SVC uses one-vs-one internally and LinearSVC uses one-vs-rest. A softmax output (P3.A8) is the alternative that handles all classes at once.
Kernels, in one sentence. Because the data enter only through dot products, replacing with a similarity function lets the same method draw a curved boundary. P3.B7 shows how.
History. The idea of the optimal separating hyperplane is due to Vapnik and Chervonenkis in the 1960s. The soft margin, which made the method usable on overlapping data, and the name “support-vector network” are from Cortes and Vapnik, “Support-vector networks”, Machine Learning 20, 273–297 (1995).
Intuition
Think of a road to be built between two villages, as wide as possible without touching any house. The widest road is blocked by the nearest houses on each side. Those few houses decide the road. Moving a house deep inside its village does not change the road. A stray house in the middle of the other village is a problem: either squeeze the road to nothing, or agree to demolish it. The penalty is the price of demolition. The analogy breaks in that houses can be on the wrong side of a straight road only because we allowed it; real data are not houses, and the street can tilt in many dimensions.
Math
Score , distance , canonical scaling , width .
Hard margin: s.t. . Soft margin: , .
Dual: s.t. , ; .
Regularized form: with ; subgradient of the hinge: if , else .
Code
The same model in scikit-learn, shown as a static block because scikit-learn is not available in the in-browser runner. The output is from a local run (scikit-learn 1.8.0) on the six points of the worked example.
import numpy as np
from sklearn.svm import SVC
X = np.array([[0, 0], [1, 3], [2, 1], [4, 0], [4, 4], [5, 2]], float)
y = np.array([-1, -1, -1, 1, 1, 1])
svm = SVC(kernel="linear", C=1e6) # a huge C: hard margin
svm.fit(X, y)
print("w:", svm.coef_[0], " b:", svm.intercept_[0].round(4))
print("support vectors:", svm.support_vectors_.tolist())
print("dual_coef_ (alpha*y):", svm.dual_coef_[0].round(3))
print("width:", round(2 / np.linalg.norm(svm.coef_[0]), 3))w: [ 1. -0.] b: -3.0
support vectors: [[2.0, 1.0], [4.0, 0.0], [4.0, 4.0]]
dual_coef_ (alpha*y): [-0.5 0.375 0.125]
width: 2.0SVC solves the dual problem with LIBSVM and stores in dual_coef_. LinearSVC is a different solver (LIBLINEAR): its default loss is the squared hinge , and it also penalizes the bias, so on the stray-point data with the call LinearSVC(loss="hinge") gave , , while SVC gave , . They are two related but different objectives.
Try it
The first cell solves the hard-margin problem exactly by trying every triple of points as the touching set, then checks the multipliers and the two moves from the text. The second cell trains the stray-point problem by subgradient descent.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Try changing to in the second cell. The exact answer is then , , but with this step rule descent has not arrived after steps, because a larger means a smaller and a slower step schedule. Quadratic-programming solvers do not have that problem.
Exercises
- For , , find the distance from the point to the line , and the street width if the closest points satisfy .
Show answer
and , so the distance is . The width is . - A student reports , for the six-point example. Is it the same line as the SVM answer? Is it the SVM solution of the optimization problem?
Show answer
It is the same line (), but gives at the closest points, so the constraints are not tight and is bigger than . The minimizer is . - Solve the hard-margin problem for the two points (class ) and (class ) in one dimension: , , width and the multipliers.
Show answer
Both constraints are active: and , so , , width . From with : , so for both, and . - A point has . Give its hinge loss and its logistic loss (natural log).
Show answer
Hinge ; logistic . - A data set has examples. A soft-margin SVM with is rewritten as . Find , and say what happens to if is increased.
Show answer
. A larger gives a smaller : weaker regularization. - How many binary classifiers do one-vs-rest and one-vs-one train for 5 classes?
Show answer
One-vs-rest: . One-vs-one: . - In the six-point example, which deletion changes the hard-margin line: or ? What is the width after the change?
Show answer
Deleting the non-support point changes nothing. Deleting the support vector changes the line to , , and the width becomes .
Check your understanding
In the hard-margin SVM with the closest points at , what is the width of the street, and what do we do to widen it?
The closest points are from the line on each side, so the width is and a short gives a wide street. The width does not grow with , and the bias only shifts the line without changing the width.
In a trained hard-margin SVM you delete one training point. When is the line certain to stay exactly the same?
A point with has an inactive constraint and multiplier , so the solution is built without it and removing it leaves the same minimizer. A hard-margin solution has no misclassified points. Removing a support vector can change the line, and distance to the origin plays no role.
A soft-margin SVM is under-fitting: the street is very wide and many training points are inside it. Which change moves it the other way?
A larger makes slack more expensive, so the line works harder to classify the points correctly and the street narrows. A smaller widens it further. Dividing the features changes the distances and so the fit, but not reliably in this direction. Without slack there is no soft margin, and no .
A point has . What are its hinge loss and its logistic loss ?
The hinge loss is . The logistic loss is , small but never exactly zero. A hinge loss of would need , and the other pair of numbers matches neither formula.
You need the probability that a new email is spam from an SVM. What is the sound approach?
The SVM score is a signed distance, scaled by , that can be any real number, so it is not a probability. A calibration step fitted on data not used for training turns scores into probabilities. Dividing by and counting support vectors have no probabilistic meaning.
Next: P3.B7 shows how replacing the dot product turns this straight street into a curved one: the kernel trick. P3.A6 and P3.A7 are the neighbours to compare with for the regularization and the loss, and P3.A11 covers the scaling that an SVM needs.