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
Build the widest street you can
- Your line
- Edges of your street
- Separates the two kinds?
- yes
- Width of your street
- 0.20
- Widest possible
- ?
The widest street here is 1.48 units across. Finding it is exactly what a
The same idea as an optimisation problem
Write the boundary as and label the classes and . Scale and so that the nearest points on each side satisfy . The street is then wide, so making it wide means making small:
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 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
Only the edge points count
- One kind
- The other kind
- Boundary and street edges
- Ringed: support vector
- Points
- 14
- Support vectors
- 3
- Street width
- 2.59
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.
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 fixes the price. This is the
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.
Take the boundary , . The length of is , so the street is wide. Three points belong to the class labelled .
- (4, 2): . Well above 1, so it is far outside the street. No intrusion.
- (2, 1.75): . Exactly on the edge of the street. No intrusion. This point is a support vector.
- (2, 1.6): . On the correct side of the boundary, but inside the street. It intrudes by .
The quantity being minimised is . With a large , that 0.6 is expensive, and the optimiser will turn or narrow the street to remove it. With a small , it will leave the point where it is and keep the street wide.
How much to mind the awkward points
- 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
At the street is 0.25 wide with only 2 points inside it. At 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
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 . 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
The most widely used is the
The setting 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.
A boundary that closes into a loop
- Shaded: would be called filled
- Ringed: support vector
- Boundary
- straight line
- Points classified correctly
- 73%
- Support vectors
- 64 of 70
The straight boundary gets 73% right. With an RBF kernel at a moderate , it gets everything right, using fewer than a third of the points as support vectors.
The two extremes of are both bad, in the familiar way. With very small, every point is “similar” to every other and the boundary is nearly straight again: underfitting. With 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.
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.
- 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.
A boundary has and . How wide is its street? For each of the points (4, 3), (2, 2.5) and (1, 1), work out the score and say where the point lies.
Hint
The street is wide. A score beyond 1 or −1 is outside the street.
Solution
The length of is , so the street is wide.
- (4, 3): . Positive side, and outside the street, because the score is above 1.
- (2, 2.5): . Negative side, but inside the street, because the score is between −1 and 1.
- (1, 1): . 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.
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.
The RBF kernel scores the similarity of two points as , where is the distance between them. Work it out for points 1 apart and 2 apart, first with and then with . What does γ control?
Hint
Square the distance, multiply by γ, and take to the power of minus that.
Solution
With : at distance 1, . At distance 2, .
With : at distance 1, . At distance 2, .
γ 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.
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.
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 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.