MLDay 16 of 50Supervised and Unsupervised Learning
Support Vector Machines
Ten students, two numbers each: hours studied and hours slept.
Ten students, two numbers each: hours studied and hours slept. Many straight lines split those who passed from those who failed. A line that skims past one student will misjudge the next student who looks a bit like them. You want the line that keeps the most room on both sides.
The idea
A support vector machine (SVM) is a classifier that draws the boundary with the widest margin. Picture a street between the two classes. The boundary runs down the middle, and the street's edges touch the nearest points on each side. The SVM picks the line whose street is widest.
Only the points on the street's edges, or inside the street, decide where it goes. They are the support vectors. Move any other point a little, and the line stays put.
Real classes overlap, so a perfect street rarely exists. The soft margin lets some points sit inside the
street, or on the wrong side, for a price. The price is the hinge loss: 0 for a point safely outside the
street, rising the deeper the point goes in. The knob C sets how much each violation costs. A big C buys
fewer violations with a narrower street. A small C accepts more of them to get a wider street. It is
regularization, as in D11, turned around: a smaller C holds
the weights back harder.
Some classes can't be split by any straight line. A kernel lets the SVM compare two points with a similarity score instead of the plain weighted sum . The RBF kernel (radial basis function) scores two points near 1 when they're close and near 0 when they're far apart. The boundary then bends around groups of support vectors, much like the "who is near?" idea of D15. Because "close" is measured in raw units, the features must be on the same scale (D09).
A tiny example
Take the score . The boundary is where , and the street's edges are where and . A point is on the right side, outside the street, when , where the label is +1 or −1. Its hinge loss is , or 0 when that is negative.
| Point | Label | Hinge loss | Where | |||
|---|---|---|---|---|---|---|
| A | (1, 1) | +1 | 3 + 4 − 5 = 2 | 2 | 0 | outside the street |
| B | (1, 0.75) | +1 | 3 + 3 − 5 = 1 | 1 | 0 | on the +1 edge |
| C | (0, 1) | −1 | 0 + 4 − 5 = −1 | 1 | 0 | on the −1 edge |
| D | (1.1, 0.5) | +1 | 3.3 + 2 − 5 = 0.3 | 0.3 | 0.7 | inside the street |
| E | (0.5, 0.5) | +1 | 1.5 + 2 − 5 = −1.5 | −1.5 | 2.5 | wrong side |
A costs nothing and has no say in the line. B, C, D and E are the support vectors. A point on the wrong side always costs more than 1.
The formula
The margin is the street's full width.
| Symbol | Meaning |
|---|---|
| the weights, one per feature: above | |
| the length of : |
Worked: , so the margin is . Smaller weights mean a wider street.
The hinge loss charges each point for entering the street.
| Symbol | Meaning |
|---|---|
| the true label, +1 or −1 | |
| the score ; its sign is the predicted class | |
| the loss for one point: 0 outside the street |
Worked, point D: and give .
Training makes as small as it can: a wide street, plus
C times the total hinge loss. Unlike log loss in D12,
the hinge loss hits exactly 0, so points far from the line drop out of the sum.
Try it
Widen the street between pass and fail
Turn and slide the line so it splits blue (+1) from yellow (−1) with the widest empty street between them.
margin width 2/‖w‖ 0.2support vectors 1total hinge loss 0right side 10 of 10
The margin's edges (dashed) sit at the closest correctly classified point. Ringed points are on or inside the margin, or on the wrong side: the support vectors. Hinge loss is max(0, 1 − y·f(x)), 0 for every point outside the street.
Blue points passed (+1) and yellow points failed (−1). The vertical line splits them all, but its margin is only 0.2. Turn the angle and slide the offset to widen the street; the best is 2.83, at 135° with offset 0. Then slide the offset past a point: the street can get wider, but the hinge loss rises above 0.
In code
SVC(kernel="linear") fits a straight-line SVM and keeps its support vectors. Both features are in hours, so
no scaling is needed here.
# script_id: day_016_support_vector_machines/linear
import numpy as np
from sklearn.svm import SVC
# hours studied, hours slept; +1 = passed, -1 = failed (the playground's points)
X = np.array([[1, 4], [2, 2], [4, 1], [3, 5], [5, 3],
[6, 6], [8, 7], [6, 9], [9, 5], [7, 7]])
y = np.array([-1, -1, -1, -1, -1, 1, 1, 1, 1, 1])
for C in [1.0, 0.02]: # C=1.0 is the default
svm = SVC(kernel="linear", C=C).fit(X, y)
w, b = svm.coef_[0], svm.intercept_[0]
print(f"C={C}: w={w.round(2)}, b={b:.2f}, margin={2 / np.linalg.norm(w):.2f}, "
f"support vectors={svm.n_support_.sum()}")
if C == 1.0:
print(" they are:", svm.support_vectors_.tolist())
C=1.0: w=[0.5 0.5], b=-5.00, margin=2.83, support vectors=3
they are: [[3.0, 5.0], [5.0, 3.0], [6.0, 6.0]]
C=0.02: w=[0.21 0.19], b=-1.97, margin=7.06, support vectors=8
At C=1.0 the SVM finds the playground's best line, , held by three students. At
C=0.02 violations are cheap, so the street widens to 7.06 and eight students sit on or inside it.
Now a curved dataset: two interlocking half-moons, with the second feature stretched 1,000× as if it were in other units.
# script_id: day_016_support_vector_machines/rbf
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC, LinearSVC
X, y = make_moons(n_samples=600, noise=0.2, random_state=42) # two curved classes
X = X * [1, 1000] # 2nd feature in other units
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
models = {
"LinearSVC, scaled": make_pipeline(StandardScaler(), LinearSVC()),
"SVC rbf, unscaled": SVC(), # kernel="rbf", C=1.0, gamma="scale"
"SVC rbf, scaled": make_pipeline(StandardScaler(), SVC()),
}
for name, model in models.items():
model.fit(X_tr, y_tr)
print(f"{name:18} test accuracy {model.score(X_te, y_te):.3f}")
LinearSVC, scaled test accuracy 0.867
SVC rbf, unscaled test accuracy 0.820
SVC rbf, scaled test accuracy 0.947
A straight line gets 0.867, because the moons curve. The RBF kernel bends around them, but only after
scaling: unscaled, the stretched feature swamps every distance, and the kernel does worse than the line.
gamma sets how fast the RBF similarity fades with distance; "scale" picks it from the data's spread.
Quick check
Quick check
1. A point has label y = −1 and score f(x) = 0.5. What is its hinge loss?
2. You lower C from 1.0 to 0.02. What happens to the street?
3. You delete a training point that is far outside the street. What happens to the boundary?
Next
SVMs need labels to learn from; D17 finds groups in data that has none.