Support Vector Machines: Margin and Hinge Loss
When two classes can be separated by a line, infinitely many lines do it. Logistic regression picks the one that maximises the likelihood; a support vector machine (SVM) picks the one with the widest margin, the widest empty street between the classes. The idea, due to Vapnik and colleagues in the 1990s, gives a classifier defined by a handful of boundary points (the support vectors), a convex training problem, and, through kernels in the next lesson, nonlinear boundaries at the cost of a linear model. The Machine Learning course uses SVC; here you solve the SVM's optimisation problem yourself.
The margin
Labels are and the classifier is , predicting the sign. Scale and so that the closest points satisfy . The distance between the two lines and is then
so maximising the margin means minimising . Real data overlaps, so the soft-margin SVM allows violations at a price :
At the optimum , the hinge loss, so the problem is unconstrained regularised hinge-loss minimisation:
Compare with logistic regression: same penalty, but the log-loss is replaced by the hinge, which is exactly zero for points beyond the margin. Those points have no influence at all, which is why the solution depends only on the support vectors. Derivations: Separating Hyperplanes and the Margin, Soft Margin and the Hinge Loss.
The dual problem
With Lagrange multipliers for the constraints, the problem turns into its dual (The Dual SVM and Kernels, Inequality Constraints and the KKT Conditions):
with . The KKT conditions sort the points: beyond the margin (not support vectors), exactly on the margin (these give ), inside the margin or misclassified. The data enters only through dot products , the door to kernels.
Solving the dual from scratch
A small quadratic program fits a general-purpose solver (SciPy's SLSQP) on 40 points:
import numpy as np
from scipy.optimize import minimize
from sklearn.datasets import make_blobs
from sklearn.svm import SVC
X, y01 = make_blobs(n_samples=40, centers=[[-1.5, -1], [1.5, 1]], cluster_std=1.0, random_state=0)
y = np.where(y01 == 1, 1.0, -1.0) # SVM labels are -1 and +1
C = 1.0
# Dual problem: maximise sum(a) - 1/2 a^T Q a subject to 0 <= a <= C and sum(a y) = 0
Q = (y[:, None] * y[None, :]) * (X @ X.T)
res = minimize(lambda a: 0.5 * a @ Q @ a - a.sum(), np.zeros(len(y)), jac=lambda a: Q @ a - 1,
bounds=[(0, C)] * len(y), constraints={"type": "eq", "fun": lambda a: a @ y, "jac": lambda a: y},
method="SLSQP", options={"ftol": 1e-12, "maxiter": 500})
a = res.x
w = (a * y) @ X # w = sum a_i y_i x_i
free = (a > 1e-6) & (a < C - 1e-6) # support vectors exactly on the margin
b = np.mean(y[free] - X[free] @ w)
sv = np.flatnonzero(a > 1e-6)
sk = SVC(kernel="linear", C=C).fit(X, y)
print("ours w", w.round(3), " b", round(b, 3))
print("sklearn w", sk.coef_[0].round(3), " b", round(sk.intercept_[0], 3))
print("support vectors ours", sv.tolist())
print("support vectors skl ", sorted(sk.support_.tolist()))
margins = y * (X @ w + b)
print("margin width 2/||w||:", round(2 / np.linalg.norm(w), 3))
print("points inside the margin or misclassified (y f(x) < 1):", int(np.sum(margins < 1 - 1e-6)),
" misclassified:", int(np.sum(margins < 0)))ours w [1.341 0.761] b -0.164
sklearn w [1.341 0.761] b -0.164
support vectors ours [4, 15, 17, 19, 22, 23, 24, 26, 34, 37]
support vectors skl [4, 15, 17, 19, 22, 23, 24, 26, 34, 37]
margin width 2/||w||: 1.297
points inside the margin or misclassified (y f(x) < 1): 8 misclassified: 2
The general solver and libsvm's specialised SMO algorithm (which SVC uses) find the same hyperplane and the same 10 support vectors out of 40 points. The other 30 points could be deleted without changing the model. Eight support vectors violate the margin (two of them are misclassified); the remaining two sit exactly on it and fix .
The primal by subgradient descent, and the role of C
The hinge loss has a kink at , so it has no gradient there, but a subgradient works (Subgradients): for points with add , for the others nothing. Plain subgradient descent with a decaying step size comes close to the exact optimum. Then the effect of :
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.svm import LinearSVC, SVC
X, y01 = make_blobs(n_samples=40, centers=[[-1.5, -1], [1.5, 1]], cluster_std=1.0, random_state=0)
y = np.where(y01 == 1, 1.0, -1.0)
def pegasos_like(X, y, C=1.0, epochs=2000, lr0=0.01):
"""Subgradient descent on the primal: 1/2 ||w||^2 + C * sum max(0, 1 - y (w.x + b))."""
w, b = np.zeros(X.shape[1]), 0.0
for t in range(epochs):
lr = lr0 / (1 + t / 200)
active = y * (X @ w + b) < 1 # points with positive hinge loss
gw = w - C * (y[active, None] * X[active]).sum(axis=0)
gb = -C * y[active].sum()
w, b = w - lr * gw, b - lr * gb
return w, b
def primal(w, b, C=1.0):
return 0.5 * w @ w + C * np.maximum(0, 1 - y * (X @ w + b)).sum()
w, b = pegasos_like(X, y)
sk = SVC(kernel="linear", C=1.0).fit(X, y)
print("subgradient w", w.round(3), " b", round(b, 3), " objective", round(primal(w, b), 4))
print("SVC (exact) w", sk.coef_[0].round(3), " b", round(sk.intercept_[0], 3), " objective", round(primal(sk.coef_[0], sk.intercept_[0]), 4))
for C in [0.01, 0.1, 1, 100]:
m = SVC(kernel="linear", C=C).fit(X, y)
print(f"C={C:<5} margin width {2 / np.linalg.norm(m.coef_):.2f} support vectors {len(m.support_):2d} training accuracy {m.score(X, y):.3f}")subgradient w [1.337 0.762] b -0.162 objective 7.4871
SVC (exact) w [1.341 0.761] b -0.164 objective 7.4861
C=0.01 margin width 5.00 support vectors 36 training accuracy 0.900
C=0.1 margin width 2.25 support vectors 18 training accuracy 0.950
C=1 margin width 1.30 support vectors 10 training accuracy 0.950
C=100 margin width 0.24 support vectors 5 training accuracy 0.975
Subgradient descent ends within 0.001 of the optimal objective. The sweep shows the trade-off: small makes violations cheap, so the street gets wide (5.00) and almost every point becomes a support vector; large punishes every violation, the street narrows to 0.24 and the boundary bends to the training points. plays the role of in ridge regression: it is an inverse regularisation strength, chosen by cross-validation. For large data, LinearSVC (liblinear) or SGDClassifier(loss="hinge") solve the primal much faster than SVC.
Try it in the lab with the linear SVM: the solid line is the boundary, the dashed lines the margins , and circled points are support vectors. Change and watch the street.
Strengths, weaknesses, when to use it
| Strengths | Weaknesses |
|---|---|
| convex problem, unique solution | no probabilities (Platt scaling via probability=True adds them, at a cost) |
| depends only on support vectors; robust to points far from the boundary | needs feature scaling |
| works well in high dimensions (text) | kernel SVMs scale badly beyond about rows |
| kernels give nonlinear boundaries | (and kernel parameters) must be tuned |
Use a linear SVM for high-dimensional sparse data such as text, where it is as accurate as logistic regression and very fast with LinearSVC; use kernel SVMs for small to medium data sets with complex boundaries.
Pitfalls
- Unscaled features. The margin is measured in feature units; a feature in thousands dominates it.
- Reading
decision_functionas a probability. It is a signed distance-like score. LinearSVCandSVC(kernel="linear")differ.LinearSVCdefaults to the squared hinge and penalises the intercept, so coefficients differ slightly.
Practice
- A point has and . What is its hinge loss, and is it a support vector?
Answer
. It is inside the margin (correct side, but ), so its and it is a support vector.
- Why does deleting a point with not change the SVM?
Answer
Its hinge loss and its subgradient are 0, and in the dual its , so it contributes nothing to . The optimum of the problem without it is the same.
Test yourself
What is the width of the margin of a linear SVM with weight vector ?
Which points determine a trained SVM?
- All training points equally
- Only the support vectors: points on or inside the margin
- Only misclassified points
- The class centroids
What happens to the margin as grows?
- It widens
- It narrows, because violations become expensive
- It stays the same
- It becomes nonlinear
How does the hinge loss differ from the logistic loss?
- It is not convex
- It is exactly zero for points beyond the margin
- It is always larger
- It needs probabilities