Support vector machines and kernels
The widest street, and the trick that makes it curve
SVMs were the dominant classifier before deep learning and remain excellent on small, clean datasets. More importantly, they teach three ideas you will meet again and again: maximizing a margin as a route to generalization, the dual view in which data enters only through inner products, and the kernel trick, which is the formal version of "similarity = dot product in some feature space" that underlies attention (7.2 Scaled dot-product and multi-head attention, fully derived) and embedding search (9.2 Embeddings deep dive).
You'll be able to
- Derive the hard- and soft-margin SVM objectives from the geometry of the margin
- Write the hinge-loss formulation and compare it with logistic loss
- Explain the dual problem, support vectors and why predictions depend on data only through inner products
- Apply the kernel trick (polynomial, RBF), tune C and γ, and know when to use linear vs kernel SVMs
Key ideas
- The SVM picks the separating hyperplane with the largest margin 2/‖w‖; maximizing the margin = minimizing ½‖w‖² under yᵢ(wᵀxᵢ + b) ≥ 1.
- Soft margins add slack; the problem equals hinge loss Σ max(0, 1 − yᵢf(xᵢ)) plus L2 regularization 1/(2C)·‖w‖².
- Large C → narrow margin, few violations, high variance; small C → wide margin, more violations, higher bias.
Show 4 more key ideas
- In the dual, w = Σ αᵢyᵢxᵢ and only support vectors (points on or inside the margin) have αᵢ > 0.
- Predictions depend on data only through inner products, so any PSD kernel k(x, z) = φ(x)ᵀφ(z) can replace them — the kernel trick.
- RBF kernel exp(−γ‖x−z‖²) is an infinite-dimensional feature map; γ controls locality and overfitting.
- Scale features, tune C and γ on log grids by CV, and switch to linear SVMs beyond ~10⁵ samples.
Suggested path through this lesson
The widest street
Take linearly separable data with labels and a linear classifier . Infinitely many hyperplanes separate the classes; which one should we trust? The SVM answer: the one with the largest margin, i.e. the widest empty street between the classes, because a wide street tolerates the most perturbation of future points.
The distance from a point to the hyperplane is (1.1 Vectors, dot products and norms). Since and describe the same hyperplane, fix the scale so that the closest points satisfy . Then the street has width , and maximizing it is
This is a convex quadratic program with a unique solution — no local minima, unlike neural networks.
Soft margins and the hinge loss
Real data overlap, so allow violations with slack variables :
Eliminating turns this into an unconstrained regularized loss:
So an SVM is "hinge loss + L2 regularization" (3.6 Regularization and generalization), just as logistic regression is "log loss + L2". The hinge is zero for points beyond the margin, so they do not influence the solution at all; log loss never reaches zero, so every point keeps pulling. is the inverse regularization strength: large approaches the hard margin (narrow street, high variance), small tolerates violations for a wider street (higher bias, lower variance).
| Logistic regression | SVM | |
|---|---|---|
| loss | ||
| outputs | calibrated probabilities | scores (calibrate with Platt scaling) |
| solution depends on | all points | support vectors only |
| nonlinearity | feature engineering | kernels |
The dual and the support vectors
Introduce multipliers for the constraints (1.10 Optimization: from gradient descent to Adam). The Lagrangian of the hard-margin problem is . Setting derivatives to zero gives
and substituting back yields the dual problem:
Complementary slackness says only for points on or inside the margin — the support vectors. Everything else has and could be deleted without changing the classifier. The decision function becomes
which depends on the data only through inner products . That observation is the door to kernels.
The kernel trick
Replace every inner product by for some feature map — without ever computing . The classifier becomes linear in feature space and curved in input space.
Worked example: the polynomial kernel in expands as
so a single multiplication-and-square does the work of a 3-dimensional feature map; for degree in dimensions the implicit space has features. The RBF (Gaussian) kernel corresponds to an infinite-dimensional ; sets how local the similarity is — large makes each support vector influence only its neighbourhood (wiggly boundary, overfitting), small approaches a linear classifier. A valid kernel must give a positive semi-definite Gram matrix (Mercer's condition): a kernel is nothing more than a legitimate similarity function.
Intuition. A kernel SVM is a weighted kNN in disguise (3.4 k-Nearest Neighbors): the prediction is a weighted sum of similarities to a few remembered training points (the support vectors), with weights learned to maximize the margin.
In practice
Scale features first — SVMs are not scale-invariant. Grid-search and on log scales with cross-validation; look at the number of support vectors (a very high fraction signals overfitting or a too-local ). Kernel SVM training is – in the number of samples, so beyond roughly rows use LinearSVC or SGD with hinge loss, or approximate kernels with random Fourier features. For probabilities, calibrate (Platt scaling or isotonic). On typical tabular data, GBDTs (3.9 Ensembles: bagging, random forests and gradient boosting) usually win; SVMs shine on small, high-dimensional, clean problems (text with TF-IDF features, bioinformatics) and as strong, fast baselines.
Kernels everywhere
The dual view generalizes far beyond SVMs (the representer theorem: regularized solutions live in the span of the training points). Kernel ridge regression and Gaussian processes replace the hinge with squared loss. And the pattern "compute a similarity between a query and stored keys, then weight stored values" is exactly scaled dot-product attention, whose similarity is a linear kernel (7.2 Scaled dot-product and multi-head attention, fully derived), and exactly embedding search, whose cosine similarity is a normalized linear kernel (9.2 Embeddings deep dive).
Where this shows up later
- Hinge loss in the loss catalog — 4.3 Loss functions catalog; regularization strength as bias–variance control — 3.6 Regularization and generalization, 3.5 Evaluating models: metrics, validation and the bias–variance trade-off.
- Attention as kernel-weighted retrieval — 7.2 Scaled dot-product and multi-head attention, fully derived; embedding similarity and vector search — 9.2 Embeddings deep dive, 9.3 Vector search and indexes; contrastive losses that learn similarity functions — 5.8 Self-supervised and contrastive learning.
Common pitfalls (4)
- Forgetting to standardize features before an RBF SVM: one large-scale feature dominates every distance.
- Interpreting decision_function scores as probabilities; SVM scores need calibration.
- Using a kernel SVM on millions of rows — the kernel matrix alone is n² entries.
- Confusing C with regularization strength: C is its inverse (large C = less regularization).
Recap: all 7 key points
- The SVM picks the separating hyperplane with the largest margin 2/‖w‖; maximizing the margin = minimizing ½‖w‖² under yᵢ(wᵀxᵢ + b) ≥ 1.
- Soft margins add slack; the problem equals hinge loss Σ max(0, 1 − yᵢf(xᵢ)) plus L2 regularization 1/(2C)·‖w‖².
- Large C → narrow margin, few violations, high variance; small C → wide margin, more violations, higher bias.
- In the dual, w = Σ αᵢyᵢxᵢ and only support vectors (points on or inside the margin) have αᵢ > 0.
- Predictions depend on data only through inner products, so any PSD kernel k(x, z) = φ(x)ᵀφ(z) can replace them — the kernel trick.
- RBF kernel exp(−γ‖x−z‖²) is an infinite-dimensional feature map; γ controls locality and overfitting.
- Scale features, tune C and γ on log grids by CV, and switch to linear SVMs beyond ~10⁵ samples.
Watch
Margins, soft margins and the kernel idea with pictures; parts 2–3 cover polynomial and RBF kernels.
Read
Exercises
- Margin by hand
For the 1-D points x = −2, −1 (class −1) and 1, 3 (class +1), find the maximum-margin classifier . Expected: the street runs from −1 to 1, so w = 1, b = 0 and the margin is 2/|w| = 2; the support vectors are −1 and 1.
- C and γ on the two-moons data
Generate
make_moons(noise=0.3), fit RBF SVMs over a grid of C ∈ {0.1, 1, 10, 100} and γ ∈ {0.01, 0.1, 1, 10}, and plot the 16 decision boundaries with support vectors highlighted. Expected: large γ gives islands around points; small C gives a smooth, wide-margin boundary; the CV-best cell is in the middle. - Verify the kernel trick numerically
Sample 5 random vectors in . Compute the Gram matrix with directly, then compute it via the explicit map . Expected: the two 5×5 matrices agree to floating-point precision, and all eigenvalues are ≥ 0.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →