Sub topic 2
Why the margin matters
This chapter assumes you know what a hyperplane is, how to compute a dot product, and what overfitting means. You should also be able to read short NumPy code.
Many boundaries, one training set
If two classes can be separated by a straight line, infinitely many lines do it. All of them have zero training error, so training error can't pick one. The choice matters because a line that passes very close to a training point is fragile. A small amount of noise in a new point can push it to the wrong side.
The maximum-margin idea resolves this. Among all separating hyperplanes, choose the one farthest from the nearest training points.
Measuring the margin
A hyperplane is the set of points where w·x + b = 0. The distance from a point x to it is |w·x + b| / ‖w‖. With labels y in {-1, +1}, the quantity y(w·x + b) is positive exactly when the point is on the correct side.
The geometric margin of a hyperplane is the smallest of these signed distances over the training set:
margin = min over i of yi (w·xi + b) / ‖w‖
Rescaling w and b by the same factor does not move the hyperplane. So we fix the scale so that the closest points satisfy y(w·x + b) = 1. The total width of the street between the two classes is then 2 / ‖w‖.
The last step is the key link to the next chapter. Maximizing 2 / ‖w‖ is the same as minimizing ‖w‖, or equivalently ½‖w‖², which is a smooth objective that is easy to optimize.
Why a large margin helps
A wide margin gives the classifier room for error. New points drawn from the same distribution as the training data tend to land near the training points. If every training point is far from the boundary, small shifts are unlikely to flip a prediction. Learning theory makes this precise: the capacity of the classifier depends on the margin, not only on the number of features. This is why SVMs can work in very high dimensions.
Computing a margin
The code below fits a linear SVM with a very large C, which approximates a hard margin. It then compares its margin to that of a hand-picked separating line.
import numpy as np
from sklearn.svm import SVC
X = np.array([[0, 0], [1, 0], [0, 1], [3, 3], [4, 3], [3, 4]], dtype=float)
y01 = np.array([0, 0, 0, 1, 1, 1])
y = 2 * y01 - 1 # labels in {-1, +1}
def geometric_margin(w, b, X, y):
return (y * (X @ w + b)).min() / np.linalg.norm(w)
clf = SVC(kernel="linear", C=1e6).fit(X, y01)
w, b = clf.coef_[0], clf.intercept_[0]
print("SVM margin:", geometric_margin(w, b, X, y))
print("SVM width 2/||w||:", 2 / np.linalg.norm(w))
print("Vertical line x1 = 2:", geometric_margin(np.array([1.0, 0.0]), -2.0, X, y))The SVM margin is at least as large as that of the hand-picked line. The width printed on the second line should be twice the SVM margin.
Exercise
A hyperplane has w = (3, 4) and b = -5. What is the distance from the point (3, 4) to it?
Show answer
w·x + b = 9 + 16 - 5 = 20. ‖w‖ = 5. The distance is 20 / 5 = 4.