Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

Support vector machines

P3.B645 min●●● AdvancedReviewed Dec 2, 2026

Why this matters for machine learning

A support vector machine is a linear classifier chosen by one clear rule: leave the widest possible empty street between the classes. The rule gives a convex problem with one answer, a solution that depends only on a few points, and the hinge loss that appears again in modern margin-based training.

  • Kernels replace the dot product inside the SVM with a similarity function, which gives curved boundaries without ever building the new features. (P3.B7: The kernel trick)
  • The penalty C of the soft margin plays the role of the inverse of the regularization strength, so it is tuned on validation data like any other model-size setting. (P3.A6: Regularization: L1 and L2)
  • The hinge loss is one member of a family of margin-based losses; comparing it with the logistic loss shows what each one asks of the model. (P3.A7: Logistic regression)
  • Support vectors are the active constraints of a constrained optimization problem, the same idea that Lagrange multipliers and KKT conditions describe. (P1.F7: Constrained optimization and Lagrange multipliers)

Before this: Logistic regression, Constrained optimization and Lagrange multipliers, Dot product and cosine similarity

After this lesson you can

  • Compute the signed distance from a point to the line w·x + b = 0, and derive that with the closest points on w·x + b = ±1 the street has width 2/‖w‖
  • State the hard-margin SVM as a convex problem, solve a small 2-D example exactly by finding which points touch the street, and say why only those support vectors determine the answer
  • Explain the slack variables, the effect of the penalty C and its relation to a regularization strength, and write the soft margin as hinge loss plus a penalty on ‖w‖²
  • Compare the hinge loss with the logistic loss, train a linear SVM by subgradient descent, and name what to do about feature scale, multi-class data and probabilities

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 w\mathbf{w} is perpendicular to the line w⋅x+b=0\mathbf{w}\cdot\mathbf{x}+b=0 (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:

f(x)=w⋅x+b,y^=sign⁡(f(x))∈{−1,+1}.f(\mathbf{x})=\mathbf{w}\cdot\mathbf{x}+b,\qquad \hat y=\operatorname{sign}\bigl(f(\mathbf{x})\bigr)\in\{-1,+1\}.

The points with f(x)=0f(\mathbf{x})=0 form the decision boundary: a line in two dimensions, a plane in three, a hyperplane in general. This lesson labels the classes −1-1 and +1+1 instead of 00 and 11, because then “correct” has a one-line test: y f(x)>0y\,f(\mathbf{x})>0.

If the classes can be separated, many (w,b)(\mathbf{w},b) 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 +1+1 is a blue circle, class −1-1 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 w\mathbf{w}, bb, the street width 2/∥w∥2/\lVert\mathbf{w}\rVert and how many points are support vectors.

Support vector machine: drag the points

0123456−1012345feature 1feature 2
class +1 class −1 support vector line street edges slack
w = (1, 0), b = −3
Street width 2/‖w‖ = 2
Support vectors: 3
Slack above 0: 0 points
Misclassified: 0
Objective ½‖w‖² + C·Σξ = 0.5 (½‖w‖²)

Every point is outside the street or on its edge. Street width 2, held by 3 support vectors.

Drag a point, or Tab to it and use the arrow keys (Shift for larger steps). The solid line is w·x + b = 0 and the dashed lines are w·x + b = ±1, so the street between them has width 2/‖w‖. A ring marks a support vector (multiplier above 0). A red segment shows the slack: how far a point has to move to reach its own side of the street.

A linear SVM on points you can drag. The solid line is w·x + b = 0, the dashed lines are w·x + b = ±1 and the shaded street between them has width 2/‖w‖. Rings mark support vectors. Red segments show slack: how far a point would have to move to reach its own side of the street. The slider sets the penalty C, from 0.05 to a huge value that acts as a hard margin.

Things to try:

  • The defaults. w=(1,0)\mathbf{w}=(1,0), b=−3b=-3, street width 22, three rings. Drag the point at (5,2)(5,2) anywhere to the right of the dashed edge at x=4x=4, or the point at (1,3)(1,3) 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 22 to 0.50.5 (w=(4,0)\mathbf{w}=(4,0), b=−15b=-15). Now lower the slider to C=1C=1: the width returns to 22, but the stray point is now on the wrong side, with a red slack segment. Lower to C=0.1C=0.1 and the street widens to 3.9213.921 with four points inside it or beyond it.
  • Overlap. On “Overlapping” the hard margin has no solution and the widget says so. At C=1C=1 the width is 22 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: w=(1,0)\mathbf{w}=(1,0), b=−1b=-1, width 22, 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 x\mathbf{x} to the hyperplane w⋅x+b=0\mathbf{w}\cdot\mathbf{x}+b=0 is ∣w⋅x+b∣/∥w∥\lvert\mathbf{w}\cdot\mathbf{x}+b\rvert/\lVert\mathbf{w}\rVert. The closest point on the plane to x\mathbf{x} is x−f(x)∥w∥2w\mathbf{x}-\frac{f(\mathbf{x})}{\lVert\mathbf{w}\rVert^2}\mathbf{w}, because w\mathbf{w} is perpendicular to the plane (P1.B3). It lies at distance ∣f(x)∣ ∥w∥/∥w∥2=∣f(x)∣/∥w∥\lvert f(\mathbf{x})\rvert\,\lVert\mathbf{w}\rVert/\lVert\mathbf{w}\rVert^2=\lvert f(\mathbf{x})\rvert/\lVert\mathbf{w}\rVert. Dividing by ∥w∥\lVert\mathbf{w}\rVert is essential: the score f(x)f(\mathbf{x}) alone is not a distance. Check it with w=(1,0)\mathbf{w}=(1,0), b=−3b=-3 (the vertical line x1=3x_1=3) and the point (2,1)(2,1): f=2−3=−1f=2-3=-1, ∥w∥=1\lVert\mathbf{w}\rVert=1, so the distance is 11, the horizontal gap from 22 to 33.

For a labelled point, the signed distance y f(x)/∥w∥y\,f(\mathbf{x})/\lVert\mathbf{w}\rVert 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 w=(1,0), b=−3\mathbf{w}=(1,0),\ b=-3 and w=(2,0), b=−6\mathbf{w}=(2,0),\ b=-6 describe the same line. Multiplying w\mathbf{w} and bb by any positive number changes the scores but not their signs, and not the distances, because the factor cancels in f/∥w∥f/\lVert\mathbf{w}\rVert. To fix the freedom, scale the pair so that the closest point has y f=1y\,f=1. Then every training point satisfies

yi (w⋅xi+b)≥1,y_i\,(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1,

with equality for the closest points. Their distance to the line is 1/∥w∥1/\lVert\mathbf{w}\rVert, one on each side, so the street between them has width

width=2∥w∥.\text{width}=\frac{2}{\lVert\mathbf{w}\rVert}.

To derive it, take a closest point x+\mathbf{x}_+ of class +1+1 and a closest point x−\mathbf{x}_- of class −1-1, so w⋅x++b=1\mathbf{w}\cdot\mathbf{x}_++b=1 and w⋅x−+b=−1\mathbf{w}\cdot\mathbf{x}_-+b=-1. Subtracting gives w⋅(x+−x−)=2\mathbf{w}\cdot(\mathbf{x}_+-\mathbf{x}_-)=2. The width is the length of the part of x+−x−\mathbf{x}_+-\mathbf{x}_- along the direction w/∥w∥\mathbf{w}/\lVert\mathbf{w}\rVert, which is 2/∥w∥2/\lVert\mathbf{w}\rVert. A wide street is therefore a short w\mathbf{w}.

The hard-margin SVM

Maximizing 2/∥w∥2/\lVert\mathbf{w}\rVert is the same as minimizing ∥w∥\lVert\mathbf{w}\rVert, or 12∥w∥2\tfrac12\lVert\mathbf{w}\rVert^2 (the square removes the root and the 12\tfrac12 tidies the derivative). The hard-margin SVM is

min⁡w, b 12∥w∥2subject toyi(w⋅xi+b)≥1  for every i.\min_{\mathbf{w},\,b}\ \tfrac12\lVert\mathbf{w}\rVert^2\quad\text{subject to}\quad y_i(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1\ \text{ for every }i.

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 12∥w∥2\tfrac12\lVert\mathbf{w}\rVert^2 is strictly convex, one answer for w\mathbf{w}. If the data cannot be separated, no (w,b)(\mathbf{w},b) satisfies all the constraints and the problem has no solution; the soft margin below repairs that.

The 1-D example of P1.F7. Take x=0x=0 labelled −1-1, x=2x=2 labelled +1+1 and x=5x=5 labelled +1+1. The constraints are −b≥1-b\ge1, 2w+b≥12w+b\ge1 and 5w+b≥15w+b\ge1. The answer is w=1w=1, b=−1b=-1: the first two hold with equality (b=−1b=-1, and 2−1=12-1=1) and the third has 5−1=4>15-1=4>1. The street between x=0x=0 and x=2x=2 has width 2/∣w∣=22/\lvert w\rvert=2. P1.F7 gave the multipliers 12,12\tfrac12,\tfrac12 and 00: they satisfy ∑αiyi=−12+12+0=0\sum\alpha_iy_i=-\tfrac12+\tfrac12+0=0 and rebuild the weight, ∑αiyixi=12⋅2−12⋅0=1=w\sum\alpha_iy_ix_i=\tfrac12\cdot2-\tfrac12\cdot0=1=w.

A 2-D example. Six points: class −1-1 at (0,0)(0,0), (1,3)(1,3), (2,1)(2,1); class +1+1 at (4,0)(4,0), (4,4)(4,4), (5,2)(5,2). Guess that the points (2,1)(2,1), (4,0)(4,0) and (4,4)(4,4) touch the street, so their constraints hold with equality:

2w1+w2+b=−1,4w1+b=1,4w1+4w2+b=1.2w_1+w_2+b=-1,\qquad 4w_1+b=1,\qquad 4w_1+4w_2+b=1.

Subtracting the last two gives 4w2=04w_2=0, so w2=0w_2=0. Subtracting the first from the second gives 2w1−w2=22w_1-w_2=2, so w1=1w_1=1 and b=−3b=-3. The line is x1=3x_1=3, with ∥w∥=1\lVert\mathbf{w}\rVert=1 and width 22. Now check the guess against the other three constraints: (0,0)(0,0) has y f=3y\,f=3, (1,3)(1,3) has 22 and (5,2)(5,2) has 22, all above 11. 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 w=∑αiyixi\mathbf{w}=\sum\alpha_iy_i\mathbf{x}_i and ∑αiyi=0\sum\alpha_iy_i=0: they are 0.50.5 for (2,1)(2,1), 0.3750.375 for (4,0)(4,0) and 0.1250.125 for (4,4)(4,4), all positive, and 00 for the other three. (Check: −0.5(2,1)+0.375(4,0)+0.125(4,4)=(1,0)-0.5(2,1)+0.375(4,0)+0.125(4,4)=(1,0).) The two optimal values agree: 12∥w∥2=0.5\tfrac12\lVert\mathbf{w}\rVert^2=0.5 and ∑αi−12∥w∥2=1−0.5=0.5\sum\alpha_i-\tfrac12\lVert\mathbf{w}\rVert^2=1-0.5=0.5 (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 αi\alpha_i (complementary slackness, P1.F7: a constraint that is not active has multiplier 00). In a rare degenerate case a point can touch the street edge and still have multiplier 00; such a point is not counted, and removing it changes nothing. In the example they are (2,1)(2,1), (4,0)(4,0) and (4,4)(4,4).

The solution is built only from them: w=∑iαiyixi\mathbf{w}=\sum_i\alpha_iy_i\mathbf{x}_i, 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 (5,2)(5,2) to (6,3)(6,3) leaves w=(1,0)\mathbf{w}=(1,0), b=−3b=-3. Deleting it changes nothing either.
  • Moving or deleting a support vector changes the line. Moving (2,1)(2,1) to (1.5,1)(1.5,1) gives w=(0.8,0)\mathbf{w}=(0.8,0), b=−2.2b=-2.2 and width 2.52.5. Deleting (4,0)(4,0) gives w=(0.571,0.286)\mathbf{w}=(0.571,0.286) and a wider street, 3.133.13.

At prediction time too, only the support vectors are needed: f(x)=∑iαiyi xi⋅x+bf(\mathbf{x})=\sum_i\alpha_iy_i\,\mathbf{x}_i\cdot\mathbf{x}+b. This is the form P3.B7 uses: the data enter only through dot products.

Go deeper The dual problem

Give each constraint a multiplier αi≥0\alpha_i\ge0 and form the Lagrangian L=12∥w∥2−∑iαi(yi(w⋅xi+b)−1)\mathcal{L}=\tfrac12\lVert\mathbf{w}\rVert^2-\sum_i\alpha_i\bigl(y_i(\mathbf{w}\cdot\mathbf{x}_i+b)-1\bigr). Setting the derivative with respect to w\mathbf{w} to zero gives w=∑iαiyixi\mathbf{w}=\sum_i\alpha_iy_i\mathbf{x}_i, and with respect to bb gives ∑iαiyi=0\sum_i\alpha_iy_i=0. Substituting back leaves a problem in α\boldsymbol\alpha alone:

max⁡α≥0 ∑iαi−12∑i,jαiαj yiyj xi⋅xjsubject to∑iαiyi=0.\max_{\boldsymbol\alpha\ge0}\ \sum_i\alpha_i-\tfrac12\sum_{i,j}\alpha_i\alpha_j\,y_iy_j\,\mathbf{x}_i\cdot\mathbf{x}_j\quad\text{subject to}\quad\sum_i\alpha_iy_i=0.

The data appear only through the dot products xi⋅xj\mathbf{x}_i\cdot\mathbf{x}_j, which is what lets a kernel replace them (P3.B7). In the soft margin below the only change is the extra bound αi≤C\alpha_i\le C. The conditions on the multipliers are: αi=0\alpha_i=0 means yifi≥1y_if_i\ge1; 0<αi<C0<\alpha_i<C means yifi=1y_if_i=1 (on the street edge); αi=C\alpha_i=C means yifi≤1y_if_i\le1 (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 ii break its constraint by an amount ξi≥0\xi_i\ge0, called its slack:

yi(w⋅xi+b)≥1−ξi.y_i(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1-\xi_i.

A point with ξi=0\xi_i=0 is outside the street or on its edge; 0<ξi≤10<\xi_i\le1 is inside the street but on the right side; ξi>1\xi_i>1 is on the wrong side. Slack is not free: the problem is

min⁡w,b,ξ 12∥w∥2+C∑iξisubject toyi(w⋅xi+b)≥1−ξi,  ξi≥0.\min_{\mathbf{w},b,\boldsymbol\xi}\ \tfrac12\lVert\mathbf{w}\rVert^2+C\sum_i\xi_i\quad\text{subject to}\quad y_i(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1-\xi_i,\ \ \xi_i\ge0.

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 C→∞C\to\infty 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 −1-1 point at (3.5,2)(3.5,2) (the widget’s “One stray point”). The exact solutions:

CCwidthslack above 0misclassified
0.13.9241
0.52.1221
12.0011
50.8010
10 (and any larger)0.5000

At C=1C=1 the line is again w=(1,0)\mathbf{w}=(1,0), b=−3b=-3, the stray point has f=0.5f=0.5, so its slack is ξ=1−(−1)(0.5)=1.5\xi=1-(-1)(0.5)=1.5, and the objective is 12⋅1+1⋅1.5=2\tfrac12\cdot1+1\cdot1.5=2. Above C=10C=10 the stray point is classified correctly and the street is a quarter of the width it had at C=1C=1. 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): CC is a hyperparameter, usually searched on a logarithmic grid.

Points with ξi>0\xi_i>0 are support vectors too: with αi=C\alpha_i=C. The widget counts them in the rings.

Hinge loss and the unconstrained form

For a given (w,b)(\mathbf{w},b) the best slack of a point is the smallest allowed one, ξi=max⁡(0, 1−yif(xi))\xi_i=\max\bigl(0,\,1-y_if(\mathbf{x}_i)\bigr). This function of y fy\,f is the hinge loss:

ℓhinge(y,f)=max⁡(0, 1−y f).\ell_{\text{hinge}}(y,f)=\max(0,\,1-y\,f).

It is 00 once the point is outside the street or on its edge (y f≥1y\,f\ge1), and then grows in a straight line as y fy\,f falls, passing through 11 at y f=0y\,f=0 (on the boundary). Substituting the slack removes the constraints, and dividing the objective by nCnC for nn examples gives

12∥w∥2+C∑iℓhinge⏟soft-margin SVM ⟺ min⁡w,b λ2∥w∥2+1n∑iℓhinge(yi,fi),λ=1nC.\underbrace{\tfrac12\lVert\mathbf{w}\rVert^2+C\sum_i\ell_{\text{hinge}}}_{\text{soft-margin SVM}}\ \Longleftrightarrow\ \min_{\mathbf{w},b}\ \frac\lambda2\lVert\mathbf{w}\rVert^2+\frac1n\sum_i\ell_{\text{hinge}}(y_i,f_i),\qquad\lambda=\frac1{nC}.

The two have the same minimizer, because one objective is the other divided by the positive number nCnC. This is a regularized loss of the kind in P3.A6: the first term is an L2 penalty (with a penalty written λ∥w∥2\lambda\lVert\mathbf{w}\rVert^2 instead, λ=1/(2nC)\lambda=1/(2nC)). Check with the stray-point data at C=1C=1: n=7n=7, λ=1/7\lambda=1/7; the objective 22 divided by nC=7nC=7 is 0.28570.2857, and λ2∥w∥2+mean hinge=114+1.57=0.2857\tfrac\lambda2\lVert\mathbf{w}\rVert^2+\text{mean hinge}=\tfrac1{14}+\tfrac{1.5}{7}=0.2857. So a large CC means a small λ\lambda, a weak penalty and a flexible fit. Remember that CC multiplies the data-fit term, so it goes the opposite way from λ\lambda. The bias bb is not penalized in this form.

Hinge versus logistic loss

Logistic regression (P3.A7) uses ln⁡(1+e−yf)\ln(1+e^{-y f}) on the same score. Both are convex functions of y fy\,f that fall as the score gets more correct; the zero-one loss, which counts a mistake as 11, is not convex.

y fy\,fhingelogistic (ln)
−1-121.3133
010.6931
0.50.50.4741
100.3133
200.1269
300.0486

The difference is in the tail. The hinge loss is exactly zero from y f=1y\,f=1 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, σ(f)=p(y=1∣x)\sigma(f)=p(y=1\mid\mathbf{x}). The SVM score f(x)f(\mathbf{x}) is a signed distance (scaled by ∥w∥\lVert\mathbf{w}\rVert), 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 y f=1y\,f=1, so it has no gradient there, but it has a subgradient: for y f<1y\,f<1 take −y x-y\,\mathbf{x}, otherwise 00. Full-batch subgradient descent on λ2∥w∥2+mean hinge\frac\lambda2\lVert\mathbf{w}\rVert^2+\text{mean hinge} uses the step ηt=1/(λt)\eta_t=1/(\lambda t), capped at 11 (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 w=(1,0)\mathbf{w}=(1,0), b=−3b=-3 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 nn (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 1010 in the stray-point data, with C=1C=1, turns the fit from w=(1,0)\mathbf{w}=(1,0) (four support vectors) into w=(0.065,0)\mathbf{w}=(0.065,0) 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 kk against all others), so KK classifiers, and predicts the class with the highest score. One-vs-one trains one per pair of classes, K(K−1)/2K(K-1)/2 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 xi⋅xj\mathbf{x}_i\cdot\mathbf{x}_j 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 CC 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 f=w⋅x+bf=\mathbf{w}\cdot\mathbf{x}+b, distance ∣f∣/∥w∥\lvert f\rvert/\lVert\mathbf{w}\rVert, canonical scaling min⁡iyifi=1\min_iy_if_i=1, width 2/∥w∥2/\lVert\mathbf{w}\rVert.

Hard margin: min⁡12∥w∥2\min\tfrac12\lVert\mathbf{w}\rVert^2 s.t. yi(w⋅xi+b)≥1y_i(\mathbf{w}\cdot\mathbf{x}_i+b)\ge1. Soft margin: min⁡12∥w∥2+C∑ξi\min\tfrac12\lVert\mathbf{w}\rVert^2+C\sum\xi_i, ξi≥max⁡(0,1−yifi)\xi_i\ge\max(0,1-y_if_i).

Dual: max⁡∑αi−12∑αiαjyiyjxi⋅xj\max\sum\alpha_i-\tfrac12\sum\alpha_i\alpha_jy_iy_j\mathbf{x}_i\cdot\mathbf{x}_j s.t. 0≤αi≤C0\le\alpha_i\le C, ∑αiyi=0\sum\alpha_iy_i=0; w=∑αiyixi\mathbf{w}=\sum\alpha_iy_i\mathbf{x}_i.

Regularized form: λ2∥w∥2+1n∑max⁡(0,1−yifi)\frac\lambda2\lVert\mathbf{w}\rVert^2+\frac1n\sum\max(0,1-y_if_i) with λ=1/(nC)\lambda=1/(nC); subgradient of the hinge: −yx-y\mathbf{x} if yf<1yf<1, else 00.

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.0

SVC solves the dual problem with LIBSVM and stores αiyi\alpha_iy_i in dual_coef_. LinearSVC is a different solver (LIBLINEAR): its default loss is the squared hinge max⁡(0,1−yf)2\max(0,1-yf)^2, and it also penalizes the bias, so on the stray-point data with C=1C=1 the call LinearSVC(loss="hinge") gave w=(0.5,−0.167)\mathbf{w}=(0.5,-0.167), b=−1b=-1, while SVC gave w=(1,0)\mathbf{w}=(1,0), b=−3b=-3. 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.

Try it: solve the hard margin by trying touching sets

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try it: train a linear SVM by subgradient descent

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Try changing CC to 55 in the second cell. The exact answer is then w=(2.5,0)\mathbf{w}=(2.5,0), b=−9b=-9, but with this step rule descent has not arrived after 20 00020\,000 steps, because a larger CC means a smaller λ\lambda and a slower step schedule. Quadratic-programming solvers do not have that problem.

Exercises

  1. For w=(3,4)\mathbf{w}=(3,4), b=−5b=-5, find the distance from the point (3,2)(3,2) to the line w⋅x+b=0\mathbf{w}\cdot\mathbf{x}+b=0, and the street width if the closest points satisfy y f=±1y\,f=\pm1.
    Show answerf=3⋅3+4⋅2−5=12f=3\cdot3+4\cdot2-5=12 and ∥w∥=5\lVert\mathbf{w}\rVert=5, so the distance is 12/5=2.412/5=2.4. The width is 2/5=0.42/5=0.4.
  2. A student reports w=(2,0)\mathbf{w}=(2,0), b=−6b=-6 for the six-point example. Is it the same line as the SVM answer? Is it the SVM solution of the optimization problem?
    Show answerIt is the same line (x1=3x_1=3), but (2,0,−6)(2,0,-6) gives y f=2y\,f=2 at the closest points, so the constraints are not tight and 12∥w∥2=2\tfrac12\lVert\mathbf{w}\rVert^2=2 is bigger than 0.50.5. The minimizer is (1,0,−3)(1,0,-3).
  3. Solve the hard-margin problem for the two points x=1x=1 (class −1-1) and x=3x=3 (class +1+1) in one dimension: ww, bb, width and the multipliers.
    Show answerBoth constraints are active: w+b=−1w+b=-1 and 3w+b=13w+b=1, so w=1w=1, b=−2b=-2, width 22. From w=∑αiyixiw=\sum\alpha_iy_ix_i with α1=α2=α\alpha_1=\alpha_2=\alpha: 3α−α=13\alpha-\alpha=1, so α=12\alpha=\tfrac12 for both, and ∑αiyi=0\sum\alpha_iy_i=0.
  4. A point has y f=0.3y\,f=0.3. Give its hinge loss and its logistic loss (natural log).
    Show answerHinge 1−0.3=0.71-0.3=0.7; logistic ln⁡(1+e−0.3)=0.5544\ln(1+e^{-0.3})=0.5544.
  5. A data set has n=200n=200 examples. A soft-margin SVM with C=0.5C=0.5 is rewritten as λ2∥w∥2+mean hinge\frac\lambda2\lVert\mathbf{w}\rVert^2+\text{mean hinge}. Find λ\lambda, and say what happens to λ\lambda if CC is increased.
    Show answerλ=1/(nC)=1/100=0.01\lambda=1/(nC)=1/100=0.01. A larger CC gives a smaller λ\lambda: weaker regularization.
  6. How many binary classifiers do one-vs-rest and one-vs-one train for 5 classes?
    Show answerOne-vs-rest: 55. One-vs-one: 5⋅4/2=105\cdot4/2=10.
  7. In the six-point example, which deletion changes the hard-margin line: (0,0)(0,0) or (4,0)(4,0)? What is the width after the change?
    Show answerDeleting the non-support point (0,0)(0,0) changes nothing. Deleting the support vector (4,0)(4,0) changes the line to w=(0.571,0.286)\mathbf{w}=(0.571,0.286), b=−2.43b=-2.43, and the width becomes 3.133.13.

Check your understanding

  1. In the hard-margin SVM with the closest points at y f=1y\,f=1, what is the width of the street, and what do we do to widen it?

  2. In a trained hard-margin SVM you delete one training point. When is the line certain to stay exactly the same?

  3. 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?

  4. A point has y f=2.5y\,f=2.5. What are its hinge loss and its logistic loss ln⁡(1+e−yf)\ln(1+e^{-y f})?

  5. You need the probability that a new email is spam from an SVM. What is the sound approach?

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.

Key takeaways

  • Many lines separate two classes. The SVM picks the one with the widest street. The signed distance from x to the line w·x + b = 0 is (w·x + b)/‖w‖.
  • The pair (w, b) can be scaled without moving the line, so fix the closest points at w·x + b = ±1. Then the street has width 2/‖w‖, and maximizing it means minimizing ½‖w‖² subject to yᵢ(w·xᵢ + b) ≥ 1. This is a convex quadratic problem with one answer.
  • Support vectors are the training points that touch the street: their constraints are active and their multipliers are positive. Moving or deleting any other point leaves the solution unchanged. For the six-point example the answer is w = (1, 0), b = −3, width 2, with three support vectors and multipliers 0.5, 0.375, 0.125.
  • The soft margin adds slack ξᵢ = max(0, 1 − yᵢ(w·xᵢ + b)) and minimizes ½‖w‖² + C Σ ξᵢ. A large C allows few violations and a narrow street; a small C allows more violations and a wider street. With n examples it is the same as minimizing (λ/2)‖w‖² + the mean hinge loss with λ = 1/(nC).
  • The hinge loss max(0, 1 − y f) is exactly zero beyond the margin, so well-classified points stop mattering and the solution is sparse in the points. The logistic loss is never exactly zero and gives probabilities; the SVM score is not a probability. Scale the features first, and use one-vs-rest or one-vs-one for more than two classes.
Found a mistake? Tell us