13 / 27 · Linear Classification
Kernels
Linear methods on nonlinear features without computing the features: feature maps and the kernel trick in the SVM dual, which functions are kernels (positive semidefinite kernels, Mercer, the rules for building new ones), the polynomial and RBF kernels and the RBF bandwidth as a bias–variance knob, the representer theorem and kernel ridge regression, the quadratic-to-cubic cost and random Fourier features as its remedy.
Support vector machines · Regularization · The multivariate Gaussian · Expectation
On this page 14
The support vector machines note ended with two observations. The dual problem and the resulting classifier use the training points only through inner products , and the margin bound does not depend on the dimension. A linear classifier on the raw features still draws a hyperplane, and two concentric rings defeat it. This note replaces the raw features by a richer representation and the inner product by a kernel that can be computed without ever forming . The same quadratic program then draws curved boundaries, and the same idea turns ridge regression into a flexible nonparametric regressor. The price is paid in the number of training points instead of the number of features, and the end of the note shows how to pay less.
Notation. Training points with targets . A feature map sends a point to a vector in a space with an inner product, possibly of infinite dimension. A kernel is a function ; the Gram matrix is the matrix with entries , and collects the kernel values of a new point against the training points. is the RBF bandwidth and the ridge penalty.
Feature maps#
A linear model becomes nonlinear in when it is linear in nonlinear features of . Points on a line with one class in the middle cannot be split by one threshold, but after they lie on a parabola, where a line splits them:
A feature map makes the classes linearly separable
The line in the lifted plane is a quadratic inequality in , which holds between two thresholds. In general one would add all products of features up to some degree . The number of monomials of degree at most in variables is : for and it is . Writing these features down for every training point, and fitting a weight to each, quickly becomes the bottleneck.
The kernel trick in the dual#
The SVM never needs the features themselves. Its dual, with in place of , reads
and the classifier is , with for any support vector on the margin. Both need only . Replacing every inner product of a linear method by a kernel is the kernel trick (Boser, Guyon and Vapnik, 1992); it works for any method that can be written in terms of inner products, from the SVM and ridge regression to PCA and -means.
The saving comes from kernels that are cheap to evaluate although is large. For and ,
Worked example. For and : , , and . The kernel costs one inner product in and a square; in dimensions costs multiplications against for the explicit features. The feature map of the figure, , has the kernel .
Which functions are kernels#
Not every similarity function is an inner product in some space. If , then for any points and any real numbers ,
So the Gram matrix of a kernel on any finite set of points is symmetric and positive semidefinite. The converse also holds: a symmetric function whose Gram matrices are all positive semidefinite is the inner product of some feature map into a Hilbert space, the reproducing kernel Hilbert space (RKHS) of (Aronszajn, 1950; Shalev-Shwartz and Ben-David, 2014, Lemma 16.2). Such functions are called positive semidefinite kernels, and they are exactly the functions the kernel trick may use. Mercer’s theorem gives the feature map explicitly for a continuous kernel on a compact domain: with eigenvalues and orthonormal eigenfunctions , so (Rasmussen and Williams, 2006, §4.3).
The condition is familiar from probability. A matrix is positive semidefinite exactly when it is the covariance matrix of some random vector, because (see covariance). In the same way, is a positive semidefinite kernel exactly when it is the covariance function of a random function: for a Gaussian process . A kernel says how strongly the values of an unknown function at two inputs are correlated; this reading returns in kernel ridge regression.
Checking the definition directly is often hard, so kernels are usually built from simpler ones by rules that preserve positive semidefiniteness. If and are kernels, so are:
- and for : sums and positive multiples of positive semidefinite matrices are positive semidefinite;
- : the elementwise product of positive semidefinite matrices is positive semidefinite (the Schur product theorem), or, with features, ;
- for any real function : a rank-one Gram matrix ;
- for any map ;
- the pointwise limit of kernels, because each inequality survives the limit.
Polynomials with non-negative coefficients of a kernel, and its exponential (a limit of such polynomials), are therefore kernels too (Bishop, 2006, §6.2).
Some natural similarities fail. The distance has zeros on the diagonal of its Gram matrix, so the eigenvalues sum to the trace, 0, and unless all points coincide one of them is negative. For two points at 0 and 1 the Gram matrix is with eigenvalues . On 50 random points in the plane its smallest eigenvalue is ; the “sigmoid kernel” gives , while the RBF kernel stays at up to rounding. With such a function the SVM dual is no longer concave and its solution loses its meaning.
Common kernels: polynomial and RBF#
The polynomial kernel with expands by the binomial formula into , a non-negative combination of the kernels . Its features are all monomials of degree at most , the monomial of degree weighted by , where the multinomial coefficient comes from expanding ; controls how much the low degrees count relative to the high ones.
The RBF (Gaussian) kernel is
The first two factors are and the last is the exponential of a kernel, so by the rules above it is a kernel. Its Taylor series contains for every , so its feature space has infinite dimension: no explicit could be stored, yet costs one distance. Every point has , and the squared distance between two points in feature space is : the RBF kernel is a similarity that decays with distance on the scale . A classifier with this kernel is a weighted vote of the support vectors in which nearby ones count most, a smooth relative of nearest neighbours with weights fitted by margin maximization.
The bandwidth as bias–variance. A large makes every training point influence the whole space, and the decision function is nearly linear; a small makes each point influence only its immediate neighbourhood, and the function can wrap around every training point. On two noisy moons (600 points, noise 0.3, half 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 . With a very wide kernel the RBF SVM is no better than the line; around – it gains three points; with a very narrow kernel it memorizes the training set (accuracy 1, 299 of 300 points are support vectors) and drops to on the test set. The number of support vectors is lowest where the test accuracy is highest. and are tuned together by cross-validation, on logarithmic grids, after standardizing the features so that one suits all of them.
The representer theorem#
Why does the solution of the SVM have the form , with one coefficient per training point, even when is infinite-dimensional? The reason is not specific to the hinge loss. Consider any regularized problem
Split , where lies in the span of and is orthogonal to all of them. The predictions on the training points depend only on , because , while . Dropping keeps the loss and strictly lowers the penalty when , so every minimizer has :
This is the representer theorem (Kimeldorf and Wahba, 1971; Schölkopf, Herbrich and Smola, 2001, who allow any strictly increasing function of as the penalty; Shalev-Shwartz and Ben-David, 2014, Theorem 16.1). It turns a search over an infinite-dimensional space into a search over coefficients, and it holds for every loss: squared, logistic, hinge. Substituting the representation, and the vector of training predictions is .
Kernel ridge regression#
With the squared loss, the problem is ridge regression in feature space, , where the rows of are . Its solution from the regularization note can be rewritten with the identity : multiplying it by on the left and by on the right, both invertible for , gives
The left form inverts a matrix of the size of the feature space, the right form one of size , and . So with
the kernel ridge regression predictor, exactly the form the representer theorem promised (Bishop, 2006, §6.1).
Worked 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 . At the kernel values are and , and : far from the data an RBF regressor returns to 0, its prior mean, whatever the trend. At the training points themselves the fit is and , not the targets and : with the fit smooths rather than interpolates. Exact interpolation needs and an invertible . Either way it does not extrapolate.
The RBF bandwidth as model complexity
The bandwidth trades bias for variance here as well. The effective number of parameters of a ridge fit, , counts how many directions the fit uses (Hastie, Tibshirani and Friedman, 2009, §3.4.1); it is near when the fit interpolates and small when it is stiff. For the 30 points of the figure:
| 1 | 0.5 | 0.3 | 0.2 | 0.1 | 0.05 | 0.02 | 0.01 | |
|---|---|---|---|---|---|---|---|---|
| df | 2.36 | 3.31 | 4.43 | 5.77 | 9.25 | 14.69 | 21.61 | 24.26 |
| training error | 0.231 | 0.098 | 0.039 | 0.031 | 0.024 | 0.019 | 0.006 | 0.004 |
| mean squared distance to the true curve | 0.181 | 0.051 | 0.007 | 0.015 | 0.031 | 0.060 | 0.116 | 0.197 |
The training error falls monotonically as the kernel narrows; the mean squared distance to the true curve has the U shape of the bias–variance decomposition, with its minimum near .
The Bayesian reading. For a finite feature map, put a Gaussian prior on the weights and Gaussian noise of variance on the targets. Then is a Gaussian process with covariance . For the RBF kernel the feature space is infinite-dimensional, and an isotropic Gaussian prior on infinitely many weights is only a formal limit of this picture; the model is then stated directly: is a Gaussian process with covariance . In both cases the posterior mean of given the data follows from the conditional of a multivariate Gaussian: with . Kernel ridge regression is the posterior mean of Gaussian process regression, just as ridge regression is the MAP estimate under a Gaussian prior (Rasmussen and Williams, 2006, §2.2 and §6.2). The Gaussian process adds what the ridge view lacks: a posterior variance, an error bar at every .
The cost, and random Fourier features#
Kernel methods trade the dimension of the features for the number of examples. Computing the Gram matrix costs time and memory, solving costs , and SVM solvers scale between and in practice. Every prediction costs one kernel evaluation per support vector or training point. For the Gram matrix alone has entries, 80 GB in double precision. Kernel methods therefore rule small and medium data and lose to linear models, trees and networks on large data.
The remedy of Rahimi and Recht (2007) is to go back to explicit features, but few and random. It rests on Bochner’s theorem: a continuous shift-invariant kernel with is positive semidefinite if and only if it is the characteristic function of a probability distribution ,
(Rahimi and Recht, §3, Theorem 1; the second form holds because is real, so the imaginary part averages to zero). Characteristic functions appeared in the expectation note. For the RBF kernel, is the Gaussian , whose characteristic function is . Now draw from and uniformly from , and set
By , each term of is , and the second cosine averages to zero over the uniform . So is an average of independent terms with mean : a Monte Carlo estimate of the kernel. Each term lies in , and Hoeffding’s inequality gives for each pair; Rahimi and Recht (Claim 1) extend the bound to all pairs in a bounded set at once, at the cost of a factor that grows with .
The error shrinks like . On 300 points in the largest error over the whole Gram matrix is , , and for , , and , a factor of about per step. Any linear method trained on then approximates the kernel method, at a cost of for the features and for a ridge fit, linear in . On the moons a linear SVM on random features already reaches the test accuracy of the exact RBF SVM with the same , .
Kernels compare distributions#
Optional depth: kernel mean embeddings and the maximum mean discrepancy, used by the generative models course. The rest of the note does not depend on it.
The mean of the features of a distribution, , summarizes as one point of the feature space, and the distance between two such points can again be computed with the kernel alone:
This is the squared maximum mean discrepancy. With a polynomial kernel it compares moments up to the degree of the kernel; with the RBF kernel it is zero only when (Gretton et al., 2012). The generative models course uses it to compare generated images with real ones: the Kernel Inception Distance is this quantity with a cubic polynomial kernel on network features.
What changed#
| Linear SVM and ridge regression | Kernel methods | |
|---|---|---|
| Decision function | , a hyperplane | , curved in |
| Parameters | weights | coefficients, one per training point (representer theorem) |
| What the data enter as | feature vectors | the Gram matrix |
| Feature space | any space with an inner product, infinite for the RBF kernel | |
| Complexity knob | or | or plus the kernel and its bandwidth |
| Training cost | linear in | memory, – time; random features bring it back to linear |
Limitations#
- Quadratic memory, cubic time. Exact kernel methods do not scale past a few tens of thousands of examples; approximations (random features, the Nyström method) trade accuracy for speed.
- The kernel is a modelling choice. It encodes which inputs count as similar. The RBF kernel treats all directions alike after standardization; with many irrelevant features the distances are dominated by noise, as in the curse of dimensionality of the nearest neighbours note.
- Hyperparameters. The bandwidth and or interact and need a joint search; the moons table shows test accuracy between and depending on alone.
- No extrapolation with local kernels. An RBF fit returns to zero away from the data, as the worked example showed.
- Fixed features. The feature map is chosen before seeing the data. Neural networks learn the features instead, which is what lets them scale to images and text.
What you should remember#
- A kernel is an inner product after a feature map, . Any method written with inner products, such as the SVM dual, works with in place of without forming .
- is a valid kernel if and only if all its Gram matrices are symmetric positive semidefinite: equivalently, is a covariance function. Sums, positive multiples, products, limits and preserve this; distances and do not have it.
- Polynomial kernel: all monomials up to degree . RBF kernel: infinite-dimensional features, similarity on the scale ; large underfits, small overfits.
- Representer theorem: for any loss plus , the minimizer is . Kernel ridge regression: , , the posterior mean of a Gaussian process.
- Exact kernel methods cost memory and up to time. Random Fourier features estimate a shift-invariant kernel by Monte Carlo with error and make training linear in .
Code#
A polynomial kernel as an inner product, Gram matrices that are and are not positive semidefinite, kernel ridge regression by hand, the RBF bandwidth on the moons, and random Fourier features:
import numpy as np, math
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC, LinearSVC
from sklearn.kernel_ridge import KernelRidge
from sklearn.kernel_approximation import RBFSampler
# a kernel is an inner product after a feature map: (x.z)^2 with phi(x) = (x1^2, sqrt(2) x1 x2, x2^2)
x, z = np.array([1.0, 2.0]), np.array([3.0, 1.0])
phi = lambda v: np.array([v[0]**2, math.sqrt(2) * v[0] * v[1], v[1]**2])
print((x @ z)**2, phi(x) @ phi(z), math.comb(100 + 3, 3)) # 25.0 25.0 176851: monomials of degree <= 3 in 100 features
# which functions are kernels: the smallest eigenvalue of the Gram matrix on 50 random points
rng = np.random.default_rng(0)
P = rng.normal(size=(50, 2)); D2 = ((P[:, None] - P[None]) ** 2).sum(-1)
for name, G in (('rbf', np.exp(-D2 / 2)), ('distance', np.sqrt(D2)), ('tanh', np.tanh(P @ P.T + 1))):
print(name, f'{np.linalg.eigvalsh(G).min():.3g}')
# rbf 4.24e-10 | distance -27.5 | tanh -6.26: only the RBF Gram matrix is positive semidefinite
# kernel ridge regression by hand: x = (0, 1), y = (1, 2), RBF with sigma = 1, lambda = 0.1
X = np.array([[0.0], [1.0]]); y = np.array([1.0, 2.0])
k = lambda A, B: np.exp(-(A - B.T) ** 2 / 2)
alpha = np.linalg.solve(k(X, X) + 0.1 * np.eye(2), y)
Xn = np.array([[0.5], [3.0]])
print(alpha.round(4), (k(Xn, X) @ alpha).round(4)) # [-0.1343 1.8922] [1.5514 0.2546]
print((k(X, X) @ alpha).round(3)) # [1.013 1.811]: the fit at the training points, not (1, 2)
print(KernelRidge(alpha=0.1, kernel='rbf', gamma=0.5).fit(X, y).predict(Xn).round(4)) # [1.5514 0.2546]
# the RBF bandwidth as bias-variance: an SVM on two noisy moons, gamma = 1/(2 sigma^2)
Xm, ym = make_moons(n_samples=600, noise=0.3, random_state=0)
Xtr, Xte, ytr, yte = train_test_split(Xm, ym, test_size=0.5, random_state=0)
print('linear', round(SVC(kernel='linear').fit(Xtr, ytr).score(Xte, yte), 3)) # linear 0.853
for g in (0.01, 0.1, 1, 10, 100, 1000):
m = SVC(kernel='rbf', gamma=g, C=1).fit(Xtr, ytr)
print(g, round(1 / math.sqrt(2 * g), 3), round(m.score(Xtr, ytr), 3), round(m.score(Xte, yte), 3), len(m.support_))
# gamma, sigma, train and test accuracy, support vectors
# 0.01 7.071 0.843 0.827 198 | 0.1 2.236 0.883 0.85 125 | 1 0.707 0.937 0.88 79
# 10 0.224 0.94 0.883 126 | 100 0.071 0.99 0.857 256 | 1000 0.022 1.0 0.653 299
# random Fourier features: the largest error over a 300 x 300 Gram matrix (5 features, gamma = 0.1), mean of 5 draws
Q = rng.normal(size=(300, 5)); K = np.exp(-0.1 * ((Q[:, None] - Q[None]) ** 2).sum(-1))
for D in (10, 100, 1000, 10000):
err = [np.abs((Z := RBFSampler(gamma=0.1, n_components=D, random_state=s).fit_transform(Q)) @ Z.T - K).max() for s in range(5)]
print(D, round(float(np.mean(err)), 3))
# 10 1.118 | 100 0.343 | 1000 0.101 | 10000 0.035: about 1/sqrt(D)
# a linear SVM on D random features approaches the RBF SVM (gamma = 1: test accuracy 0.88)
for D in (2, 10, 100, 1000):
f = RBFSampler(gamma=1, n_components=D, random_state=0).fit(Xtr)
print(D, round(LinearSVC(C=1).fit(f.transform(Xtr), ytr).score(f.transform(Xte), yte), 3))
# 2 0.663 | 10 0.883 | 100 0.88 | 1000 0.877
Next#
The SVM and its kernels separate two classes. Many problems have more: ten digits, thousands of topics, a vocabulary of tens of thousands of words, or several labels at once for the same object. The next note reduces such problems to binary ones, extends logistic regression to many classes with the softmax, and adapts the metrics of the classification metrics note to several classes and to several labels per example.
References#
- B. E. Boser, I. M. Guyon, V. N. Vapnik. A Training Algorithm for Optimal Margin Classifiers. COLT, 1992, pp. 144–152. The kernel trick applied to the maximum-margin classifier.
- N. Aronszajn. Theory of Reproducing Kernels. Transactions of the American Mathematical Society, 68(3), pp. 337–404, 1950.
- G. Kimeldorf, G. Wahba. Some Results on Tchebycheffian Spline Functions. Journal of Mathematical Analysis and Applications, 33(1), pp. 82–95, 1971. The representer theorem for the squared loss.
- B. Schölkopf, R. Herbrich, A. J. Smola. A Generalized Representer Theorem. COLT, LNCS 2111, pp. 416–426, 2001.
- A. Rahimi, B. Recht. Random Features for Large-Scale Kernel Machines. NIPS, 2007. §3: Bochner’s theorem (Theorem 1), random Fourier features (Algorithm 1), uniform convergence (Claim 1).
- A. Gretton, K. M. Borgwardt, M. J. Rasch, B. Schölkopf, A. Smola. A kernel two-sample test. JMLR, 13, pp. 723–773, 2012. The maximum mean discrepancy.
- C. E. Rasmussen, C. K. I. Williams. Gaussian Processes for Machine Learning. MIT Press, 2006. §2.1–2.2 (weight-space and function-space views of regression), §4.3 (eigenfunction analysis of kernels, Mercer’s theorem), §6.1–6.2 (reproducing kernel Hilbert spaces, regularization).
- S. Shalev-Shwartz, S. Ben-David. Understanding Machine Learning: From Theory to Algorithms. Cambridge University Press, 2014. Chapter 16: embeddings into feature spaces, the kernel trick, Theorem 16.1 (representer theorem), Lemma 16.2 (positive semidefinite kernels).
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. §6.1 (dual representations), §6.2 (constructing kernels), §6.4 (Gaussian processes).
- T. Hastie, R. Tibshirani, J. Friedman. The Elements of Statistical Learning, 2nd ed. Springer, 2009. §3.4.1 (ridge regression and its effective degrees of freedom), §5.8 (regularization and reproducing kernel Hilbert spaces), §12.3 (support vector machines and kernels).
- E. Sokolov et al. Машинное обучение (HSE), lecture notes: lecture 13 (kernel methods, constructing kernels, the polynomial and Gaussian kernels), lecture 14 (the kernel SVM, random Fourier features).