The Kernel Trick
Nonlinear patterns with linear algebra.
No straight line separates a ring of points from the cluster inside it. Add one feature, the squared distance from the center, and a flat plane does. Kernels make this lifting free: any algorithm that touches its data only through inner products can run in an enormous, even infinite-dimensional, feature space at the cost of evaluating one function on pairs of points.
What you’ll learn
- Define feature maps and kernels, and show that the polynomial kernel and the RBF kernel are inner products in feature spaces of dimension and .
- Prove that every Gram matrix is positive semidefinite, and build new kernels from old ones with the closure rules.
- Kernelize an algorithm that uses its data only through inner products: derive kernel ridge regression, , and outline the kernel SVM and kernel PCA.
- Weigh the cost of exact kernel methods against explicit features, and choose a kernel, its width and the regularization by cross-validation.
Lifting data until a line works
Label the points of a disk and the points of a ring around it (labels in , as for SVMs). In the plane no line separates them: every line leaves ring points on the disk's side. Now send each point to three coordinates,
The third coordinate is the squared distance from the center: small on the disk, large on the ring. A horizontal plane at height , for a radius between the disk and the ring, now separates the classes, and back in the input plane it is the circle . A linear boundary in feature space is a nonlinear boundary in input space.
This is the basis-function idea of Feature Maps & the Road to Kernels: choose a feature map and fit a linear model to the features. The catch is size. To let the boundary be any polynomial of degree , you need every monomial with , and there are of them.
With inputs, how many thousand monomials of degree at most are there?
Show the answer
177 thousand
. A degree-5 expansion of the same inputs has features. Storing and fitting such vectors soon becomes the bottleneck, yet the next step computes the inner product of two of them with about 100 multiplications.
Inner products without the features
Many learning algorithms see their inputs only through inner products : the SVM dual, ridge regression in its dual form, PCA through the Gram matrix, the perceptron, the distances of k-means. Run on features, they need only . A kernel is a function that returns this number directly:
The kernel trick is to evaluate instead of forming , which pays off whenever is cheap and is huge.
Square an inner product and expand. The result is an inner product of the pairwise products:
Add the constant 1 and take . Six features appear, one per monomial of degree at most 2, with weights that make the cross terms come out right:
In general the multinomial theorem gives one feature per monomial of degree at most (the exponent belongs to the constant 1), so the polynomial kernel is an inner product in dimensions that costs to evaluate:
Think first Take and . Compute directly, then as with the six features above.
, so the kernel gives . The features are and , and their inner product is . Same number, but the kernel needed an inner product of length 2 instead of building two vectors of length 6.
The Gaussian RBF kernel , the default choice in practice, goes further: its feature space is infinite-dimensional. Writing makes its length scale explicit: points much farther apart than have .
Expand the squared distance, , and split the exponential:
The last factor is a power series with positive coefficients: a weighted sum of polynomial kernels of every degree.
So the features are all monomials of all degrees, damped by . In one dimension they can be written out, one per power of :
Which functions are kernels?
For points , the Gram matrix collects all pairwise kernel values, . It plays the role that plays for linear methods, and it has a defining property.
| If are kernels, so is | Why | Example |
|---|---|---|
| for | scale the features by | the signal variance in front of a GP kernel |
| concatenate the two feature vectors | linear + RBF: a global trend plus local bumps | |
| features are all products ; for Gram matrices, the Schur product theorem | ||
| for any | features | normalizing: |
| for any map | features | an RBF kernel on standardized inputs or on learned embeddings |
| , or any power series in with nonnegative coefficients | limits of sums and products |
Kernels also free you from vectors. A string kernel compares two documents or DNA sequences by the substrings they share, a graph kernel compares molecules by their walks or subtrees, a set kernel compares bags of items. Anything with a positive semidefinite similarity can be handed to an SVM or a Gaussian process.
Which of these is not a valid kernel on ?
Show the answer
C.
For two distinct points the Gram matrix is with . Its eigenvalues are , and gives , impossible for a squared norm. A distance measures dissimilarity; kernels measure similarity.
Kernelizing an algorithm
Turning a linear method into a kernel method takes three moves: show that the solution is a combination of the training features, ; rewrite everything in terms of inner products; replace every inner product by . Ridge regression is the cleanest case.
Ridge regression in feature space, with the matrix whose rows are the :
The push-through identity of Ridge Regression in Depth, , moves the inverse onto an matrix, and is exactly the Gram matrix:
Predictions need only the kernel values between the new point and the training points, :
has disappeared. With the RBF kernel the fit is a weighted sum of Gaussian bumps centered on the training points, and trades fitting the labels against the size of the weights. As (with invertible, as it is for the RBF kernel on distinct points) the fit interpolates the data:
import numpy as np
def rbf(A, B, gamma):
# squared distances between the rows of A and the rows of B
sq = (A**2).sum(1)[:, None] + (B**2).sum(1)[None, :] - 2 * A @ B.T
return np.exp(-gamma * np.maximum(sq, 0.0))
def krr_fit(X, y, gamma, lam):
K = rbf(X, X, gamma) # n x n Gram matrix
return np.linalg.solve(K + lam * np.eye(len(X)), y) # alpha: O(n^3)
def krr_predict(X_train, alpha, X_new, gamma):
return rbf(X_new, X_train, gamma) @ alpha # sum_i alpha_i k(x_i, x)The whole method in a dozen lines: time and memory for the Gram matrix, for the solve, per prediction. scikit-learn's KernelRidge(alpha=lam, kernel='rbf', gamma=gamma) fits the same estimator; its alpha is this lesson's .
| Algorithm | Sees the data through | Kernelized solution |
|---|---|---|
| Ridge regression | , in its dual form | with |
| Support vector machine | in the dual | , with only for the support vectors |
| PCA | the Gram matrix of centered data | eigenvectors of , ; each component is a kernel expansion (after centering) |
| Perceptron | , where counts the mistakes made on example | |
| Gaussian process regression | covariances of function values | posterior mean , which is kernel ridge regression with , plus an error bar |
Cost, and choosing the kernel
Exact kernel methods trade the feature dimension for the number of examples :
| Cost | Explicit features (primal) | Kernel (dual) |
|---|---|---|
| Training | ||
| Memory | ||
| One prediction | ; for an SVM, only the support vectors count | |
| Best when | , or |
How many gigabytes does the Gram matrix of training points take in double precision (8 bytes per entry)?
Show the answer
80 GB
entries times 8 bytes is bytes, 80 GB, before the solve of about operations even starts. Symmetry halves the storage, but the scaling is the real problem: ten times more data costs a hundred times the memory and a thousand times the time.
Choosing a kernel is choosing an inductive bias: whatever the kernel calls similar, the model treats alike. Practical rules:
- Standardize the inputs. The RBF and polynomial kernels use Euclidean geometry, so a feature measured in thousands drowns one measured in fractions.
- The width is a bias–variance knob. As every pair of points looks alike, approaches the all-ones matrix, and the fit flattens: underfitting. As , and each training point becomes an isolated spike: the model memorizes and predicts about zero elsewhere.
- Start from the median heuristic, equal to the median distance between training points, then search together with (or the SVM's ) on a logarithmic grid by cross-validation.
- Encode what you know. Periodicity, additive structure, invariances or a known roughness can be built into the kernel (Kernel Design for Gaussian Processes), and Gaussian processes can fit kernel parameters by maximizing the marginal likelihood.
Key takeaways
- A kernel is an inner product of feature maps, . The polynomial kernel hides monomials and costs ; the RBF kernel hides infinitely many features.
- A symmetric function is a kernel exactly when all its Gram matrices are positive semidefinite. Sums, products, nonnegative scalings and exponentials of kernels are kernels, and so is a kernel evaluated on transformed inputs, .
- Kernelizing: write and replace inner products by . Kernel ridge regression has and ; the SVM, PCA, the perceptron and Gaussian processes follow the same pattern.
- Exact kernel methods cost memory and time. Use the kernel when features outnumber examples, explicit (or approximate) features when examples dominate.
- Standardize the inputs, then choose the kernel, its width and or by cross-validation: small underfits, large memorizes.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A polynomial kernel is used on inputs. How large is its feature space, and what does one kernel evaluation cost?
- features, and an evaluation must form them: about 125,000 multiplications
- features, but one evaluation costs about 50 multiplications
- features, about 150 multiplications
- Infinitely many features, so the kernel can only be approximated
Show the answer
B. features, but one evaluation costs about 50 multiplications
The features are the monomials of degree at most 3 in 50 variables, of them. The kernel never forms them: it computes (50 multiplications), adds 1 and cubes.
Why is every Gram matrix of a valid kernel positive semidefinite?
- Because , a squared length, which cannot be negative
- Because all its entries are nonnegative
- Because it is symmetric
- Because every principal submatrix has a nonnegative determinant
Show the answer
A. Because , a squared length, which cannot be negative
A quadratic form in the Gram matrix is the squared norm of a combination of feature vectors. That is the whole proof, and it is why the converse (Moore–Aronszajn) is the natural definition of a kernel.
After fitting kernel ridge regression with an RBF kernel on points, what do you need to predict at a new input ?
- The weight vector in feature space
- Only the support vectors, since most coefficients are zero
- The coefficients and the kernel values for all training points
- A new solve of that includes
Show the answer
C. The coefficients and the kernel values for all training points
: the coefficients are computed once, in , and each prediction is a weighted sum costing .
You fit RBF kernel ridge regression with a so large that for every pair of distinct training points. What does the model do?
- It fits a nearly straight line
- It returns about at each training point and about 0 everywhere else
- It becomes linear regression on the raw inputs
- It fails, because becomes singular
Show the answer
B. It returns about at each training point and about 0 everywhere else
With , and is a row of narrow spikes, one per training point. The training labels are reproduced (shrunk), and away from the data the prediction collapses to 0: overfitting in its purest form.
You have examples with inputs and want a degree-2 polynomial model. Which route makes sense?
- The kernel trick, because it avoids forming features
- Either: the two routes cost about the same
- Neither: a degree-2 model needs
- Explicit features: there are only , so a linear fit costs about operations, while the Gram matrix alone would have entries
Show the answer
D. Explicit features: there are only , so a linear fit costs about operations, while the Gram matrix alone would have entries
The kernel trick wins when features outnumber examples. Here : the primal fit is cheap, while the dual's matrix needs about 32 TB in double precision and its solve about operations.
Go deeper
- Reproducing Kernel Hilbert Spaces · Mercer’s theorem, the representer theorem and kernel norms.
- Scaling Kernel Methods · Nyström approximation and random Fourier features.
- Kernel Mean Embeddings & Two-Sample Tests · Comparing distributions with kernels: the MMD.
Further reading
- B. Schölkopf & A. J. Smola, Learning with Kernels (MIT Press, 2002).
- T. Hofmann, B. Schölkopf & A. J. Smola, "Kernel methods in machine learning," Annals of Statistics 36(3), 1171–1220 (2008).
- B. E. Boser, I. M. Guyon & V. N. Vapnik, "A training algorithm for optimal margin classifiers," Proceedings of the 5th Annual Workshop on Computational Learning Theory (COLT), 144–152 (1992).
- B. Schölkopf, A. Smola & K.-R. Müller, "Nonlinear component analysis as a kernel eigenvalue problem," Neural Computation 10(5), 1299–1319 (1998).