Kernels and support vector machines¶
A support vector machine draws the separating line with the widest possible margin, and the solution depends on the data only through dot products. Replace the dot product with a kernel and the same convex problem learns curved boundaries in a feature space you never build.
10,000 ft
From the early 1990s to about 2010, kernel methods were the most principled and often the most accurate tools in machine learning: SVMs led text classification and, with hand-crafted invariances, digit recognition, and they came with a convex training problem and a generalisation theory. Deep learning displaced them by learning the feature map instead of fixing it in advance. But the ideas stayed. A kernel is just a similarity function that behaves like an inner product, and that view explains Gaussian processes, the neural tangent kernel (wide networks trained by gradient descent behave like kernel machines), and attention, which is a learned kernel smoother. The margin idea also explains why boosting keeps improving after training error hits zero and anchors the learning theory of large-margin classifiers.
2,000 ft
Among all hyperplanes that separate two classes, pick the one farthest from the nearest points: maximise the margin. This is a convex quadratic programme. Allowing some points inside the margin at a price \(C\) turns it into minimising hinge loss plus an \(\ell_2\) penalty, a cousin of logistic regression. Its Lagrange dual has two decisive properties: the data appear only as dot products \(\mathbf{x}_i^\top\mathbf{x}_j\), and only the few points on or inside the margin (the support vectors) get non-zero weight. Replacing \(\mathbf{x}_i^\top\mathbf{x}_j\) by a kernel \(k(\mathbf{x}_i,\mathbf{x}_j)\) (any function that is an inner product in some feature space) gives a nonlinear classifier at the cost of a linear one in that space, even when the space is infinite-dimensional.
Ground level¶
The margin¶
A linear classifier predicts \(\operatorname{sign}(\mathbf{w}^\top\mathbf{x} + b)\) for labels \(y \in \{-1,+1\}\). The signed distance from a point \(\mathbf{x}_i\) to the hyperplane \(\mathbf{w}^\top\mathbf{x} + b = 0\) is \((\mathbf{w}^\top\mathbf{x}_i + b)/\lVert\mathbf{w}\rVert\), so the geometric margin of a correctly classified point is
If the data are linearly separable there are infinitely many separating hyperplanes; the perceptron stops at whichever it reaches first. The SVM asks for the one whose smallest margin is largest. Scaling \(\mathbf{w}\) and \(b\) together does not move the hyperplane, so we may fix the scale by requiring \(y_i(\mathbf{w}^\top\mathbf{x}_i + b) \ge 1\) for all points with equality for the closest ones. The margin band then has width \(2/\lVert\mathbf{w}\rVert\), and maximising it is the same as
A quadratic objective with linear constraints: a convex quadratic programme with a unique solution.
Worked example: a hard-margin SVM by hand¶
Four points in 2-D: one negative \(B = (0,0)\) and three positives \(A = (1,2)\), \(C = (2,1)\), \(D = (3,3)\).
The max-margin boundary is the perpendicular bisector of the shortest segment between the two classes' convex hulls. The positive hull's nearest point to the origin is the midpoint of \(AC\), \((1.5, 1.5)\), so \(\mathbf{w}\) points along \((1,1)\): \(\mathbf{w} = (a, a)\). The constraints are tight at \(B\) and at \(A\) and \(C\):
- \(B\): \(y(\mathbf{w}^\top B + b) = -(0 + b) = 1 \Rightarrow b = -1\).
- \(C\): \(2a + a - 1 = 1 \Rightarrow a = 2/3\) (and \(A\) gives the same).
So \(\mathbf{w} = (2/3, 2/3)\), \(b = -1\), \(\lVert\mathbf{w}\rVert = 0.943\), margin width \(2/0.943 = 2.121\), exactly the distance from \((0,0)\) to \((1.5,1.5)\). The point \(D\) has \(y(\mathbf{w}^\top D + b) = 4 - 1 = 3 > 1\): it is outside the margin and plays no role. Move it anywhere on the positive side beyond the margin and nothing changes.
The dual (derived below) writes \(\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i\) with \(\alpha_i \ge 0\) and \(\sum_i \alpha_i y_i = 0\). Here \(\mathbf{w} = \alpha_A(1,2) + \alpha_C(2,1) - \alpha_B(0,0) = (2/3, 2/3)\) gives \(\alpha_A = \alpha_C = 2/9\), and the balance constraint gives \(\alpha_B = 4/9\); \(\alpha_D = 0\). The code in Build it recovers \(\alpha = (0.4444, 0.2222, 0.2222, 0)\), \(\mathbf{w} = (0.667, 0.667)\), \(b = -1\), margin \(2.1214\). As a check on the theory, \(\sum_i\alpha_i = 8/9 = \lVert\mathbf{w}\rVert^2\), an identity that holds at every hard-margin optimum.
Soft margins and the hinge loss¶
Real data overlap. Give each point a slack \(\xi_i \ge 0\) that lets it violate the margin, and charge \(C\) per unit of slack:
At the optimum each slack is as small as allowed, \(\xi_i = \max(0, 1 - y_i f(\mathbf{x}_i))\) with \(f(\mathbf{x}) = \mathbf{w}^\top\mathbf{x} + b\). Substituting, the soft-margin SVM is exactly regularised empirical risk minimisation with the hinge loss:
Large \(C\) (small \(\lambda\)) means "violations are expensive": a narrow margin that bends around the data, low bias and high variance. Small \(C\) allows many violations for a wide, stable margin. Seen this way, an SVM is a linear model like logistic regression that differs only in the loss applied to the functional margin \(m = y f(\mathbf{x})\):
The dual and the support vectors¶
The dual of the soft-margin problem (derived in The maths) is
with \(\mathbf{w} = \sum_i \alpha_i y_i \mathbf{x}_i\) and the classifier
Complementary slackness sorts the training points into three kinds:
| \(\alpha_i\) | Position | Role |
|---|---|---|
| \(0\) | outside the margin, \(y_i f(\mathbf{x}_i) > 1\) | irrelevant: delete it and the solution is unchanged |
| \(0 < \alpha_i < C\) | exactly on the margin, \(y_i f(\mathbf{x}_i) = 1\) | free support vector; used to compute \(b\) |
| \(C\) | inside the margin or misclassified | bounded support vector; its pull is capped at \(C\) |
Two things to notice. First, the solution is sparse: often a small fraction of the training set ends up as support vectors, and prediction costs one kernel evaluation per support vector. Second, and far more consequential, the data enter only through inner products.
The kernel trick¶
Suppose we map inputs through features \(\phi(\mathbf{x})\) and run a linear SVM there. The dual and the predictor need only \(\phi(\mathbf{x}_i)^\top\phi(\mathbf{x}_j)\). If some function \(k\) computes that inner product directly from the raw inputs, we never need \(\phi\) at all.
Worked example. In 2-D let \(\phi(\mathbf{x}) = (x_1^2,\ \sqrt2\,x_1x_2,\ x_2^2)\). Then
For \(\mathbf{x} = (1,2)\), \(\mathbf{z} = (3,1)\): \(\mathbf{x}^\top\mathbf{z} = 5\) so \(k = 25\); explicitly \(\phi(\mathbf{x}) = (1, 2\sqrt2, 4)\), \(\phi(\mathbf{z}) = (9, 3\sqrt2, 1)\) and \(9 + 12 + 4 = 25\). A linear boundary in \(\phi\)-space is a conic section (circle, ellipse, hyperbola) in the original plane. The polynomial kernel \((\mathbf{x}^\top\mathbf{z} + c)^d\) on \(p\) inputs corresponds to all monomials up to degree \(d\), which number \(\binom{p+d}{d}\): for 256-pixel images and \(d = 5\) that is about \(9.7\times10^{9}\) features, computed with one 256-dimensional dot product and a power.
Which functions are kernels?¶
\(k\) is a valid kernel (an inner product in some feature space) if and only if it is symmetric and positive semi-definite: for every finite set of points, the Gram matrix \(K_{ij} = k(\mathbf{x}_i, \mathbf{x}_j)\) satisfies \(\mathbf{c}^\top K\mathbf{c} \ge 0\) for all \(\mathbf{c}\). This is what keeps the dual a concave maximisation. (The space it implicitly defines is the reproducing kernel Hilbert space, RKHS.) Valid kernels are closed under addition, multiplication, positive scaling, \(f(\mathbf{x})k(\mathbf{x},\mathbf{z})f(\mathbf{z})\) and \(\exp(k)\), so you can build them like Lego:
| Kernel | \(k(\mathbf{x},\mathbf{z})\) | Feature space | Knob |
|---|---|---|---|
| Linear | \(\mathbf{x}^\top\mathbf{z}\) | the inputs | — |
| Polynomial | \((\mathbf{x}^\top\mathbf{z} + c)^d\) | monomials up to degree \(d\) | \(d\), \(c\) |
| Gaussian (RBF) | \(\exp(-\gamma\lVert\mathbf{x}-\mathbf{z}\rVert^2)\) | infinite-dimensional | bandwidth \(\gamma\) |
| Laplacian | \(\exp(-\gamma\lVert\mathbf{x}-\mathbf{z}\rVert_1)\) | infinite-dimensional, rougher functions | \(\gamma\) |
| String / graph kernels | counts of shared substrings, walks | combinatorial | — |
The RBF kernel is the default for vectors. For \(\mathbf{x} = (1,2)\), \(\mathbf{z} = (3,1)\) with \(\gamma = 0.5\): \(\lVert\mathbf{x}-\mathbf{z}\rVert^2 = 5\) and \(k = e^{-2.5} = 0.082\), so the points are "barely similar". Its predictor \(f(\mathbf{x}) = \sum_i \alpha_i y_i e^{-\gamma\lVert\mathbf{x}-\mathbf{x}_i\rVert^2} + b\) is a weighted sum of Gaussian bumps centred on the support vectors: a smart, sparse, weighted nearest-neighbour rule. \(\gamma\) sets the bump width. Large \(\gamma\) gives narrow bumps, every point its own island and overfitting; small \(\gamma\) gives broad bumps and a nearly linear boundary. \(\gamma\) and \(C\) must be tuned together, usually on a log grid with cross-validation.
Kernel ridge regression and the representer theorem¶
The trick is not specific to SVMs. Any algorithm that can be written in terms of inner products can be kernelised: ridge regression, PCA (kernel PCA), \(k\)-means, logistic regression. The guarantee behind this is the representer theorem: for any loss on the training predictions plus an increasing function of the RKHS norm, the minimiser has the form \(f(\cdot) = \sum_{i=1}^n \alpha_i k(\mathbf{x}_i, \cdot)\). An optimisation over an infinite-dimensional function space collapses to \(n\) coefficients. For squared loss (kernel ridge regression) they have a closed form,
which is also exactly the posterior mean of a Gaussian process with covariance \(k\) and noise variance \(\lambda\): the Bayesian and the regularisation views give the same predictor.
The catch: \(n^2\)¶
Kernel methods pay for their elegance in the number of examples. The Gram matrix has \(n^2\) entries: for \(n = 100{,}000\) that is \(10^{10}\) numbers, 80 GB in float64. Solving kernel ridge regression exactly costs \(O(n^3)\). SVM solvers avoid forming the whole matrix: SMO (Platt, 1998) optimises the dual two coefficients at a time (the smallest subproblem that respects \(\sum\alpha_iy_i = 0\)), each solved in closed form, and LIBSVM caches kernel rows; still, scikit-learn's documentation warns that SVC fit time "scales at least quadratically with the number of samples and may be impractical beyond tens of thousands of samples".
The way out is to approximate the kernel with an explicit, finite feature map and go back to a linear model:
- Random Fourier features (Rahimi and Recht, 2007): for shift-invariant kernels, \(k(\mathbf{x}-\mathbf{z}) \approx \mathbf{z}(\mathbf{x})^\top\mathbf{z}(\mathbf{z})\) with \(\mathbf{z}(\mathbf{x}) = \sqrt{2/D}\cos(W^\top\mathbf{x} + \mathbf{b})\), \(W\) drawn from the kernel's Fourier transform. Cost \(O(nD^2)\) instead of \(O(n^3)\); the approximation error falls like \(1/\sqrt{D}\).
- Nyström: use the kernel between all points and \(m\) landmark points, \(K \approx K_{nm}K_{mm}^{-1}K_{mn}\).
That move (replace an expensive kernel by random features, then use a linear method) reappears in transformers as linear attention.
Kernels in modern deep learning¶
- Attention is a kernel smoother. Output \(i\) of attention is \(\sum_j \kappa(\mathbf{q}_i,\mathbf{k}_j)\mathbf{v}_j / \sum_j \kappa(\mathbf{q}_i,\mathbf{k}_j)\) with \(\kappa(\mathbf{q},\mathbf{k}) = \exp(\mathbf{q}^\top\mathbf{k}/\sqrt{d})\): the Nadaraya–Watson estimator from 1960s statistics, with learned queries and keys (Tsai et al., 2019, make this precise).
- Linear attention replaces \(\kappa\) by \(\phi(\mathbf{q})^\top\phi(\mathbf{k})\), so \(\sum_j \phi(\mathbf{q}_i)^\top\phi(\mathbf{k}_j)\mathbf{v}_j = \phi(\mathbf{q}_i)^\top\big(\sum_j\phi(\mathbf{k}_j)\mathbf{v}_j^\top\big)\) costs \(O(n)\) rather than \(O(n^2)\) in sequence length (Katharopoulos et al., 2020); the Performer approximates the softmax kernel with positive random features (Choromanski et al., 2020). This is the bridge to the state-space and linear-attention models.
- The neural tangent kernel. Jacot, Gabriel and Hongler (2018) showed that in the infinite-width limit, a network trained by gradient descent evolves as kernel regression with a fixed kernel, \(\Theta(\mathbf{x},\mathbf{x}') = \nabla_\theta f(\mathbf{x})^\top\nabla_\theta f(\mathbf{x}')\). Real networks of finite width escape this "lazy" regime and learn their features, which is a good one-line answer to why deep learning beat kernel machines.
History¶
- 1964: Aizerman, Braverman and Rozonoer's "potential function" method uses what we now call the kernel trick, in the Soviet journal Avtomatika i Telemekhanika.
- 1960s–1970s: Vapnik and Chervonenkis develop the "generalised portrait" (a linear maximum-margin classifier) and the statistical learning theory behind it.
- 1992: Boser, Guyon and Vapnik combine the maximum margin with kernels: the modern SVM.
- 1995: Cortes and Vapnik add slack variables (the soft margin) and name the method "support-vector networks".
- 1998: Platt's SMO makes training practical; Joachims shows SVMs excel at text categorisation; Burges's tutorial spreads the method.
- 2000s: LIBSVM becomes the standard library; DeCoste and Schölkopf (2002) report the lowest MNIST error of the time with SVMs trained on transformed "virtual" examples; kernel methods dominate NeurIPS. Rahimi and Recht's random features (2007) later win the NeurIPS test-of-time award.
- 2012 onwards: deep networks with learned features overtake kernels on perception tasks; kernel ideas return as theory (NTK, 2018) and as efficient attention (2020).
First principles¶
Why maximise the margin? Three answers that converge. Robustness: if test points are training points plus small perturbations of size less than the margin, they are still classified correctly. Capacity: Vapnik showed that hyperplanes constrained to margin \(\gamma\) on data inside a ball of radius \(R\) have VC dimension at most \(\min(\lceil R^2/\gamma^2\rceil, d) + 1\), which does not depend on the dimension \(d\) once the margin is large. That is why an SVM can work in an infinite-dimensional feature space without overfitting by default (more in learning theory). Uniqueness: the margin objective is strictly convex in \(\mathbf{w}\), so there is one answer, not a perceptron's arbitrary one.
Why does the dual contain only dot products? Because the optimal \(\mathbf{w}\) lies in the span of the training inputs: any component of \(\mathbf{w}\) orthogonal to all \(\mathbf{x}_i\) leaves every constraint unchanged but increases \(\lVert\mathbf{w}\rVert\), so the optimum sets it to zero. Once \(\mathbf{w} = \sum_i \beta_i\mathbf{x}_i\), every quantity (\(\mathbf{w}^\top\mathbf{x}\), \(\lVert\mathbf{w}\rVert^2\)) is a combination of inner products. This is the representer theorem in miniature.
Why must a kernel be positive semi-definite? An inner product gives non-negative squared lengths: \(\lVert\sum_i c_i\phi(\mathbf{x}_i)\rVert^2 = \mathbf{c}^\top K\mathbf{c} \ge 0\). If \(K\) had a negative eigenvalue, some "vector" would have negative squared length, the dual quadratic would be unbounded and there would be no feature space. Conversely (Mercer, Moore–Aronszajn), any PSD \(k\) defines a feature space in which it is an inner product.
Why sparsity? The hinge is flat (zero) for \(m \ge 1\). Points that are comfortably correct exert no force on the solution, so they can be deleted. Logistic loss is never exactly zero, so every point keeps a small pull; logistic regression has no support vectors.
What the RBF kernel really is. Expand \(e^{-\gamma\lVert\mathbf{x}-\mathbf{z}\rVert^2} = e^{-\gamma\lVert\mathbf{x}\rVert^2}e^{-\gamma\lVert\mathbf{z}\rVert^2}\sum_{n\ge0}\frac{(2\gamma)^n(\mathbf{x}^\top\mathbf{z})^n}{n!}\): a weighted sum of polynomial kernels of every degree. So the RBF feature space contains all monomials, with higher degrees down-weighted by \(1/n!\); this is why it is a "universal" kernel that can approximate any continuous function on a compact set.
The maths¶
Derivation: the soft-margin dual and the KKT conditions
Primal: minimise \(\tfrac12\lVert\mathbf{w}\rVert^2 + C\sum_i\xi_i\) subject to \(y_i(\mathbf{w}^\top\mathbf{x}_i + b) \ge 1 - \xi_i\) and \(\xi_i \ge 0\). Introduce multipliers \(\alpha_i \ge 0\) and \(\mu_i \ge 0\):
Stationarity in the primal variables:
Substituting back, the \(\xi\) terms cancel and \(\tfrac12\lVert\mathbf{w}\rVert^2 - \sum_i\alpha_iy_i\mathbf{w}^\top\mathbf{x}_i = -\tfrac12\lVert\mathbf{w}\rVert^2\), leaving the dual
Strong duality holds (convex problem, linear constraints), so the KKT conditions characterise the optimum. Complementary slackness, \(\alpha_i[y_if(\mathbf{x}_i) - 1 + \xi_i] = 0\) and \(\mu_i\xi_i = 0\), gives the three cases in the table above: \(\alpha_i = 0 \Rightarrow y_if_i \ge 1\); \(0 < \alpha_i < C \Rightarrow \xi_i = 0, y_if_i = 1\); \(\alpha_i = C \Rightarrow y_if_i \le 1\). For any free support vector \(s\), \(b = y_s - \sum_i\alpha_iy_i\,\mathbf{x}_i^\top\mathbf{x}_s\) (average over all of them for numerical stability). For the hard margin (\(C\to\infty\)), the dual optimum equals the primal \(\tfrac12\lVert\mathbf{w}\rVert^2\), and since \(\sum\alpha_i - \tfrac12\lVert\mathbf{w}\rVert^2 = \tfrac12\lVert\mathbf{w}\rVert^2\) we get \(\sum_i\alpha_i = \lVert\mathbf{w}\rVert^2\), the identity checked in the worked example.
Kernelised SVM. Replace every \(\mathbf{x}_i^\top\mathbf{x}_j\) by \(K_{ij} = k(\mathbf{x}_i,\mathbf{x}_j)\). Shapes: \(K \in \mathbb{R}^{n\times n}\), \(\boldsymbol\alpha, \mathbf{y} \in \mathbb{R}^n\); the dual objective is \(\mathbf{1}^\top\boldsymbol\alpha - \tfrac12(\boldsymbol\alpha\odot\mathbf{y})^\top K(\boldsymbol\alpha\odot\mathbf{y})\); predictions on \(m\) new points are \(K_{\text{new}}(\boldsymbol\alpha\odot\mathbf{y}) + b\) with \(K_{\text{new}} \in \mathbb{R}^{m\times n}\) (only support-vector columns needed).
Derivation: the representer theorem and kernel ridge regression
Let \(\mathcal{H}\) be the RKHS of \(k\), with the reproducing property \(f(\mathbf{x}) = \langle f, k(\mathbf{x},\cdot)\rangle_{\mathcal{H}}\). Minimise \(J(f) = \sum_i L(y_i, f(\mathbf{x}_i)) + \Omega(\lVert f\rVert_{\mathcal{H}})\) with \(\Omega\) strictly increasing. Write \(f = f_\parallel + f_\perp\), where \(f_\parallel \in \operatorname{span}\{k(\mathbf{x}_i,\cdot)\}\) and \(f_\perp\) is orthogonal to that span. Then \(f(\mathbf{x}_i) = \langle f_\parallel + f_\perp, k(\mathbf{x}_i,\cdot)\rangle = f_\parallel(\mathbf{x}_i)\): the loss term ignores \(f_\perp\). But \(\lVert f\rVert^2 = \lVert f_\parallel\rVert^2 + \lVert f_\perp\rVert^2\), so any \(f_\perp \ne 0\) strictly increases \(\Omega\). Hence the minimiser has \(f = \sum_i\alpha_ik(\mathbf{x}_i,\cdot)\).
For squared loss and \(\Omega = \lambda\lVert f\rVert^2\): with \(f(\mathbf{x}_j) = (K\boldsymbol\alpha)_j\) and \(\lVert f\rVert^2 = \boldsymbol\alpha^\top K\boldsymbol\alpha\), minimise \(\lVert\mathbf{y} - K\boldsymbol\alpha\rVert^2 + \lambda\boldsymbol\alpha^\top K\boldsymbol\alpha\). The gradient is \(-2K(\mathbf{y} - K\boldsymbol\alpha) + 2\lambda K\boldsymbol\alpha = 2K\big[(K + \lambda I)\boldsymbol\alpha - \mathbf{y}\big]\), which vanishes at \(\boldsymbol\alpha = (K + \lambda I)^{-1}\mathbf{y}\). Predictions on new points: \(f(\mathbf{x}) = \mathbf{k}(\mathbf{x})^\top(K + \lambda I)^{-1}\mathbf{y}\), where \(\mathbf{k}(\mathbf{x})_i = k(\mathbf{x}_i,\mathbf{x})\).
Derivation: why random Fourier features work
Bochner's theorem: a continuous shift-invariant kernel \(k(\mathbf{x},\mathbf{z}) = \kappa(\mathbf{x}-\mathbf{z})\) with \(\kappa(0) = 1\) is positive definite if and only if \(\kappa\) is the Fourier transform of a probability density \(p(\boldsymbol\omega)\):
(the imaginary part vanishes because \(\kappa\) is real and symmetric). For the RBF kernel \(e^{-\gamma\lVert\boldsymbol\delta\rVert^2}\), \(p = \mathcal{N}(\mathbf{0}, 2\gamma I)\). Now take \(b \sim U[0, 2\pi]\) and \(z_{\boldsymbol\omega,b}(\mathbf{x}) = \sqrt2\cos(\boldsymbol\omega^\top\mathbf{x} + b)\). Using \(2\cos A\cos B = \cos(A-B) + \cos(A+B)\), \(\mathbb{E}_b[z(\mathbf{x})z(\mathbf{z})] = \cos(\boldsymbol\omega^\top(\mathbf{x}-\mathbf{z}))\) because \(\mathbb{E}_b\cos(\boldsymbol\omega^\top(\mathbf{x}+\mathbf{z}) + 2b) = 0\). Averaging \(D\) independent draws gives an unbiased estimate of \(k\) whose standard deviation shrinks as \(1/\sqrt{D}\) (Hoeffding gives uniform bounds over a compact set).
In practice¶
- Scale your features. RBF and polynomial kernels depend on distances and dot products, so a feature measured in rupees will swamp one measured in years. Standardise first (trees do not care; SVMs care a lot).
- Linear first for text and very high-dimensional sparse data. With \(p \gg n\) (bag-of-words, TF–IDF), data are often already nearly separable and a linear SVM (
LinearSVC, liblinear) is fast and strong. - Grid-search \(C\) and \(\gamma\) on a log scale, e.g. \(C \in \{10^{-2},\dots,10^{3}\}\), \(\gamma \in \{10^{-4},\dots,10^{1}\}\) times \(1/(p\cdot\operatorname{Var}(X))\), which is scikit-learn's
gamma="scale"default. - Probabilities need calibration. SVM scores are not probabilities; Platt scaling (a 1-D logistic regression on held-out scores) or isotonic regression converts them. Multi-class SVMs are built from binary ones (LIBSVM uses one-vs-one).
- Know when to stop using them. Beyond tens of thousands of points, use random features or Nyström plus a linear model, or switch to gradient-boosted trees (tabular) or neural networks (perception, language). As of 2026, kernel methods are mostly used for small, clean, scientific datasets, as Gaussian processes in Bayesian optimisation and hyperparameter tuning, and as a theoretical lens on deep networks.
Common misconceptions¶
“The kernel trick maps data to a higher dimension so that it becomes separable”
Half right. The mapping is implicit and never computed, and what makes it work is not the dimension but the margin. In very high dimensions almost anything is separable, which by itself would be a recipe for overfitting; the \(\lVert\mathbf{w}\rVert^2\) penalty (equivalently, the RKHS norm) is what keeps the solution simple.
“SVMs do not overfit”
They do, through \(\gamma\) and \(C\). With \(\gamma = 50\) on the rings below, the SVM classifies every training point correctly with 184 of 200 points as support vectors, and test accuracy drops. A large fraction of support vectors is a warning sign: the leave-one-out error of an SVM is at most (number of support vectors)/\(n\).
“Any similarity function can be used as a kernel”
Only positive semi-definite ones. The sigmoid "kernel" \(\tanh(a\,\mathbf{x}^\top\mathbf{z} + c)\) offered by many libraries is not PSD for most parameter values, and the optimiser may then misbehave.
Build it¶
A complete kernel SVM in NumPy using simplified SMO: pick a point that violates the KKT conditions, pair it with a random partner, solve the two-variable dual exactly, clip to the box \([0, C]\), update \(b\). Then the worked example and a nonlinear problem, two noisy concentric rings.
import numpy as np
rng = np.random.default_rng(0)
def rbf(A, B, gamma): # K[i,j] = exp(-gamma * ||a_i - b_j||^2)
sq = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T
return np.exp(-gamma * np.maximum(sq, 0))
def smo(K, y, C, tol=1e-4, sweeps=200):
"""Simplified SMO (Platt 1998): repeatedly optimise the dual over a pair (i, j)."""
n = len(y); a = np.zeros(n); b = 0.0
for _ in range(sweeps):
changed = 0
for i in range(n):
Ei = (a * y) @ K[:, i] + b - y[i]
if (y[i]*Ei < -tol and a[i] < C) or (y[i]*Ei > tol and a[i] > 0): # KKT violated
j = rng.integers(n - 1); j += j >= i
Ej = (a * y) @ K[:, j] + b - y[j]
ai, aj = a[i], a[j]
L, H = (max(0, aj-ai), min(C, C+aj-ai)) if y[i] != y[j] else (max(0, ai+aj-C), min(C, ai+aj))
eta = 2*K[i, j] - K[i, i] - K[j, j]
if L == H or eta >= 0: continue
a[j] = np.clip(aj - y[j]*(Ei - Ej)/eta, L, H)
a[i] = ai + y[i]*y[j]*(aj - a[j])
b1 = b - Ei - y[i]*(a[i]-ai)*K[i, i] - y[j]*(a[j]-aj)*K[i, j]
b2 = b - Ej - y[i]*(a[i]-ai)*K[i, j] - y[j]*(a[j]-aj)*K[j, j]
b = b1 if 0 < a[i] < C else b2 if 0 < a[j] < C else (b1 + b2) / 2
changed += 1
if changed == 0: break
return a, b
# 1) The worked example: linear kernel, hard margin (huge C)
X = np.array([[0., 0.], [1., 2.], [2., 1.], [3., 3.]]); y = np.array([-1., 1., 1., 1.])
a, b = smo(X @ X.T, y, C=1e6)
w = (a * y) @ X
print("alpha =", a.round(4), " w =", w.round(4), " b =", round(b, 4), " margin =", round(2/np.linalg.norm(w), 4))
# 2) Two concentric rings: no line separates them, an RBF kernel does
def rings(n):
r = np.where(np.arange(n) % 2 == 0, 1.0, 2.0) + rng.normal(0, 0.25, n)
t = rng.uniform(0, 2*np.pi, n)
return np.c_[r*np.cos(t), r*np.sin(t)], np.where(np.arange(n) % 2 == 0, 1., -1.)
Xtr, ytr = rings(200); Xte, yte = rings(1000)
kernels = {"linear": lambda A, B: A @ B.T}
for g in (0.1, 1, 50): kernels[f"rbf gamma={g}"] = lambda A, B, g=g: rbf(A, B, g)
for name, C in [("linear", 1), ("rbf gamma=0.1", 1), ("rbf gamma=1", 1), ("rbf gamma=1", 100), ("rbf gamma=50", 1)]:
k = kernels[name]; a, b = smo(k(Xtr, Xtr), ytr, C)
acc = lambda X_, y_: np.mean(np.sign((a * ytr) @ k(Xtr, X_) + b) == y_)
print(f"{name:<14} C={C:<4} support vectors={np.sum(a > 1e-6):3d}/200 "
f"train acc={acc(Xtr, ytr):.3f} test acc={acc(Xte, yte):.3f}")
Output:
alpha = [0.4444 0.2222 0.2222 0. ] w = [0.6666 0.6666] b = -0.9999 margin = 2.1214
linear C=1 support vectors=199/200 train acc=0.535 test acc=0.537
rbf gamma=0.1 C=1 support vectors= 95/200 train acc=0.985 test acc=0.975
rbf gamma=1 C=1 support vectors= 59/200 train acc=0.980 test acc=0.981
rbf gamma=1 C=100 support vectors= 26/200 train acc=0.995 test acc=0.971
rbf gamma=50 C=1 support vectors=184/200 train acc=1.000 test acc=0.954
The first line reproduces the hand derivation: \(\alpha = (4/9, 2/9, 2/9, 0)\). The linear kernel is at chance on rings, and almost every point becomes a bounded support vector. The RBF kernel solves the problem. Raising \(C\) to 100 trusts the data more (fewer, more decisive support vectors, higher training accuracy, slightly lower test accuracy); \(\gamma = 50\) makes every point its own Gaussian island: perfect training accuracy, the worst test accuracy, and 92% of the data as support vectors.
Next, the scaling escape hatch. Random Fourier features approximate the RBF Gram matrix, and ridge regression on those features reproduces kernel ridge regression:
import numpy as np
rng = np.random.default_rng(1)
gamma, n, d = 0.5, 400, 3
X = rng.normal(size=(n, d))
sq = ((X[:, None, :] - X[None, :, :])**2).sum(-1)
K = np.exp(-gamma * sq) # exact RBF Gram matrix, n x n
def rff(X, D):
"""Random Fourier features (Rahimi & Recht 2007): z(x)·z(y) ≈ exp(-gamma ||x-y||^2)."""
W = rng.normal(0, np.sqrt(2 * gamma), size=(X.shape[1], D)) # spectral density of the RBF
b = rng.uniform(0, 2 * np.pi, D)
return np.sqrt(2 / D) * np.cos(X @ W + b)
for D in (10, 100, 1000, 10000):
Z = rff(X, D)
print(f"D={D:>5}: max |K - ZZ^T| = {np.abs(K - Z @ Z.T).max():.3f} mean = {np.abs(K - Z @ Z.T).mean():.4f}")
# Kernel ridge regression vs ridge on random features: same function, O(n^3) vs O(n D^2)
y = np.sin(X[:, 0]) + 0.1 * rng.normal(size=n)
lam = 1e-2
alpha = np.linalg.solve(K + lam * np.eye(n), y) # representer theorem: f = sum_i alpha_i k(x_i, .)
Z = rff(X, 2000)
w = np.linalg.solve(Z.T @ Z + lam * np.eye(2000), Z.T @ y) # linear ridge in feature space
print("train predictions agree to:", np.abs(K @ alpha - Z @ w).max().round(3))
D= 10: max |K - ZZ^T| = 0.929 mean = 0.1893
D= 100: max |K - ZZ^T| = 0.336 mean = 0.0683
D= 1000: max |K - ZZ^T| = 0.120 mean = 0.0231
D=10000: max |K - ZZ^T| = 0.039 mean = 0.0080
train predictions agree to: 0.037
Each tenfold increase in \(D\) cuts the mean error by about \(\sqrt{10} \approx 3.2\): the \(1/\sqrt{D}\) Monte Carlo rate from the derivation.
Things to try
- Add a fifth point \((1, 1)\) labelled \(-1\) to the worked example and predict, before running, which \(\alpha\)s become non-zero.
- Plot the RBF decision function on a grid for \(\gamma \in \{0.1, 1, 50\}\) and circle the support vectors. Watch the boundary go from nearly circular to a set of islands.
- Implement the polynomial kernel \((\mathbf{x}^\top\mathbf{z} + 1)^2\) and show it also solves the rings (a circle is a degree-2 curve).
- Replace SMO with sub-gradient descent on the primal hinge-loss objective for the linear kernel (Pegasos style) and check you get the same \(\mathbf{w}\).
- Compute the eigenvalues of the Gram matrix for
np.tanh(0.5 * X @ X.T - 1)on random data: find a negative one, and explain why that matters.
Check yourself¶
Why is the margin width 2/‖w‖ and not 1/‖w‖?
The canonical scaling puts the closest points of each class at \(\mathbf{w}^\top\mathbf{x} + b = \pm1\). Each of those planes is \(1/\lVert\mathbf{w}\rVert\) from the decision boundary, so the band between them is \(2/\lVert\mathbf{w}\rVert\) wide. (Some texts call the half-width the margin; the optimiser is the same.)
You delete every training point that is not a support vector and retrain. What happens?
Nothing: you get the same \(\mathbf{w}\) and \(b\). Points with \(\alpha_i = 0\) have no influence on the dual solution, and the KKT conditions still hold without them. This is why SVM models are compact and why the leave-one-out error is bounded by the fraction of support vectors.
Compute k(x, z) for x = (1, 0, 2), z = (2, 1, 1) with the polynomial kernel (xᵀz + 1)² and with an RBF kernel at γ = 0.1.
\(\mathbf{x}^\top\mathbf{z} = 2 + 0 + 2 = 4\), so the polynomial kernel is \((4 + 1)^2 = 25\). \(\lVert\mathbf{x}-\mathbf{z}\rVert^2 = 1 + 1 + 1 = 3\), so the RBF kernel is \(e^{-0.3} \approx 0.741\).
Show that the hinge-loss formulation with λ = 1/(nC) is the same problem as the slack formulation.
For fixed \(\mathbf{w}, b\), the slack problem minimises \(C\sum\xi_i\) subject to \(\xi_i \ge 1 - y_if_i\) and \(\xi_i \ge 0\), so the optimum is \(\xi_i = \max(0, 1 - y_if_i)\). The objective becomes \(\tfrac12\lVert\mathbf{w}\rVert^2 + C\sum_i\max(0, 1-y_if_i)\). Dividing by \(nC\) (which does not change the minimiser) gives \(\frac1n\sum_i\text{hinge}_i + \frac{1}{2nC}\lVert\mathbf{w}\rVert^2\).
Why does logistic regression not produce support vectors, and when might you prefer it to an SVM anyway?
Its loss \(\log(1 + e^{-m})\) is positive for every finite margin, so every point has a non-zero gradient and non-zero dual weight. You might prefer it because it outputs calibrated probabilities directly, has a smooth objective that is easy to optimise with SGD at scale, and degrades gracefully on noisy labels.
Hard: kernel ridge regression costs O(n³). Gaussian process regression with the same kernel gives the same mean prediction. What does the GP give you that kernel ridge does not, and what does it cost?
A predictive variance: \(k(\mathbf{x},\mathbf{x}) - \mathbf{k}(\mathbf{x})^\top(K + \sigma^2I)^{-1}\mathbf{k}(\mathbf{x})\), which grows away from the data. That uncertainty is what makes GPs the standard surrogate in Bayesian optimisation. It also gives a marginal likelihood for choosing kernel hyperparameters without cross-validation. The cost is the same \(O(n^3)\) factorisation (plus \(O(n^2)\) per variance), which is why scalable GPs use inducing points, the Nyström idea again.
Hard: in what precise sense is softmax attention a kernel method, and in what sense is it not?
Each output is a Nadaraya–Watson kernel-weighted average of the values, with an exponential (unnormalised softmax) kernel between query and key. But the kernel's inputs are learned projections \(W_Q\mathbf{x}\) and \(W_K\mathbf{x}\) that change during training and depend on context, there is no convex training problem and no representer theorem, and \(\exp(\mathbf{q}^\top\mathbf{k})\) applied to different query and key maps is not a symmetric PSD kernel on a single input space. The kernel view explains the computation and inspires approximations (Performer), not the learning.
Go deeper¶
Papers
- Support-vector networks — Cortes and Vapnik, Machine Learning, 1995. The soft-margin SVM; still very readable.
- A training algorithm for optimal margin classifiers — Boser, Guyon and Vapnik, COLT 1992. Where maximum margin met the kernel trick.
- A Tutorial on Support Vector Machines for Pattern Recognition — Burges, 1998. The classic tutorial: geometry, duality, VC theory and Mercer in one place.
- Random Features for Large-Scale Kernel Machines — Rahimi and Recht, NeurIPS 2007. Four pages that changed how kernels scale.
- Neural Tangent Kernel: Convergence and Generalization in Neural Networks — Jacot, Gabriel and Hongler, 2018. The bridge from infinitely wide networks to kernel regression.
- Transformer Dissection: A Unified Understanding of Transformer's Attention via the Lens of Kernel — Tsai et al., 2019. Attention rewritten as a kernel smoother.
- Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention — Katharopoulos et al., 2020; and Rethinking Attention with Performers: Choromanski et al., 2020. Kernel feature maps make attention linear in sequence length.
Videos and lectures
- Learning: Support Vector Machines (MIT 6.034) — Patrick Winston. The derivation at a blackboard, with the history of how Vapnik's idea was received.
- Caltech Learning From Data: Lecture 14 (SVMs) and Lecture 15 (Kernel methods) — Yaser Abu-Mostafa. The cleanest pairing of margin and generalisation.
- Support Vector Machines Part 1: Main Ideas, the polynomial kernel and the RBF kernel — StatQuest. Gentle visual intuition first.
Articles and lecture notes
- Cornell CS4780: SVM, Kernels and Kernels continued — Kilian Weinberger. Concise notes with the kernelisation of ordinary algorithms.
- CS229 lecture notes — Andrew Ng et al. The SVM and kernel chapters: Lagrange duality done slowly.
Courses and books
- Gaussian Processes for Machine Learning — Rasmussen and Williams (free). The probabilistic face of kernels; Chapters 2 and 6 connect GPs, RKHS and SVMs.
- The Elements of Statistical Learning — Hastie, Tibshirani and Friedman. Chapter 12 treats the SVM as hinge-loss regularisation, the view taken here.
Code
- LIBSVM — Chang and Lin. The library behind scikit-learn's
SVC. See also scikit-learn SVM guide.
Where this leads¶
- Learning theory: PAC, VC and double descent: the capacity arguments behind "maximise the margin", and why they struggle with deep networks.
- Attention from first principles: attention as a learned, context-dependent kernel smoother.
- Beyond transformers: SSMs, Mamba, linear attention: the random-feature trick, applied to sequence length.
- PCA, t-SNE and UMAP: kernel PCA, and similarity kernels as the engine of t-SNE and UMAP.
- Probabilistic graphical models: Gaussian processes and the Bayesian reading of kernel ridge regression.