Kernel methods and non-linear SVMs
The kernel trick: linear algorithms in huge feature spaces without ever computing the features.
Animated explanation
The idea
Some classes cannot be split by a line: a ring around a core, a checkerboard. But add the right new features and they can. For a ring, the squared distance from the centre does it: in that feature, one threshold separates the classes, which is a circle back in the original plane.
The SVM dual only ever uses dot products between points. A kernel computes the dot product of two points in some feature space directly, often without that space being written down at all. Swap the dot product for a kernel and the linear SVM becomes a non-linear one, at no extra cost in the number of parameters.
Why the trick is cheap
The degree-2 polynomial kernel equals the dot product of all pairwise products : features, computed in . The RBF kernel corresponds to an infinite-dimensional feature space, yet costs one exponential. The price moves elsewhere: kernel methods need the Gram matrix, so training scales like to .
Tuning C and γ
For the RBF kernel, sets how far one training point's influence reaches. Small : smooth, nearly linear boundaries (bias). Large : each support vector becomes its own little island (variance). interacts with it, so search both on a logarithmic grid, e.g. and , with cross-validation, on standardised features.
Kernels beyond SVMs
Any algorithm written in terms of dot products can be kernelised: kernel ridge regression, kernel PCA, Gaussian processes, spectral clustering. For very large datasets, random Fourier features or the Nyström method approximate the kernel with explicit features so linear solvers can be used.
The algorithm, step by step
- 1Standardise features and choose a kernel (RBF by default).
- 2Build the Gram matrix (or compute entries on demand).
- 3Solve the dual: maximise subject to , .
- 4Predict , summing over support vectors only.
The maths
Kernelised decision function
RBF kernel
Polynomial kernel
Explicit degree-2 map in 2-D
Strengths and weaknesses
Strengths
- Flexible non-linear boundaries with a convex problem
- Works with any similarity, including strings and graphs
- Strong accuracy on small and medium datasets
Weaknesses
- Gram matrix: memory and time grow quadratically or worse with n
- Two hyperparameters to tune jointly
- Harder to interpret than linear models
Reach for it when…
Check your understanding
Lambdian Lab
Kernels and the Gram matrix
Build kernels and verify the kernel trick, then use scikit-learn's SVC with your own kernel.
- rbf_kernel(A, B, gamma) → matrix .
- poly2_features(X): the explicit degree-2 map for 2-D inputs.
- poly2_kernel(A, B) = ; it must equal poly2_features(A) @ poly2_features(B).T.
- best_gamma(X_tr, y_tr, X_va, y_va, gammas): fit SVC(kernel="precomputed", C=1) with your RBF Gram matrices; return the γ with the best validation accuracy.