Kernels
Linear methods on nonlinear features without computing the features — feature maps, the kernel trick in the SVM dual, positive semidefinite kernels and the rules for building them, the polynomial and RBF kernels, the bandwidth as a bias–variance knob, the representer theorem, kernel ridge regression, the cost and random Fourier features.
Lifting the data
The topic Support vector machines ended with two facts. Its dual problem and its classifier touch the training points only through inner products . And whatever we pick, the boundary is a hyperplane in the original features. As there, the classes are .
A hyperplane is not always enough. Take XOR, four points in the plane:
- and belong to class ;
- and belong to class .
No line separates them, and a linear SVM gets two of the four right.
The fix is to give the linear model better features. A feature map sends each object to a vector in a richer space, and the model stays linear there: . For XOR one extra coordinate is enough:
The third coordinate separates the classes on its own, so and do the job. A plane in the lifted space becomes a curve in the original one: here the boundary is the pair of coordinate axes.
In general we do not know which product to add, so we add them all. All products of features up to degree are the monomials of degree at most , and in variables there are
of them. For and that is features per object, each with its own weight. Writing them down quickly becomes the bottleneck. This topic shows how to use them without ever writing them down.
The kernel trick
Put in place of in the SVM dual. It is maximized under the same constraints as before:
and the classifier becomes . Both need the features only through one function, the kernel:
Replacing every inner product of a linear method by a kernel is the kernel trick (Boser, Guyon and Vapnik, 1992). The topic Duality of Mathematics for ML already hinted at it. It works for any method written through inner products: ridge regression later in this topic, PCA in the topic Dimensionality reduction, the one-class SVM in Anomaly detection.
It pays off when is cheap although is large. Take and . Then
For and the features give , and the shortcut gives . In dimensions costs multiplications, while the explicit features number about .
Back to XOR. Train an SVM with the kernel , whose features include among the monomials up to degree 2. All four points become support vectors with and , and the sum collapses to
The kernel SVM found the product feature by itself, without anyone writing it down.
Which functions are kernels
Can any similarity function serve as a kernel? No. If , then for any points and any numbers
So the Gram matrix of any finite set of points is symmetric positive semidefinite. The topic Symmetric matrices and quadratic forms showed this as . The converse holds too: a symmetric function whose Gram matrices are all positive semidefinite is an inner product after some feature map into a Hilbert space (Aronszajn, 1950; Mercer's theorem builds that map explicitly for continuous kernels). Such functions are positive semidefinite kernels. They are exactly what the kernel trick may use; with any other function the SVM dual stops being concave, and its solution loses its meaning.
There is a probabilistic reading. A positive semidefinite matrix is exactly a covariance matrix (the topic The multivariate Gaussian). In the same way, is a kernel exactly when it is the covariance of a random function: . A kernel says how strongly the values of an unknown function at two inputs move together. The course Bayesian Methods in Machine Learning builds on this in the topic Gaussian processes.
Checking the definition directly is hard, so kernels are built from simpler ones. If and are kernels, so are:
- and for ;
- the product (the Schur product theorem);
- for any real function , a rank-one Gram matrix;
- for any map ;
- a pointwise limit of kernels.
So polynomials of a kernel with non-negative coefficients are kernels, and so is its exponential, a limit of such polynomials.
Some natural similarities fail. The distance has zeros on the diagonal of its Gram matrix. Its eigenvalues sum to the trace, which is zero, so one of them is negative unless all points coincide. On 50 random points in the plane the smallest eigenvalue is . The so-called sigmoid kernel gives on the same points, while the Gaussian kernel of the next block stays at zero up to rounding.
Polynomial and RBF kernels
The polynomial kernel is
By the binomial formula it is a non-negative combination of the kernels for . Its features are all monomials of degree at most , the ones counted in the first block. The constant sets how much the low degrees weigh against the high ones. For and it computes an inner product of features at the price of one inner product in and a cube.
The RBF kernel (Gaussian kernel) is
The first two factors have the form , and the last one is the exponential of a kernel. By the rules of the previous block, is a kernel. Its Taylor series contains for every , so the feature space is infinite-dimensional. No computer could store , yet costs one distance.
Every point has . Distances in the feature space follow from the kernel alone:
So the RBF kernel is a similarity that decays with distance on the scale , the bandwidth. A classifier with this kernel is a weighted vote of the support vectors in which the nearby ones count most. It is a smooth relative of the topic Nearest neighbours, with the weights fitted by maximizing the margin.
The bandwidth as a bias–variance knob
The bandwidth decides how far each training point reaches. With a large every point influences the whole space, and the decision function is nearly linear. With a small each point influences only its own neighbourhood, and the boundary can wrap around every training point.
Here are two noisy moons: 600 points, noise , half of them for testing, . scikit-learn writes the kernel as , so .
| train accuracy | test accuracy | support vectors | ||
|---|---|---|---|---|
| 0.01 | 7.07 | 0.843 | 0.827 | 198 |
| 0.1 | 2.24 | 0.883 | 0.850 | 125 |
| 1 | 0.71 | 0.937 | 0.880 | 79 |
| 10 | 0.22 | 0.940 | 0.883 | 126 |
| 100 | 0.07 | 0.990 | 0.857 | 256 |
| 1000 | 0.02 | 1.000 | 0.653 | 299 |
The linear SVM reaches on the same split. A very wide kernel is no better than the line. Around – the RBF SVM gains three points. A very narrow kernel memorizes the training set: train accuracy , 299 of 300 points are support vectors, and the test accuracy falls to . The number of support vectors is smallest where the test accuracy is highest.
This is the same bias–variance picture as in the topic Nearest neighbours. In practice and are tuned together by cross-validation (the topic Validation and overfitting), on logarithmic grids. Standardize the features first (the topic Data, features and leakage), so that one suits all of them.
The representer theorem
Why does the SVM solution have the form , one coefficient per training point, even when is infinite-dimensional? The reason has nothing to do with the hinge loss. Take any regularized problem
Split , where lies in the span of and is orthogonal to all of them. The training predictions see only , because . The penalty sees both: . Dropping keeps the loss and lowers the penalty, so every minimizer has :
This is the representer theorem (Kimeldorf and Wahba, 1971; Schölkopf, Herbrich and Smola, 2001). It turns a search in an infinite-dimensional space into a search over numbers, and it holds for every loss: squared, logistic, hinge. With this form, the penalty is and the vector of training predictions is , where is the Gram matrix.
Kernel ridge regression
With the squared loss the problem is ridge regression in the feature space. Let the rows of be . The topic Regularization gave the solution . Multiply the identity by both inverses, and the solution takes a second form:
The left form inverts a matrix as large as the feature space, the right one an matrix, and is the Gram matrix. So , exactly as the representer theorem promised, with
This is kernel ridge regression. A small example: two training points and with targets and , the RBF kernel with , and . The kernel between the points is , so
At both kernel values are , and . The same by hand and in scikit-learn, whose alpha argument is our :
import numpy as np
from sklearn.kernel_ridge import KernelRidge
X = np.array([[0.0], [1.0]])
y = np.array([1.0, 2.0])
rbf = lambda A, B: np.exp(-(A - B.T) ** 2 / 2) # sigma = 1
alpha = np.linalg.solve(rbf(X, X) + 0.1 * np.eye(2), y)
X_new = np.array([[0.5], [3.0]])
print(alpha.round(4))
print((rbf(X_new, X) @ alpha).round(4))
model = KernelRidge(alpha=0.1, kernel="rbf", gamma=0.5).fit(X, y)
print(model.predict(X_new).round(4))[-0.1343 1.8922]
[1.5514 0.2546]
[1.5514 0.2546]At the prediction is . Far from the data an RBF regressor returns to zero, whatever the trend, so it does not extrapolate. At the training points themselves the fit is and , not and : with it smooths rather than interpolates.
The Gaussian reading of the previous blocks pays off here. Let be a random function with covariance , observed with Gaussian noise. The conditional mean of given the data, by the formula from The multivariate Gaussian, is exactly the kernel ridge prediction, with the ratio of the noise variance to the scale of . Just as ridge regression is a MAP estimate, kernel ridge regression is the posterior mean of Gaussian process regression. The topic Gaussian processes of Bayesian Methods in Machine Learning adds what ridge lacks: an error bar at every .
The bill and random features
Kernel methods trade the number of features for the number of objects. The Gram matrix costs time and memory. Solving costs , and SVM solvers take between and in practice. Each prediction needs one kernel value per support vector or training point. For the Gram matrix alone has entries, 80 GB in double precision. So exact kernel methods rule small and medium data and lose to linear models, trees and networks on large data.
Rahimi and Recht (2007) went back to explicit features, but few and random. Their tool is Bochner's theorem: a continuous kernel that depends only on , with , is positive semidefinite exactly when it is an expectation over some probability distribution ,
For the RBF kernel is the Gaussian . Draw from and uniformly from , and set
Then is an average of independent terms whose mean is : a Monte Carlo estimate of the kernel (the topic Monte Carlo methods). On 300 points in , the largest error over the whole Gram matrix is:
| 10 | 100 | 1000 | 10000 | |
|---|---|---|---|---|
| largest error | 1.118 | 0.343 | 0.101 | 0.035 |
Any linear method trained on then approximates the kernel method, at a cost linear in . On the moons of the bandwidth block, a linear SVM on just random features reaches , the accuracy of the exact RBF SVM with .
One limit remains: the kernel, like any feature map, is chosen before seeing the data. Networks will learn their features instead, starting with the topic From linear models to networks. But first, a different gap. The SVM and its kernels separate two classes, while digits come in ten and an article can carry several topics at once. The next topic, Multiclass and multilabel classification, handles both.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.