Chapter 10 // Classification

Support Vector Machines.

When many lines separate two groups perfectly, which one should you pick?

Reading time
17 min
Data

Logistic regression draws a straight boundary and is content with any line that fits the training data well. This chapter asks a sharper question: among all the lines that work, is one of them best? The answer leads to a classifier built on geometry instead of probability, and to a trick that lets straight-line methods draw curves.

The widest street

Here are two groups of points with a clear gap between them. Plenty of lines separate them without a single mistake. They are not equally good.

A line that passes very close to some of the points is fragile. A new point only slightly different from those would land on the wrong side. A line that stays far from both groups has room to spare.

Picture the boundary as the centre line of a street, and widen the street until it touches the nearest point on either side. The width of that empty street is the . The safest boundary is the one with the widest street.

Figure

Build the widest street you can

Filled kind at (5.54, 7.78)Filled kind at (6.95, 6.37)Filled kind at (6.48, 6.61)Filled kind at (7.38, 5.68)Filled kind at (5.72, 5.35)Filled kind at (6.91, 6.75)Filled kind at (6.78, 7.02)Filled kind at (6.31, 6.17)Filled kind at (6.91, 5.9)Filled kind at (6.44, 6.43)Filled kind at (6.38, 7.51)Filled kind at (6.86, 6.08)Hollow kind at (3.28, 4.54)Hollow kind at (3.18, 3.29)Hollow kind at (2.59, 4.04)Hollow kind at (3.41, 3.21)Hollow kind at (3.78, 3.27)Hollow kind at (2.47, 4.76)Hollow kind at (2.83, 3.75)Hollow kind at (2.9, 3.57)Hollow kind at (3.53, 3.77)Hollow kind at (3.3, 3.35)Hollow kind at (4.54, 4.45)Hollow kind at (4.83, 4.01)
  • Your line
  • Edges of your street
Separates the two kinds?
yes
Width of your street
0.20
Widest possible
?
Drag the two orange handles.
The solid line is your boundary. The dashed lines are the edges of the widest empty street centred on it. Try it: drag the two handles to make your street as wide as possible. Then reveal the best possible street and compare.

The widest street here is 1.48 units across. Finding it is exactly what a does: it is the classifier that maximises the margin.

The same idea as an optimisation problem

Write the boundary as w⋅x+b=0w \cdot x + b = 0 and label the classes y=+1y = +1 and y=−1y = -1. Scale ww and bb so that the nearest points on each side satisfy w⋅x+b=±1w \cdot x + b = \pm 1. The street is then 2/∥w∥2 / \lVert w \rVert wide, so making it wide means making ww small:

minimise 12∥w∥2subject toyi (w⋅xi+b)≥1  for every point i\text{minimise } \tfrac{1}{2}\lVert w \rVert^2 \quad \text{subject to} \quad y_i\,(w \cdot x_i + b) \ge 1 \ \text{ for every point } i

The condition says every point must be on its correct side and outside the street. Notice that the thing being minimised is the ridge penalty from . An SVM is, in a sense, all regularization: the smallest weights that still classify everything correctly.

The points that matter

Look again at the widest street. It is pinned in place by the few points it touches. Everything else is further back and plays no part.

The points on the edge of the street are called , and they give the method its name.

Figure

Only the edge points count

4.36, 4.375.02, 7.356.21, 6.18
  • One kind
  • The other kind
  • Boundary and street edges
  • Ringed: support vector
Points
14
Support vectors
3
Street width
2.59
Drag any point. Try one far from the street, then a ringed one.
Every point can be dragged. Ringed points are the support vectors, the ones the street is resting on. Try it: drag a point that is far from the street and watch nothing change. Then drag a ringed point and watch the whole street swing.

This is very different from the models before it. In logistic regression every example pulls on the weights, however far it is from the boundary. Here you could delete every point except the support vectors and get exactly the same classifier. The easy cases, deep inside their own territory, tell the model nothing it needs.

Checkpoint

An SVM is trained on 10,000 points and ends with 40 support vectors. You add 500 new points, all far from the boundary and on the correct side. What happens to the boundary?

When no line is clean

Real groups overlap. There is then no line with an empty street on either side, and the problem as stated has no solution. Even when a clean line exists, a single stray point can force the street to be very narrow.

The fix is to let points enter the street, or cross it, at a price. Each violation is charged in proportion to how far it intrudes, and a setting called CC fixes the price. This is the .

minimise 12∥w∥2+C∑imax⁡ ⁣(0,  1−yi (w⋅xi+b))\text{minimise } \tfrac{1}{2}\lVert w \rVert^2 + C \sum_i \max\!\big(0,\; 1 - y_i\,(w \cdot x_i + b)\big)

minimise: (how small the weights are) + C × (total amount by which points intrude)

  • Large C makes violations expensive. The street narrows to avoid them, and the boundary bends to the awkward points.
  • Small C makes them cheap. The street widens, more points end up inside it, and the boundary reflects the overall trend.
ExampleAdding up the intrusions

Take the boundary w=[3, 4]w = [3,\ 4], b=−12b = -12. The length of ww is 32+42=5\sqrt{3^2 + 4^2} = 5, so the street is 2/5=0.42 / 5 = 0.4 wide. Three points belong to the class labelled +1+1.

  • (4, 2): 3×4+4×2−12=83 \times 4 + 4 \times 2 - 12 = 8. Well above 1, so it is far outside the street. No intrusion.
  • (2, 1.75): 6+7−12=16 + 7 - 12 = 1. Exactly on the edge of the street. No intrusion. This point is a support vector.
  • (2, 1.6): 6+6.4−12=0.46 + 6.4 - 12 = 0.4. On the correct side of the boundary, but inside the street. It intrudes by 1−0.4=0.61 - 0.4 = 0.6.

The quantity being minimised is 12×25+C×0.6\tfrac{1}{2} \times 25 + C \times 0.6. With a large CC, that 0.6 is expensive, and the optimiser will turn or narrow the street to remove it. With a small CC, it will leave the point where it is and keep the street wide.

Figure

How much to mind the awkward points

6.82, 4.745.38, 4.987.36, 4.385.61, 3.593.08, 5.973.18, 4.355.24, 4.955.1, 5.074.11, 4.75Filled kind at (8.07, 5.94)Filled kind at (5.78, 9.29)Filled kind at (6.82, 4.74)Filled kind at (5.38, 4.98)Filled kind at (8.51, 6.43)Filled kind at (7.62, 8.17)Filled kind at (7.15, 7.17)Filled kind at (6.62, 8.86)Filled kind at (9.19, 6.59)Filled kind at (3.97, 6.4)Filled kind at (3.08, 5.97)Filled kind at (7.27, 7.89)Filled kind at (7.94, 5.63)Filled kind at (5.1, 5.07)Filled kind at (5.66, 5.51)Filled kind at (8.53, 6.54)Filled kind at (6.48, 5.02)Filled kind at (8.44, 8.37)Filled kind at (6.02, 7.67)Filled kind at (8.23, 5.22)Filled kind at (5.07, 6.66)Filled kind at (6.17, 6.03)Hollow kind at (1.5, 1.78)Hollow kind at (3.73, 2.08)Hollow kind at (0.81, 4.52)Hollow kind at (1.77, 4.42)Hollow kind at (2.59, 2.28)Hollow kind at (4.96, 3.77)Hollow kind at (2.86, 4.07)Hollow kind at (7.36, 4.38)Hollow kind at (5.61, 3.59)Hollow kind at (3.23, 2.76)Hollow kind at (4.54, 2.27)Hollow kind at (3.18, 4.35)Hollow kind at (5.24, 4.95)Hollow kind at (0.89, 3.74)Hollow kind at (4.07, 2.59)Hollow kind at (4.11, 4.75)Hollow kind at (4.69, 2.58)Hollow kind at (1.79, 3.92)Hollow kind at (3.16, 2.92)Hollow kind at (2.2, 2.15)Hollow kind at (2.64, 3.97)Hollow kind at (3.57, 3.37)
  • Boundary and street edges
  • Ringed: support vector
Cost of a violation (C)
1
Street width
1.52
Points inside the street
6
On the wrong side
2
1
The two groups overlap, so some points must end up inside the street or on the wrong side. Try it: slide C from 100 down to 0.001. Watch the street widen and the number of ringed points grow.

At C=100C = 100 the street is 0.25 wide with only 2 points inside it. At C=0.01C = 0.01 it is 5.75 wide and holds 26 of the 44 points. Every point inside the street or on its edge is now a support vector.

This is the same trade as the penalty strength in , turned upside down: a small CC means strong regularization. Like every hyperparameter, it is chosen by cross-validation.

Bending the boundary

So far the boundary has been straight. Some data cannot be separated by any straight line however soft the margin: here, one group sits inside a ring of the other.

The standard answer in Part I was to add features, such as x2x^2. SVMs have a neater route. Their training turns out to need only one thing from the data: for each pair of points, a number saying how similar they are. For a straight boundary that number is the dot product. Replace it with a different measure of similarity, called a , and the same algorithm draws a curved boundary without ever computing new features.

The most widely used is the . It calls two points similar when they are close together:

K(a,b)=exp⁡ ⁣(−γ ∥a−b∥2)K(a, b) = \exp\!\big(-\gamma\,\lVert a - b \rVert^2\big)

The setting γ\gamma controls how fast similarity fades with distance. The resulting classifier behaves a little like a smooth version of nearest neighbours, in which only the support vectors get a vote.

Figure

A boundary that closes into a loop

2.88, 1.525.43, 5.29.73, 4.110.51, 6.374.01, 5.128.77, 4.716.11, 4.63.78, 1.366.26, 4.545.8, 7.795.66, 3.822.26, 3.535.72, 4.294.53, 8.265.36, 6.243.23, 2.294.84, 5.614.71, 8.360.56, 4.994.68, 5.053.68, 2.75.93, 4.541.53, 2.95.93, 4.32.42, 6.395.51, 6.38.07, 7.274.89, 3.943.92, 4.826.57, 7.553.72, 5.815.23, 5.083.87, 5.891.98, 7.564.53, 3.847.53, 6.493.89, 4.298.43, 4.174.14, 4.414.73, 8.524.87, 4.374.96, 8.785.98, 6.018.14, 4.143.71, 7.824.88, 5.622.49, 3.386.04, 4.968.54, 5.784.49, 4.388.18, 2.622.9, 5.992.57, 2.163.91, 5.451.9, 6.583.91, 4.837.87, 2.895.06, 5.011.85, 2.443.81, 5.596.4, 1.983.87, 4.867.42, 3.455.53, 6.13Filled kind at (5.43, 5.2)Filled kind at (3.61, 6.26)Filled kind at (4.01, 5.12)Filled kind at (6.11, 4.6)Filled kind at (6.26, 4.54)Filled kind at (5.66, 3.82)Filled kind at (5.72, 4.29)Filled kind at (5.36, 6.24)Filled kind at (4.84, 5.61)Filled kind at (3.91, 6.3)Filled kind at (4.68, 5.05)Filled kind at (5.93, 4.54)Filled kind at (5.93, 4.3)Filled kind at (5.51, 6.3)Filled kind at (4.89, 3.94)Filled kind at (3.92, 4.82)Filled kind at (3.72, 5.81)Filled kind at (5.23, 5.08)Filled kind at (3.87, 5.89)Filled kind at (4.53, 3.84)Filled kind at (3.89, 4.29)Filled kind at (4.14, 4.41)Filled kind at (4.87, 4.37)Filled kind at (5.98, 6.01)Filled kind at (3.96, 6.71)Filled kind at (4.88, 5.62)Filled kind at (6.04, 4.96)Filled kind at (4.49, 4.38)Filled kind at (2.9, 5.99)Filled kind at (3.91, 5.45)Filled kind at (3.91, 4.83)Filled kind at (5.06, 5.01)Filled kind at (3.81, 5.59)Filled kind at (3.87, 4.86)Filled kind at (5.53, 6.13)Hollow kind at (2.88, 1.52)Hollow kind at (9.73, 4.11)Hollow kind at (0.51, 6.37)Hollow kind at (8.77, 4.71)Hollow kind at (3.78, 1.36)Hollow kind at (5.8, 7.79)Hollow kind at (2.26, 3.53)Hollow kind at (4.53, 8.26)Hollow kind at (3.23, 2.29)Hollow kind at (4.71, 8.36)Hollow kind at (0.56, 4.99)Hollow kind at (3.68, 2.7)Hollow kind at (1.53, 2.9)Hollow kind at (2.42, 6.39)Hollow kind at (8.07, 7.27)Hollow kind at (5.54, 1.08)Hollow kind at (6.57, 7.55)Hollow kind at (4.54, 1.47)Hollow kind at (6.53, 1.93)Hollow kind at (1.98, 7.56)Hollow kind at (7.53, 6.49)Hollow kind at (8.43, 4.17)Hollow kind at (4.73, 8.52)Hollow kind at (4.96, 8.78)Hollow kind at (8.14, 4.14)Hollow kind at (3.71, 7.82)Hollow kind at (2.49, 3.38)Hollow kind at (8.54, 5.78)Hollow kind at (8.18, 2.62)Hollow kind at (2.57, 2.16)Hollow kind at (1.9, 6.58)Hollow kind at (7.87, 2.89)Hollow kind at (1.85, 2.44)Hollow kind at (6.4, 1.98)Hollow kind at (7.42, 3.45)
  • Shaded: would be called filled
  • Ringed: support vector
Boundary
straight line
Points classified correctly
73%
Support vectors
64 of 70
0.32
Shaded areas would be classified as the filled kind. Try it: with the straight boundary, read the accuracy. Switch to RBF, then move γ to its smallest and largest values and count the support vectors.

The straight boundary gets 73% right. With an RBF kernel at a moderate γ\gamma, it gets everything right, using fewer than a third of the points as support vectors.

The two extremes of γ\gamma are both bad, in the familiar way. With γ\gamma very small, every point is “similar” to every other and the boundary is nearly straight again: underfitting. With γ\gamma very large, each point is similar only to itself, almost every point becomes a support vector, and the model has memorised the training set: overfitting.

Checkpoint

An RBF-kernel SVM scores 100% on training data and 71% on new data. Which change is most likely to help?

In code

from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC

# SVMs measure distances, so scale the features first.
model = make_pipeline(StandardScaler(), SVC(kernel="rbf"))

# C and gamma are tuned together, each over several powers of ten.
grid = {"svc__C": [0.1, 1, 10, 100], "svc__gamma": [0.01, 0.1, 1, 10]}
search = GridSearchCV(model, grid, cv=5).fit(X_train, y_train)

print(search.best_params_)
print(search.score(X_test, y_test))
print(search.best_estimator_[-1].n_support_)    # support vectors per class

Use SVC(kernel="linear") or the faster LinearSVC for a straight boundary. Because SVMs depend on distances, the scaling step matters as much here as it did for nearest neighbours.

Key Takeaways

  • Of all the boundaries that separate two classes, an SVM picks the one with the widest margin.
  • The boundary is fixed by the support vectors, the few points on the edge of the margin. The rest could be deleted.
  • A soft margin lets points cross, at a price set by C. Small C means a wider, more tolerant street.
  • A kernel replaces the dot product with another measure of similarity, giving curved boundaries from the same algorithm.
  • C and γ control flexibility, and are tuned together by cross-validation.
You can now
  • Explain why the widest margin is a sensible choice of boundary.
  • Tell which points are support vectors and what would happen if the others were removed.
  • Say what C trades off, and what small and large values do.
  • Describe what a kernel changes and how γ affects the boundary.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

A boundary has w=[1, 1]w = [1,\ 1] and b=−5b = -5. How wide is its street? For each of the points (4, 3), (2, 2.5) and (1, 1), work out the score w⋅x+bw \cdot x + b and say where the point lies.

Hint

The street is 2/∥w∥2 / \lVert w \rVert wide. A score beyond 1 or −1 is outside the street.

Solution

The length of ww is 2\sqrt{2}, so the street is 2/2≈1.412 / \sqrt{2} \approx 1.41 wide.

  • (4, 3): 4+3−5=24 + 3 - 5 = 2. Positive side, and outside the street, because the score is above 1.
  • (2, 2.5): 2+2.5−5=−0.52 + 2.5 - 5 = -0.5. Negative side, but inside the street, because the score is between −1 and 1.
  • (1, 1): 1+1−5=−31 + 1 - 5 = -3. Negative side, far outside the street.

The sign of the score gives the class. Whether its size is above 1 says whether the point is clear of the street.

Exercisethink

An SVM is trained on 100 points that a line separates cleanly, and 4 of them turn out to be support vectors. How many points could you delete without changing the boundary at all? What happens if you delete one of the 4?

Hint

Only the points on the edge of the street hold the boundary in place.

Solution

All 96 points that are not support vectors could be deleted and the boundary would stay exactly where it is. They sit behind the edges of the street and play no part in fixing it.

Delete a support vector and the street is no longer held on that side. It can usually widen or swing until it touches another point, which becomes a new support vector, and the boundary moves.

This is very different from logistic regression, where every point contributes to the loss and removing any of them shifts the fit a little.

Exerciseby hand

The RBF kernel scores the similarity of two points as e−γd2e^{-\gamma d^2}, where dd is the distance between them. Work it out for points 1 apart and 2 apart, first with γ=1\gamma = 1 and then with γ=0.1\gamma = 0.1. What does γ control?

Hint

Square the distance, multiply by γ, and take ee to the power of minus that.

Solution

With γ=1\gamma = 1: at distance 1, e−1≈0.37e^{-1} \approx 0.37. At distance 2, e−4≈0.02e^{-4} \approx 0.02.

With γ=0.1\gamma = 0.1: at distance 1, e−0.1≈0.90e^{-0.1} \approx 0.90. At distance 2, e−0.4≈0.67e^{-0.4} \approx 0.67.

γ sets how quickly similarity fades with distance. With a large γ, a point 2 units away is already treated as unrelated, so each training point influences only its immediate surroundings and the boundary can wrap tightly around individual points. With a small γ, influence reaches far, and the boundary is smooth.

Exercisethink

You train an SVM with a very small C and another with a very large C on noisy data. Which is more likely to underfit, and which to overfit? How does C relate to the λ of ridge regression?

Hint

C is the price of a point intruding into the street. Ask what a very cheap or very expensive intrusion leads to.

Solution

Very small C makes intrusions cheap. The optimiser cares mostly about a wide street and tolerates many points inside it, or on the wrong side. Taken too far, the boundary ignores real structure: underfitting.

Very large C makes every intrusion expensive. The street narrows and the boundary bends to get each awkward point right, including the noisy ones: overfitting.

C plays the role of one over λ. In ridge regression λ multiplies the penalty on the weights, so a large λ means strong regularization. In an SVM, C multiplies the error term instead, so a large C means weak regularization.

Exercisewith the figure

In the figure “How much to mind the awkward points”, read the width of the street and the number of points inside it at C = 100 and at C = 0.01. Which setting would you expect to do better on new data if the awkward points are noise?

Hint

A point inside the street is one the optimiser decided was not worth bending the boundary for.

Solution

At C = 100 the street is 0.25 wide with 2 points inside it. At C = 0.01 it is 5.75 wide and holds 26 of the 44 points.

If the awkward points are noise, the large C has bent the boundary to accommodate them, and it will carry that distortion to new data. The small C follows the overall trend and ignores them, so it should generalise better. If those points were real structure, the opposite would hold. Cross-validation decides which it is.

Going further

The hinge loss

The term max⁡(0, 1−y (w⋅x+b))\max(0,\, 1 - y\,(w \cdot x + b)) is called the hinge loss. It is zero for points safely outside the street and grows in a straight line as a point intrudes. Compare it with the log loss of logistic regression, which is never quite zero: that difference is why logistic regression listens to every point and an SVM only to the support vectors.

Why kernels work

A kernel is secretly a dot product in a larger space of features. The RBF kernel corresponds to infinitely many features, which could never be computed one by one. Because the SVM only ever asks for dot products between pairs of points, it never needs the features themselves. This is known as the kernel trick.

Where SVMs stand today

Before deep learning, kernel SVMs were the strongest general-purpose classifiers. They are still excellent on small and medium datasets with a few thousand examples. On very large datasets they are slow to train, because the work grows with the square of the number of examples.

References and further reading

  • G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, chapter 9. Free at statlearning.com.
  • T. Ma and A. Ng, CS229 Lecture Notes, chapters 5 and 6 (kernel methods and support vector machines), cs229.stanford.edu.
  • scikit-learn user guide, Support Vector Machines.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 10.1The widest street
  3. 10.2The points that matter
  4. 10.3When no line is clean
  5. 10.4Bending the boundary
  6. 10.5In code
  7. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in