# Chapter 10: Support Vector Machines

> Separating classes with the widest possible margin. Opening question: When many lines separate two groups perfectly, which one should you pick?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/support-vector-machines/

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 margin. The safest boundary is the one with the widest street.

> **Interactive figure: Build the widest street you can.** 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.
> (Use it at https://thebookofml.com/support-vector-machines/)

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

**Derivation: The same idea as an optimisation problem**

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

$$
\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 [the regularization chapter](https://thebookofml.com/regularization/). 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 support vectors, and they give the method its name.

> **Interactive figure: Only the edge points count.** 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.
> (Use it at https://thebookofml.com/support-vector-machines/)

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.

**Check your understanding:** 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?

- It shifts toward the new points — Points well outside the street do not touch it and so cannot move it.
- Nothing: it stays exactly where it was **(correct)** — Only points on or inside the margin determine the boundary. Correctly classified points far from it are ignored.
- The margin narrows because there is more data — The margin is set by the closest points. The new ones are not close.

## 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 $C$ fixes the price. This is the soft margin.

$$
\text{minimise } \tfrac{1}{2}\lVert w \rVert^2 + C \sum_i \max\!\big(0,\; 1 - y_i\,(w \cdot x_i + b)\big)
$$

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

**Example: Adding up the intrusions**

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

- **(4, 2):** $3 \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 = 1$. Exactly on the edge of the street. No intrusion. This point is a support vector.
- **(2, 1.6):** $6 + 6.4 - 12 = 0.4$. On the correct side of the boundary, but inside the street. It intrudes by $1 - 0.4 = 0.6$.

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

> **Interactive figure: How much to mind the awkward points.** 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.
> (Use it at https://thebookofml.com/support-vector-machines/)

At $C = 100$ the street is 0.25 wide with only 2 points inside it. At $C = 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 [the regularization chapter](https://thebookofml.com/regularization/), turned upside down: a *small* $C$ 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 $x^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 kernel, and the same algorithm draws a curved boundary without ever computing new features.

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

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

> **Interactive figure: A boundary that closes into a loop.** 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.
> (Use it at https://thebookofml.com/support-vector-machines/)

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.

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

- Increase γ — A larger γ makes the boundary wrap even more tightly around individual training points, which is more overfitting.
- Decrease γ or decrease C **(correct)** — Both make the model smoother: a smaller γ widens each point's influence, and a smaller C tolerates more violations. Either reduces overfitting.
- Switch to a linear kernel regardless of the data — That might help or might underfit badly. Tuning γ and C by cross-validation is the direct fix.

**Common mistake: Reading the score as a probability**

An SVM's output, $w \cdot x + b$, says which side of the boundary a point is on and roughly how far from it. It is not a probability. A score of 2 does not mean "twice as sure" as a score of 1, and nothing limits it to the range 0 to 1. If you need probabilities, for ranking by risk or for choosing a threshold by cost, either use a model that produces them, such as logistic regression, or fit a separate step that converts scores into probabilities.

## In code

```python
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.

## What you should now be able to do

- 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

### Exercise (by hand)

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

**Hint:**

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

**Solution:**

The length of $w$ is $\sqrt{2}$, so the street is $2 / \sqrt{2} \approx 1.41$ wide.

- **(4, 3):** $4 + 3 - 5 = 2$. Positive side, and outside the street, because the score is above 1.
- **(2, 2.5):** $2 + 2.5 - 5 = -0.5$. Negative side, but inside the street, because the score is between −1 and 1.
- **(1, 1):** $1 + 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.

### Exercise (think)

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.

### Exercise (by hand)

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

**Hint:**

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

**Solution:**

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

With $\gamma = 0.1$: at distance 1, $e^{-0.1} \approx 0.90$. At distance 2, $e^{-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.

### Exercise (think)

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.

### Exercise (with 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 \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

- G. James, D. Witten, T. Hastie and R. Tibshirani, *An Introduction to Statistical Learning*, chapter 9. Free at [statlearning.com](https://www.statlearning.com).
- T. Ma and A. Ng, *CS229 Lecture Notes*, chapters 5 and 6 (kernel methods and support vector machines), [cs229.stanford.edu](https://cs229.stanford.edu/main_notes.pdf).
- scikit-learn user guide, [Support Vector Machines](https://scikit-learn.org/stable/modules/svm.html).

## Next

That completes the classifiers of Part II. From here the book goes two ways. Part III, which is still being written, builds models out of simple yes-or-no questions and has hundreds of them vote. Part IV, ready now, starts from a single artificial neuron and builds up to a network that recognises pictures.
