Skip to content
BIASED

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 ⟨xi,xj⟩\langle x_i, x_j \rangle. And whatever CC we pick, the boundary is a hyperplane in the original features. As there, the classes are y∈{−1,+1}y \in \{-1, +1\}.

A hyperplane is not always enough. Take XOR, four points in the plane:

  • (1,1)(1, 1) and (−1,−1)(-1, -1) belong to class +1+1;
  • (1,−1)(1, -1) and (−1,1)(-1, 1) belong to class −1-1.

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 φ\varphi sends each object xx to a vector φ(x)\varphi(x) in a richer space, and the model stays linear there: f(x)=⟨w,φ(x)⟩+bf(x) = \langle w, \varphi(x) \rangle + b. For XOR one extra coordinate is enough:

φ(x)=(x1, x2, x1x2).\varphi(x) = (x_1,\ x_2,\ x_1 x_2) .

The third coordinate separates the classes on its own, so w=(0,0,1)w = (0, 0, 1) and b=0b = 0 do the job. A plane in the lifted space becomes a curve in the original one: here the boundary x1x2=0x_1 x_2 = 0 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 pp are the monomials of degree at most pp, and in dd variables there are

(d+pp)\binom{d + p}{p}

of them. For d=100d = 100 and p=3p = 3 that is 176,851176{,}851 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 φ(xi)\varphi(x_i) in place of xix_i in the SVM dual. It is maximized under the same constraints as before:

max⁡α ∑iαi−12∑i,jαiαjyiyj K(xi,xj),0≤αi≤C,∑iαiyi=0,\max_{\alpha}\ \sum_i \alpha_i - \tfrac12 \sum_{i,j} \alpha_i \alpha_j y_i y_j\, K(x_i, x_j), \qquad 0 \le \alpha_i \le C, \quad \sum_i \alpha_i y_i = 0,

and the classifier becomes f(x)=∑iαiyi K(xi,x)+bf(x) = \sum_i \alpha_i y_i\, K(x_i, x) + b. Both need the features only through one function, the kernel:

K(x,x′)=⟨φ(x),φ(x′)⟩.K(x, x') = \langle \varphi(x), \varphi(x') \rangle .

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 KK is cheap although φ\varphi is large. Take x∈R2x \in \mathbb R^2 and φ(x)=(x12, 2 x1x2, x22)\varphi(x) = (x_1^2,\ \sqrt2\, x_1 x_2,\ x_2^2). Then

⟨φ(x),φ(x′)⟩=x12x1′2+2x1x2x1′x2′+x22x2′2=⟨x,x′⟩2.\langle \varphi(x), \varphi(x') \rangle = x_1^2 x_1'^2 + 2 x_1 x_2 x_1' x_2' + x_2^2 x_2'^2 = \langle x, x' \rangle^2 .

For x=(1,2)x = (1, 2) and x′=(3,1)x' = (3, 1) the features give 9+12+4=259 + 12 + 4 = 25, and the shortcut gives (3+2)2=25(3 + 2)^2 = 25. In dd dimensions ⟨x,x′⟩2\langle x, x' \rangle^2 costs dd multiplications, while the explicit features number about d2/2d^2/2.

Back to XOR. Train an SVM with the kernel K(x,x′)=(⟨x,x′⟩+1)2K(x, x') = (\langle x, x' \rangle + 1)^2, whose features include x1x2x_1 x_2 among the monomials up to degree 2. All four points become support vectors with αi=1/8\alpha_i = 1/8 and b=0b = 0, and the sum ∑iαiyiK(xi,x)\sum_i \alpha_i y_i K(x_i, x) collapses to

f(x)=x1x2.f(x) = x_1 x_2 .

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 K(x,x′)=⟨φ(x),φ(x′)⟩K(x, x') = \langle \varphi(x), \varphi(x') \rangle, then for any points x1,…,xmx_1, \dots, x_m and any numbers c1,…,cmc_1, \dots, c_m

∑i,jcicj K(xi,xj)=∥∑iciφ(xi)∥2≥0.\sum_{i,j} c_i c_j\, K(x_i, x_j) = \Big\lVert \sum_i c_i \varphi(x_i) \Big\rVert^2 \ge 0 .

So the Gram matrix Kij=K(xi,xj)K_{ij} = K(x_i, x_j) of any finite set of points is symmetric positive semidefinite. The topic Symmetric matrices and quadratic forms showed this as K=ΦΦ⊤K = \Phi \Phi^\top. 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, KK is a kernel exactly when it is the covariance of a random function: K(x,x′)=Cov⁡(F(x),F(x′))K(x, x') = \operatorname{Cov}(F(x), F(x')). 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 K1K_1 and K2K_2 are kernels, so are:

  • K1+K2K_1 + K_2 and cK1c K_1 for c>0c > 0;
  • the product K1K2K_1 K_2 (the Schur product theorem);
  • g(x) g(x′)g(x)\, g(x') for any real function gg, a rank-one Gram matrix;
  • K1(ψ(x),ψ(x′))K_1(\psi(x), \psi(x')) for any map ψ\psi;
  • 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 ∥x−x′∥\lVert x - x' \rVert 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 −27.5-27.5. The so-called sigmoid kernel tanh⁡(⟨x,x′⟩+1)\tanh(\langle x, x' \rangle + 1) gives −6.26-6.26 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

K(x,x′)=(⟨x,x′⟩+c)p,c≥0.K(x, x') = (\langle x, x' \rangle + c)^p, \qquad c \ge 0 .

By the binomial formula it is a non-negative combination of the kernels ⟨x,x′⟩j\langle x, x' \rangle^j for j=0,…,pj = 0, \dots, p. Its features are all monomials of degree at most pp, the ones counted in the first block. The constant cc sets how much the low degrees weigh against the high ones. For d=100d = 100 and p=3p = 3 it computes an inner product of 176,851176{,}851 features at the price of one inner product in R100\mathbb R^{100} and a cube.

The RBF kernel (Gaussian kernel) is

K(x,x′)=exp⁡(−∥x−x′∥22σ2)=e−∥x∥2/(2σ2) e−∥x′∥2/(2σ2) e⟨x,x′⟩/σ2.K(x, x') = \exp\Big(-\frac{\lVert x - x' \rVert^2}{2\sigma^2}\Big) = e^{-\lVert x \rVert^2/(2\sigma^2)}\, e^{-\lVert x' \rVert^2/(2\sigma^2)}\, e^{\langle x, x' \rangle/\sigma^2} .

The first two factors have the form g(x) g(x′)g(x)\, g(x'), and the last one is the exponential of a kernel. By the rules of the previous block, KK is a kernel. Its Taylor series contains ⟨x,x′⟩j\langle x, x' \rangle^j for every jj, so the feature space is infinite-dimensional. No computer could store φ(x)\varphi(x), yet KK costs one distance.

Every point has ∥φ(x)∥2=K(x,x)=1\lVert \varphi(x) \rVert^2 = K(x, x) = 1. Distances in the feature space follow from the kernel alone:

∥φ(x)−φ(x′)∥2=K(x,x)+K(x′,x′)−2K(x,x′)=2−2K(x,x′).\lVert \varphi(x) - \varphi(x') \rVert^2 = K(x, x) + K(x', x') - 2K(x, x') = 2 - 2K(x, x') .

So the RBF kernel is a similarity that decays with distance on the scale σ\sigma, the bandwidth. A classifier f(x)=∑iαiyi K(xi,x)+bf(x) = \sum_i \alpha_i y_i\, K(x_i, x) + b 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 σ\sigma every point influences the whole space, and the decision function is nearly linear. With a small σ\sigma each point influences only its own neighbourhood, and the boundary can wrap around every training point.

Here are two noisy moons: 600 points, noise 0.30.3, half of them for testing, C=1C = 1. scikit-learn writes the kernel as e−γ∥x−x′∥2e^{-\gamma \lVert x - x' \rVert^2}, so γ=1/(2σ2)\gamma = 1/(2\sigma^2).

γ\gamma σ\sigma 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 0.8530.853 on the same split. A very wide kernel is no better than the line. Around σ≈0.2\sigma \approx 0.2–0.70.7 the RBF SVM gains three points. A very narrow kernel memorizes the training set: train accuracy 11, 299 of 300 points are support vectors, and the test accuracy falls to 0.6530.653. The number of support vectors is smallest where the test accuracy is highest.

This is the same bias–variance picture as kk in the topic Nearest neighbours. In practice σ\sigma and CC 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 σ\sigma suits all of them.

The representer theorem

Why does the SVM solution have the form w=∑iαiyiφ(xi)w = \sum_i \alpha_i y_i \varphi(x_i), one coefficient per training point, even when φ\varphi is infinite-dimensional? The reason has nothing to do with the hinge loss. Take any regularized problem

min⁡w ∑i=1nL(yi, ⟨w,φ(xi)⟩)+λ∥w∥2,λ>0.\min_{w}\ \sum_{i=1}^n L\big(y_i,\ \langle w, \varphi(x_i) \rangle\big) + \lambda \lVert w \rVert^2, \qquad \lambda > 0 .

Split w=w∥+w⊥w = w_\parallel + w_\perp, where w∥w_\parallel lies in the span of φ(x1),…,φ(xn)\varphi(x_1), \dots, \varphi(x_n) and w⊥w_\perp is orthogonal to all of them. The training predictions see only w∥w_\parallel, because ⟨w⊥,φ(xi)⟩=0\langle w_\perp, \varphi(x_i) \rangle = 0. The penalty sees both: ∥w∥2=∥w∥∥2+∥w⊥∥2\lVert w \rVert^2 = \lVert w_\parallel \rVert^2 + \lVert w_\perp \rVert^2. Dropping w⊥w_\perp keeps the loss and lowers the penalty, so every minimizer has w⊥=0w_\perp = 0:

w=∑i=1nαiφ(xi),f(x)=⟨w,φ(x)⟩=∑i=1nαi K(xi,x).\begin{aligned} w &= \sum_{i=1}^n \alpha_i \varphi(x_i), \\ f(x) &= \langle w, \varphi(x) \rangle = \sum_{i=1}^n \alpha_i\, K(x_i, x) . \end{aligned}

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 nn numbers, and it holds for every loss: squared, logistic, hinge. With this form, the penalty is ∥w∥2=α⊤Kα\lVert w \rVert^2 = \alpha^\top K \alpha and the vector of training predictions is KαK\alpha, where KK is the Gram matrix.

Kernel ridge regression

With the squared loss the problem is ridge regression in the feature space. Let the rows of Φ\Phi be φ(xi)⊤\varphi(x_i)^\top. The topic Regularization gave the solution w=(Φ⊤Φ+λI)−1Φ⊤yw = (\Phi^\top \Phi + \lambda I)^{-1} \Phi^\top y. Multiply the identity Φ⊤(ΦΦ⊤+λI)=(Φ⊤Φ+λI)Φ⊤\Phi^\top (\Phi \Phi^\top + \lambda I) = (\Phi^\top \Phi + \lambda I) \Phi^\top by both inverses, and the solution takes a second form:

w=(Φ⊤Φ+λI)−1Φ⊤y=Φ⊤(ΦΦ⊤+λI)−1y.w = (\Phi^\top \Phi + \lambda I)^{-1} \Phi^\top y = \Phi^\top (\Phi \Phi^\top + \lambda I)^{-1} y .

The left form inverts a matrix as large as the feature space, the right one an n×nn \times n matrix, and ΦΦ⊤=K\Phi \Phi^\top = K is the Gram matrix. So w=∑iαiφ(xi)w = \sum_i \alpha_i \varphi(x_i), exactly as the representer theorem promised, with

α=(K+λI)−1y,f(x)=∑i=1nαi K(xi,x).\alpha = (K + \lambda I)^{-1} y, \qquad f(x) = \sum_{i=1}^n \alpha_i\, K(x_i, x) .

This is kernel ridge regression. A small example: two training points x=0x = 0 and x=1x = 1 with targets 11 and 22, the RBF kernel with σ=1\sigma = 1, and λ=0.1\lambda = 0.1. The kernel between the points is e−1/2=0.6065e^{-1/2} = 0.6065, so

K+λI=(1.10.60650.60651.1),α=(K+λI)−1(12)=(−0.13431.8922).K + \lambda I = \begin{pmatrix} 1.1 & 0.6065 \\ 0.6065 & 1.1 \end{pmatrix}, \qquad \alpha = (K + \lambda I)^{-1} \begin{pmatrix} 1 \\ 2 \end{pmatrix} = \begin{pmatrix} -0.1343 \\ 1.8922 \end{pmatrix} .

At x=0.5x = 0.5 both kernel values are e−1/8=0.8825e^{-1/8} = 0.8825, and f(0.5)=0.8825⋅(−0.1343+1.8922)=1.5514f(0.5) = 0.8825 \cdot (-0.1343 + 1.8922) = 1.5514. The same by hand and in scikit-learn, whose alpha argument is our λ\lambda:

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 x=3x = 3 the prediction is 0.25460.2546. 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 1.0131.013 and 1.8111.811, not 11 and 22: with λ>0\lambda > 0 it smooths rather than interpolates.

The Gaussian reading of the previous blocks pays off here. Let FF be a random function with covariance KK, observed with Gaussian noise. The conditional mean of F(x)F(x) given the data, by the formula from The multivariate Gaussian, is exactly the kernel ridge prediction, with λ\lambda the ratio of the noise variance to the scale of KK. 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 xx.

The bill and random features

Kernel methods trade the number of features for the number of objects. The Gram matrix costs O(n2d)O(n^2 d) time and O(n2)O(n^2) memory. Solving (K+λI)α=y(K + \lambda I)\alpha = y costs O(n3)O(n^3), and SVM solvers take between O(n2)O(n^2) and O(n3)O(n^3) in practice. Each prediction needs one kernel value per support vector or training point. For n=100,000n = 100{,}000 the Gram matrix alone has 101010^{10} 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 x−x′x - x', with K(0)=1K(0) = 1, is positive semidefinite exactly when it is an expectation over some probability distribution pp,

K(x−x′)=Eω∼pcos⁡⟨ω,x−x′⟩.K(x - x') = \mathbb E_{\omega \sim p} \cos \langle \omega, x - x' \rangle .

For the RBF kernel pp is the Gaussian N(0,σ−2I)\mathcal N(0, \sigma^{-2} I). Draw ω1,…,ωD\omega_1, \dots, \omega_D from pp and b1,…,bDb_1, \dots, b_D uniformly from [0,2π][0, 2\pi], and set

z(x)=2/D (cos⁡(⟨ω1,x⟩+b1),…,cos⁡(⟨ωD,x⟩+bD)).z(x) = \sqrt{2/D}\, \big(\cos(\langle \omega_1, x \rangle + b_1), \dots, \cos(\langle \omega_D, x \rangle + b_D)\big) .

Then ⟨z(x),z(x′)⟩\langle z(x), z(x') \rangle is an average of DD independent terms whose mean is K(x,x′)K(x, x'): a Monte Carlo estimate of the kernel (the topic Monte Carlo methods). On 300 points in R5\mathbb R^5, the largest error over the whole 300×300300 \times 300 Gram matrix is:

DD 10 100 1000 10000
largest error 1.118 0.343 0.101 0.035

Any linear method trained on z(x)z(x) then approximates the kernel method, at a cost linear in nn. On the moons of the bandwidth block, a linear SVM on just D=10D = 10 random features reaches 0.880.88, the accuracy of the exact RBF SVM with γ=1\gamma = 1.

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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.