Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

The kernel trick

P3.B740 min●●● AdvancedReviewed Dec 2, 2026

Why this matters for machine learning

Linear methods are simple and well understood, but real patterns are curved. Kernels let a linear method draw curved boundaries while the computation stays about as cheap as one dot product per pair of points.

Before this: Support Vector Machines, Dot product and cosine similarity, Constrained optimization and Lagrange multipliers

After this lesson you can

  • Explain why a straight line cannot separate two concentric rings, and show that a lift such as adding the coordinate x₁² + x₂² lets a flat plane separate them
  • Count how fast explicit polynomial features grow, using the number of monomials of degree at most p in d variables
  • State why an algorithm that uses the data only through dot products can use a kernel k(x, z) = φ(x)·φ(z) instead, and check the identity for the degree-2 polynomial kernel
  • Describe the polynomial, Gaussian (RBF) and linear kernels, the Gram matrix, and how the width γ and the penalty C control flexibility
  • Compute kernel ridge regression from a Gram matrix and explain why kernel methods struggle with very large data sets

A support vector machine (P3.B6) draws the straight line with the widest margin between two classes. That works when a line exists. Now picture two classes arranged as concentric rings, one inside the other. Wherever you draw a straight line, both classes end up on both sides of it. This lesson shows a way out that is both simple and slightly magical: lift the points into a space with more dimensions, where a flat cut does exist, and then do the whole job without ever visiting that space.

Rings that no line can split

The data in this lesson is made up, and a fixed random seed makes it the same on every visit. There are 30 points on an inner ring, with a radius near 1, and 30 points on an outer ring, with a radius near 2. Each radius has a little random scatter of 0.15, so the rings are slightly fuzzy.

In the first panel of the widget below, the pink circles are the inner ring and the blue squares are the outer ring. Try to imagine a straight line with all the pink on one side and all the blue on the other. There is none. The rings are symmetric: any line through the picture cuts each ring about in half, so about half of each class lands on each side. Running a search over many lines on this sample, the best straight line gets 41 of the 60 points right (68%), and that is partly luck of this particular sample. A model that always guesses one class gets 30 of 60 (50%).

A linear classifier such as the perceptron or a linear SVM (P3.B6) cannot do better than this. The problem is not the training method. The model family, straight lines, is too small for this pattern.

Lifting: a new coordinate makes the problem easy

The two rings differ in one simple way: the inner ring is close to the origin and the outer ring is far from it. The distance to the origin is not a linear function of x1x_1 and x2x_2, but it is a very simple function of them. Its square is

z=x12+x22.z = x_1^2 + x_2^2 .

Give every point this third coordinate. The map from the original coordinates to the new ones is called a feature map, written φ\varphi (the Greek letter phi):

φ(x1,x2)=(x1,  x2,  x12+x22).\varphi(x_1,x_2)=(x_1,\;x_2,\;x_1^2+x_2^2).

A point on the inner ring, at radius about 1, gets zz about 1. A point on the outer ring, at radius about 2, gets zz about 4. In 3-D the two rings now sit at different heights, like two circles on a lamp shade: a low one and a high one. On this sample, every inner-ring point has zz below 1.6 and every outer-ring point has zz above 2.8. A flat horizontal plane anywhere between those heights, for example z=2.2z=2.2 (a circle of radius about 1.48), separates all 60 points, a clean 100%.

In 2-D: no straight line works

−2−1012−2−1012x₁x₂

Lifted to 3-D: a flat plane separates them

x₁x₂z

● inner ring, ■ outer ring, green: the plane and its circle in 2-D. Thin grey lines drop each point to the floor. A point's height is lift amount × (x₁² + x₂²).

circle radius √z: 1.48
on the correct side: 60 of 60

The plane z = 2.2 separates all 60 points: the inner ring is below it and the outer ring above. Back in 2-D it is the circle of radius 1.48.

Lifting two rings. Pink circles are the inner ring and blue squares the outer ring (made-up data, seeded). Top or left: the points in 2-D with the dashed circle where the plane cuts. Bottom or right: the same points lifted to height lift amount × (x₁² + x₂²), with a horizontal plane. The RBF kernel view is used later in the lesson.

Things to try, in order:

  1. Press Play the lift and watch the rings rise. The inner ring stays low; the outer ring rises further, because the height is the squared distance.
  2. Drag Plane height z from 0.2 to 6. The 2-D circle grows. Find the range of heights where the count reads 60 of 60. That range is the gap between the rings, and a plane anywhere inside it works.
  3. Use Turn the view to see the plane from the side. A plane only needs to separate the two heights.

This is the same trick as polynomial regression (P3.A3). There, the powers x,x2,x3x,x^2,x^3 were new columns, and the model stayed linear in its weights. A linear method on lifted features φ(x)\varphi(\mathbf{x}) gives a nonlinear method on x\mathbf{x}.

The cost of lifting grows fast

We guessed a good lift here by looking at the picture. In general you do not know which new features are useful, so a common recipe is to include every monomial up to some degree pp: all products of the inputs with total power at most pp, including the constant 1. For two inputs and p=2p=2, that is 1, x1, x2, x12, x1x2, x221,\,x_1,\,x_2,\,x_1^2,\,x_1x_2,\,x_2^2, six features. The count for dd inputs and degree at most pp is

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

(P3.A3 gave one example: 286 weights for d=10d=10, p=3p=3.) It grows quickly:

Inputs ddDegree ppMonomials
226
103286
1003176,851
784 (a 28 × 28 image)2308,505
784380,931,145

A small grey-scale image of 28×2828\times28 pixels has 784 inputs, and with degree 3 the lifted vector has about 81 million entries per example. Storing and multiplying those for thousands of examples is out of reach, and a high-degree lift of the exact rings above would be worse still. We want the benefit of a huge lift without paying for its coordinates.

The observation that saves us: only dot products matter

Look at how some algorithms use their data. Take the dual form of the support vector machine. In P1.F7, the 1-D example with points x=0x=0 (label −1-1), x=2x=2 and x=5x=5 (label +1+1) had multipliers 0.5, 0.5, 00.5,\,0.5,\,0. The weight vector turned out to be a weighted sum of the training points:

w=∑i=1nαi yi xi,\mathbf{w}=\sum_{i=1}^{n}\alpha_i\,y_i\,\mathbf{x}_i ,

which gives w=0.5⋅(−1)⋅0+0.5⋅(+1)⋅2=1w=0.5\cdot(-1)\cdot0+0.5\cdot(+1)\cdot2=1 there. This comes straight from the stationarity condition of the Lagrangian (P1.F7), and P3.B6 derives it for the SVM. Substitute it back and the weight vector disappears. What remains is the dual problem, and in it the data appears only inside the dot products xi⋅xj\mathbf{x}_i\cdot\mathbf{x}_j:

max⁡α  ∑iαi−12∑i,jαiαj yiyj (xi⋅xj)subject to0≤αi≤C,∑iαiyi=0.\begin{aligned} &\max_{\boldsymbol{\alpha}}\;\sum_i\alpha_i\\ &\qquad-\tfrac12\sum_{i,j}\alpha_i\alpha_j\,y_iy_j\,(\mathbf{x}_i\cdot\mathbf{x}_j)\\ &\text{subject to}\quad 0\le\alpha_i\le C,\\ &\qquad\sum_i\alpha_iy_i=0 . \end{aligned}

The prediction for a new point x\mathbf{x} also needs only dot products with the training points:

f(x)=∑iαi yi (xi⋅x)+b.f(\mathbf{x})=\sum_i\alpha_i\,y_i\,(\mathbf{x}_i\cdot\mathbf{x})+b .

In the 1-D example, f(x)=0.5⋅(−1)⋅0⋅x+0.5⋅(+1)⋅2⋅x+b=x−1f(x)=0.5\cdot(-1)\cdot0\cdot x+0.5\cdot(+1)\cdot2\cdot x+b=x-1 with b=−1b=-1, the same line as before. Only the support vectors, the points with αi>0\alpha_i>0, contribute to the sum.

Now apply the lift. If you run the same algorithm on φ(xi)\varphi(\mathbf{x}_i) instead of xi\mathbf{x}_i, every dot product xi⋅xj\mathbf{x}_i\cdot\mathbf{x}_j becomes φ(xi)⋅φ(xj)\varphi(\mathbf{x}_i)\cdot\varphi(\mathbf{x}_j), and nothing else changes: the algorithm never looks at a single coordinate, only at these numbers. So give the number a name. A kernel is a function

k(x,z)=φ(x)⋅φ(z),k(\mathbf{x},\mathbf{z})=\varphi(\mathbf{x})\cdot\varphi(\mathbf{z}),

the dot product of the two points after the lift. If there is a formula for kk that uses x\mathbf{x} and z\mathbf{z} directly, we can plug it in and never compute φ\varphi. That is the kernel trick:

It is not only about SVMs. The SVM dual is one algorithm with this property. A second is kernel ridge regression, below. Others with a kernel version include the perceptron, principal component analysis (kernel PCA; PCA itself is P3.C3) and Gaussian process regression. An algorithm that needs the coordinates themselves, such as a decision tree that splits on one coordinate, cannot use the trick.

A worked example: the degree-2 polynomial kernel

The lifted space can be written out, so that we can see the trick work. Take two inputs and the map

φ(x)=(x12,  2 x1x2,  x22).\varphi(\mathbf{x})=\bigl(x_1^2,\;\sqrt2\,x_1x_2,\;x_2^2\bigr).

The strange-looking 2\sqrt2 is chosen so that the cross term gets the right weight. Take x=(1,2)\mathbf{x}=(1,2) and z=(3,1)\mathbf{z}=(3,1):

  • φ(x)=(1,  22,  4)\varphi(\mathbf{x})=(1,\;2\sqrt2,\;4) and φ(z)=(9,  32,  1)\varphi(\mathbf{z})=(9,\;3\sqrt2,\;1).
  • Dot product in the lifted space: 1⋅9+22⋅32+4⋅1=9+12+4=251\cdot9+2\sqrt2\cdot3\sqrt2+4\cdot1=9+12+4=25.
  • Original dot product: x⋅z=3+2=5\mathbf{x}\cdot\mathbf{z}=3+2=5, and 52=255^2=25.

The two ways agree. In general,

φ(x)⋅φ(z)=x12z12+2x1x2z1z2+x22z22=(x1z1+x2z2)2=(x⋅z)2.\begin{aligned} \varphi(\mathbf{x})\cdot\varphi(\mathbf{z})&=x_1^2z_1^2+2x_1x_2z_1z_2\\ &\quad+x_2^2z_2^2\\ &=(x_1z_1+x_2z_2)^2\\ &=(\mathbf{x}\cdot\mathbf{z})^2 . \end{aligned}

So the kernel k(x,z)=(x⋅z)2k(\mathbf{x},\mathbf{z})=(\mathbf{x}\cdot\mathbf{z})^2 is the dot product in a 3-dimensional lifted space, computed with one dot product in the original 2-D space and one squaring. With dd inputs, the lifted space for this kernel has d(d+1)/2d(d+1)/2 coordinates (3 for d=2d=2, 307,720 for d=784d=784), yet the kernel costs one dot product in dd numbers plus one squaring.

The variant (x⋅z+1)2(\mathbf{x}\cdot\mathbf{z}+1)^2 also adds the constant and linear terms. It corresponds to six features, and equals 36 for the same x\mathbf{x} and z\mathbf{z}. The run below checks the identity on 1,000 random pairs.

Try it: the kernel equals the lifted dot product

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The last part of the cell belongs to the next section: it shows the Gaussian kernel as a sum of ever higher polynomial terms.

Common kernels

A kernel function takes two points and returns one number that acts like a similarity score. These three cover most uses.

  • Linear: k(x,z)=x⋅zk(\mathbf{x},\mathbf{z})=\mathbf{x}\cdot\mathbf{z}. No lift at all, the ordinary algorithm.
  • Polynomial: k(x,z)=(x⋅z+c)pk(\mathbf{x},\mathbf{z})=(\mathbf{x}\cdot\mathbf{z}+c)^p with c≥0c\ge0. With c>0c>0 it stands for all monomials up to degree pp (the (d+pp)\binom{d+p}{p} above), with particular weights. With c=0c=0 it stands for the monomials of degree exactly pp only. Evaluating kk takes about dd multiplications, whatever pp is.
  • RBF or Gaussian: k(x,z)=exp⁡ ⁣(−γ ∥x−z∥2)k(\mathbf{x},\mathbf{z})=\exp\!\bigl(-\gamma\,\lVert\mathbf{x}-\mathbf{z}\rVert^2\bigr) with γ>0\gamma>0. It equals 1 when the two points coincide and falls toward 0 as they move apart, so it reads as “how close are these two points?”. (RBF stands for radial basis function, a function of distance only.)

The RBF kernel is the usual default. It is a sum of polynomial kernels of every degree, so its feature space is infinite: the Gaussian kernel equals a dot product in a space with infinitely many coordinates, which no computer ever builds. The Go-deeper box shows why and checks it numerically.

Go deeper Why the Gaussian kernel has infinitely many features

Expand the squared distance: ∥x−z∥2=∥x∥2−2 x⋅z+∥z∥2\lVert\mathbf{x}-\mathbf{z}\rVert^2=\lVert\mathbf{x}\rVert^2-2\,\mathbf{x}\cdot\mathbf{z}+\lVert\mathbf{z}\rVert^2. Then

exp⁡(−γ∥x−z∥2)=e−γ∥x∥2×e−γ∥z∥2×e2γ x⋅z,e2γ x⋅z=∑j=0∞(2γ)jj!×(x⋅z)j.\begin{aligned} \exp(-\gamma\lVert\mathbf{x}-\mathbf{z}\rVert^2)&=\mathrm{e}^{-\gamma\lVert\mathbf{x}\rVert^2}\\ &\quad\times\mathrm{e}^{-\gamma\lVert\mathbf{z}\rVert^2}\\ &\quad\times\mathrm{e}^{2\gamma\,\mathbf{x}\cdot\mathbf{z}},\\ \mathrm{e}^{2\gamma\,\mathbf{x}\cdot\mathbf{z}}&=\sum_{j=0}^{\infty}\frac{(2\gamma)^j}{j!}\\ &\qquad\times(\mathbf{x}\cdot\mathbf{z})^j . \end{aligned}

Each term (x⋅z)j(\mathbf{x}\cdot\mathbf{z})^j is a polynomial kernel of degree jj, which has its own set of monomial features, and the sum never stops. So the RBF kernel is a dot product in a space with infinitely many coordinates. This is a statement about the existence of such a space (a feature space, in the language of functional analysis), and no computer ever builds it. The cell above checks it for one variable: with γ=0.7\gamma=0.7, a=0.9a=0.9 and b=−0.3b=-0.3 the kernel is 0.3649480.364948, and the first 10 terms of the series already give 0.3649480.364948.

A kernel must correspond to some dot product. Mercer’s condition (in the finite form used in machine learning) requires that for every finite set of points the matrix of kernel values, the Gram matrix below, is symmetric and positive semi-definite: all its eigenvalues are at least 0 (P1.B12). Sums, products and positive multiples of valid kernels are valid, and kernels also exist for strings and graphs.

Go deeper A similarity that is not a kernel

Take k(x,z)=−∥x−z∥2k(\mathbf{x},\mathbf{z})=-\lVert\mathbf{x}-\mathbf{z}\rVert^2. For two points at distance 1 the Gram matrix has rows (0,−1)(0,-1) and (−1,0)(-1,0), with eigenvalues −1-1 and +1+1. A negative eigenvalue means that no lifted space exists, so this function is not a kernel.

The Gram matrix

For a training set of nn points, collect all the kernel values in an n×nn\times n table, the Gram matrix (or kernel matrix):

Kij=k(xi,xj).K_{ij}=k(\mathbf{x}_i,\mathbf{x}_j).

It is symmetric (Kij=KjiK_{ij}=K_{ji}), and for the Gaussian kernel its diagonal is all ones. This table is all that the training algorithm sees of the data. In the cell below, the 60 ring points give a 60×6060\times60 matrix; its smallest eigenvalue is not below −10−9-10^{-9}, which is the finite-data form of the positive semi-definite condition up to rounding.

Prediction for a new point uses the same formula as before, with the kernel replacing the dot product:

f(x)=∑iαi yi k(xi,x)+b,f(\mathbf{x})=\sum_i\alpha_i\,y_i\,k(\mathbf{x}_i,\mathbf{x})+b ,

and only the support vectors (αi>0\alpha_i>0) are in the sum. In the Gaussian case this reads as a vote: each support vector contributes a bump of height αiyi\alpha_iy_i centred on itself, and ff adds the bumps up.

Try it: separate the rings by lifting, and the Gram matrix

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

This cell draws its own rings, so its figures differ from the widget’s. In particular its best straight line scores about 77% (46 of 60), not 68%. A line can beat 50% by luck on a small sample, but not by much: every line cuts both rings roughly in half.

A second example: kernel ridge regression

Kernel ridge regression is ridge regression (L2 regularization, P3.A6) with a kernel. In its ordinary form, the weights are found from the features: w=(Φ⊤Φ+λI)−1Φ⊤y\mathbf{w}=(\boldsymbol{\Phi}^{\top}\boldsymbol{\Phi}+\lambda\mathbf{I})^{-1}\boldsymbol{\Phi}^{\top}\mathbf{y}, where each row of Φ\boldsymbol{\Phi} is one lifted point. There is an equivalent form that uses an n×nn\times n matrix instead of a d×dd\times d one. Writing w=Φ⊤α\mathbf{w}=\boldsymbol{\Phi}^{\top}\boldsymbol{\alpha},

α=(K+λI)−1y,f(x)=∑i=1nαi k(xi,x),\begin{aligned} \boldsymbol{\alpha}&=(\mathbf{K}+\lambda\mathbf{I})^{-1}\mathbf{y},\\ f(\mathbf{x})&=\sum_{i=1}^{n}\alpha_i\,k(\mathbf{x}_i,\mathbf{x}), \end{aligned}

where K=ΦΦ⊤\mathbf{K}=\boldsymbol{\Phi}\boldsymbol{\Phi}^{\top} is the Gram matrix. Only K\mathbf{K} appears, so Φ\boldsymbol{\Phi} is never needed. (The step between the two forms is a matrix identity, shown in the Go-deeper box.) This version has no intercept (bias) term; it is not needed here, and one can be added.

Take three 1-D points, x=0,1,2x=0,1,2 with targets y=0,1,0y=0,1,0, and the Gaussian kernel with γ=1\gamma=1. The Gram matrix entries are e−1=0.3679\mathrm{e}^{-1}=0.3679 for neighbours and e−4=0.0183\mathrm{e}^{-4}=0.0183 for the outer pair:

K=(10.36790.01830.367910.36790.01830.36791).\mathbf{K}=\begin{pmatrix}1&0.3679&0.0183\\0.3679&1&0.3679\\0.0183&0.3679&1\end{pmatrix}.
  • With λ=0\lambda=0 the solution is α=(−0.492, 1.362, −0.492)\boldsymbol{\alpha}=(-0.492,\,1.362,\,-0.492) and the curve passes exactly through the three targets. At x=0.5x=0.5 and x=1.5x=1.5 it predicts 0.6260.626.
  • With λ=0.1\lambda=0.1 the solution is α=(−0.383, 1.166, −0.383)\boldsymbol{\alpha}=(-0.383,\,1.166,\,-0.383). The curve now misses the targets slightly (it gives 0.038, 0.883, 0.0380.038,\,0.883,\,0.038 at the training points) and predicts 0.5690.569 between them. The penalty λ\lambda trades a little training error for a smoother curve, as in P3.A6.

The run below reproduces both and then uses the same recipe on the rings. It also shows the width γ\gamma at work, which comes next.

Go deeper From the feature form of ridge regression to the Gram-matrix form

For any matrix Φ\boldsymbol{\Phi} and λ>0\lambda>0, the identity (Φ⊤Φ+λI)−1Φ⊤=Φ⊤(ΦΦ⊤+λI)−1(\boldsymbol{\Phi}^{\top}\boldsymbol{\Phi}+\lambda\mathbf{I})^{-1}\boldsymbol{\Phi}^{\top}=\boldsymbol{\Phi}^{\top}(\boldsymbol{\Phi}\boldsymbol{\Phi}^{\top}+\lambda\mathbf{I})^{-1} holds. (Multiply both sides by the two matrices in parentheses to see it.) It turns the weights into w=Φ⊤α\mathbf{w}=\boldsymbol{\Phi}^{\top}\boldsymbol{\alpha} with α=(K+λI)−1y\boldsymbol{\alpha}=(\mathbf{K}+\lambda\mathbf{I})^{-1}\mathbf{y}. A prediction is then w⋅φ(x)=∑iαi φ(xi)⋅φ(x)=∑iαik(xi,x)\mathbf{w}\cdot\varphi(\mathbf{x})=\sum_i\alpha_i\,\varphi(\mathbf{x}_i)\cdot\varphi(\mathbf{x})=\sum_i\alpha_ik(\mathbf{x}_i,\mathbf{x}). A quick NumPy check with random matrices (8 points, 5 features, λ=0.7\lambda=0.7) gives equal weight vectors to about 10−1610^{-16}. Notice the trade: the feature form solves a system of size dd (the number of features), the Gram form one of size nn (the number of points). The kernel form wins when the lifted space has far more coordinates than there are points, and loses on large data sets.

The width γ\gamma and the penalty CC control flexibility

A kernel does not remove the capacity question (P3.A3, P3.A5). It moves it into two settings.

  • γ\gamma in the Gaussian kernel. γ\gamma says how fast similarity falls with distance. It is often described through the bandwidth σ\sigma, with γ=1/(2σ2)\gamma=1/(2\sigma^2): a large σ\sigma means a small γ\gamma. A small γ\gamma makes every point similar to many others, so the boundary is smooth and simple, and it can underfit. A very large γ\gamma makes each point similar only to its own tiny neighbourhood, so the boundary wraps around individual training points, and it can memorize noise and mislabeled points. A middle value follows the real pattern.
  • CC in the soft-margin SVM (P3.B6). CC is the price of a margin violation. A small CC tolerates many violations, giving a wide margin and a simpler boundary. A large CC insists on fitting the training points.

The numbers below come from scikit-learn on a noisier version of the rings (radius scatter 0.3 instead of 0.15, so the rings overlap a little): 100 training and 100 test points per ring, with C=1C=1 (the default) unless stated. The block is shown, not run in the browser (scikit-learn is not available there). It is the real output on the machine used for this lesson, with scikit-learn 1.8.

import numpy as np
from sklearn.svm import SVC

rng = np.random.default_rng(0)
def rings(n):
    ang = rng.uniform(0, 2 * np.pi, 2 * n)
    r = np.r_[rng.normal(1, 0.3, n), rng.normal(2, 0.3, n)]
    y = np.r_[-np.ones(n), np.ones(n)]
    return np.c_[r * np.cos(ang), r * np.sin(ang)], y

Xtr, ytr = rings(100)
Xte, yte = rings(100)
print("kernel  train  test  SVs")
for kernel in ["linear", "rbf"]:
    m = SVC(kernel=kernel, gamma=1.0, C=1.0).fit(Xtr, ytr)
    print(f"{kernel:6s} {m.score(Xtr, ytr):6.3f} {m.score(Xte, yte):5.3f} {m.n_support_.sum():4d}")
kernel  train  test  SVs
linear  0.550 0.565  200
rbf     0.955 0.945   59

A straight line is barely better than guessing (55% on the training points), and the RBF kernel reaches 95.5% training and 94.5% test accuracy with only 59 of the 200 training points as support vectors. Now vary γ\gamma with C=1C=1:

gamma   train   test  SVs
  0.01  0.770  0.740  200
   0.1  0.970  0.960   93
     1  0.955  0.945   59
    10  0.980  0.930  145
   100  1.000  0.775  196
  1000  1.000  0.615  200

Small γ\gamma underfits (77% training). Large γ\gamma memorizes: at γ=1000\gamma=1000 the training accuracy is 100% while the test accuracy drops to 61.5%. This is the U-shape of P3.A5 with γ\gamma as the knob. On this data CC matters much less than γ\gamma. The RBF kernel view of the widget shows the same effect with kernel ridge regression (not an SVM): tick mislabel 4 training points and raise γ\gamma, and the boundary grows small islands around the mislabeled points.

Two practical notes. The right γ\gamma depends on the scale of the inputs, so scale the features first (P3.A11), and choose γ\gamma and CC on validation data (P3.A4), never on the test set. Scikit-learn’s default gamma="scale" sets γ=1/(d⋅Var(X))\gamma=1/(d\cdot\mathrm{Var}(X)), where dd is the number of features and Var(X)\mathrm{Var}(X) is the variance of all entries of the training matrix.

Try it: kernel ridge regression, then the width gamma

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

Running the cell prints the numbers above for part 1. For part 2 it shows training accuracy rising from 0.700 at γ=0.01\gamma=0.01 to 1.000 at γ=10\gamma=10 and above, while the test accuracy peaks at 1.000 for γ=0.1\gamma=0.1 and falls to 0.887 at γ=10\gamma=10 and 0.863 at γ=100\gamma=100. The training points of this cell are not the same as the widget’s, but the same recipe gives the same shape.

Three views of the same idea

Intuition

Imagine you must sort people into two groups, but you are not given their measurements. All you get is a table saying how alike every pair of people is. A kernel method works from exactly such a table: the Gram matrix of similarities. To label a newcomer, it asks how alike the newcomer is to the people it trusts most (the support vectors) and takes a weighted vote. The lifting story and the similarity story are the same story, because a dot product in the lifted space is the similarity.

Where the analogy breaks: a similarity table is only usable if it comes from a real lifted space. A table made of arbitrary “alike” scores can break the maths (the Mercer condition above).

Math

A function kk is a valid kernel when every Gram matrix it produces is symmetric and positive semi-definite. Then some feature map φ\varphi exists with k(x,z)=φ(x)⋅φ(z)k(\mathbf{x},\mathbf{z})=\varphi(\mathbf{x})\cdot\varphi(\mathbf{z}), and every formula above that has a dot product can take kk in its place.

Code

With scikit-learn, a kernel SVM can take the Gram matrix directly. This block is shown, not run (scikit-learn is not available in the browser):

from sklearn.svm import SVC

m = SVC(kernel="precomputed", C=1.0)
m.fit(K_train, y_train)          # K_train[i, j] = k(x_i, x_j), shape (n, n)
pred = m.predict(K_test_train)   # K_test_train[i, j] = k(test_i, train_j)

The model never sees a coordinate: it sees only the two tables of kernel values.

The price: an n×nn\times n matrix

The Gram matrix has n2n^2 entries for nn training points, and everything above reads it. That is the weak spot of kernel methods:

  • Memory. Explicit features cost memory proportional to nn × (number of features); a kernel method needs n×nn\times n, which is smaller only when the lifted space is huge. In 64-bit floats, n=1,000n=1{,}000 needs 8 MB, n=10,000n=10{,}000 needs 800 MB, n=100,000n=100{,}000 needs 80 GB and n=1,000,000n=1{,}000{,}000 needs 8 TB.
  • Time. Solving kernel ridge regression takes time proportional to n3n^3. Kernel SVM solvers usually scale somewhere between n2n^2 and n3n^3 in practice, depending on the data and on CC and γ\gamma.
  • Prediction. Each new point costs one kernel evaluation per support vector, so a model with many support vectors predicts slowly. Kernel ridge regression has no sparsity: every training point has a nonzero αi\alpha_i in general.

So kernel methods are a strong choice for small and medium data sets (up to some tens of thousands of examples) and a poor fit for millions. Approximations exist: random Fourier features (Rahimi and Recht, 2007) replace the RBF kernel with an explicit random feature map of moderate size, and the Nyström method builds a low-rank approximation of the Gram matrix from a subset of the points. Both bring back an ordinary linear model on a manageable number of features, at the cost of some accuracy. For very large data, neural networks (Part 4) are usually preferred, because they learn the lift φ\varphi from the data in place of fixing a kernel (P4.3).

Quiz

Check your understanding

  1. Two concentric rings of points cannot be separated by a straight line in 2-D. After adding the coordinate z = x₁² + x₂², what is true?

  2. What does the kernel trick avoid?

  3. For x = (1, 2) and z = (3, 1), what is the kernel value k(x, z) = (x·z)², and where does it come from?

  4. An RBF-kernel SVM has 100% training accuracy and much lower test accuracy, and almost every training point is a support vector. Which change is most likely to help?

  5. You have 1,000,000 training examples. Why is a standard kernel SVM or kernel ridge regression hard to use?

Exercises

  1. How many monomials of degree at most 2 are there for d=3d=3 inputs? List them.
    Show answer(52)=10\binom{5}{2}=10: 11; x1,x2,x3x_1,x_2,x_3; x12,x22,x32x_1^2,x_2^2,x_3^2; x1x2,x1x3,x2x3x_1x_2,x_1x_3,x_2x_3.
  2. For x=(2,0)\mathbf{x}=(2,0) and z=(1,3)\mathbf{z}=(1,3), compute (x⋅z)2(\mathbf{x}\cdot\mathbf{z})^2 and φ(x)⋅φ(z)\varphi(\mathbf{x})\cdot\varphi(\mathbf{z}) with φ(x)=(x12,2x1x2,x22)\varphi(\mathbf{x})=(x_1^2,\sqrt2x_1x_2,x_2^2).
    Show answerx⋅z=2\mathbf{x}\cdot\mathbf{z}=2, so the kernel is 44. φ(x)=(4,0,0)\varphi(\mathbf{x})=(4,0,0) and φ(z)=(1,32,9)\varphi(\mathbf{z})=(1,3\sqrt2,9), so the dot product is 44. They agree.
  3. For the Gaussian kernel with γ=1\gamma=1, what is k(x,z)k(\mathbf{x},\mathbf{z}) when ∥x−z∥=2\lVert\mathbf{x}-\mathbf{z}\rVert=2? And for γ=0.1\gamma=0.1?
    Show answere−4≈0.0183\mathrm{e}^{-4}\approx0.0183 for γ=1\gamma=1 and e−0.4≈0.670\mathrm{e}^{-0.4}\approx0.670 for γ=0.1\gamma=0.1. The smaller γ\gamma treats distant points as still quite similar.
  4. In the dual SVM of P1.F7 (points 0,2,50,2,5 with labels −1,+1,+1-1,+1,+1 and multipliers 0.5,0.5,00.5,0.5,0), use f(x)=∑iαiyi(xix)+bf(x)=\sum_i\alpha_iy_i(x_ix)+b with b=−1b=-1 to compute f(3)f(3) and say which points matter.
    Show answerf(3)=0.5⋅(−1)⋅0⋅3+0.5⋅1⋅2⋅3−1=2f(3)=0.5\cdot(-1)\cdot0\cdot3+0.5\cdot1\cdot2\cdot3-1=2. Only the support vectors (x=0x=0 and x=2x=2, with α>0\alpha>0) appear in the sum; the point x=5x=5 has α=0\alpha=0.
  5. A data set has n=20,000n=20{,}000 examples. Estimate the memory of its Gram matrix in 64-bit floats. How much less in 32-bit?
    Show answer20,0002=4×10820{,}000^2=4\times10^8 entries, times 8 bytes is 3.2 GB; in 32-bit floats (4 bytes) it is 1.6 GB.
  6. Why can a decision tree not use the kernel trick, while an SVM can?
    Show answerA tree splits on single coordinates (xjx_j above a threshold), so it needs the coordinates themselves. The SVM dual and its predictions use the data only through dot products, which a kernel can replace.
  7. In the widget’s RBF view, tick mislabel 4 training points and compare γ=0.1\gamma=0.1 with γ=100\gamma=100. What happens to the training accuracy and the test accuracy, and why?
    Show answerAt γ=0.1\gamma=0.1 the training accuracy is 93% (56 of 60) and the test accuracy 100%: the smooth model ignores the four wrong labels. At γ=100\gamma=100 the training accuracy is 100% and the test accuracy drops to 96% (77 of 80): the model bends around each mislabeled point, and a few test points near them go wrong.

Next: Module 3B is complete. Part 3 continues with unsupervised learning (P3.C1 onward), and neural networks (Part 4) take the idea of learned lifts further.

Key takeaways

  • If no straight line separates the classes, lift the points with a feature map φ so that a flat boundary in the new space is a curved boundary in the old one. For two rings, φ(x₁, x₂) = (x₁, x₂, x₁² + x₂²) lets a horizontal plane z = h separate them, and that plane is the circle x₁² + x₂² = h back in 2-D.
  • Writing out the lifted features costs too much: the number of monomials of degree at most p in d variables is C(d + p, p), which is 286 for d = 10 and p = 3 and about 81 million for d = 784 and p = 3.
  • The SVM dual and kernel ridge regression use the training points only through dot products xᵢ·xⱼ. A kernel k(x, z) = φ(x)·φ(z) can replace each dot product, and k is computed straight from x and z, so φ is never built.
  • For φ(x) = (x₁², √2 x₁x₂, x₂²), φ(x)·φ(z) = (x·z)². With x = (1, 2) and z = (3, 1) both sides equal 25. The Gaussian kernel exp(−γ‖x − z‖²) equals a dot product in a space with infinitely many coordinates.
  • The width γ (and the penalty C) set the capacity: a small γ gives smooth, simple boundaries; a very large γ lets each point shape only its own neighbourhood, so the model memorizes the training set.
  • A kernel method works with an n × n Gram matrix K, so memory grows like n²: 800 MB for n = 10,000 and 80 GB for n = 100,000 in 64-bit floats. Training costs at least as much, which is why kernel methods are used mostly on small and medium data sets.
Found a mistake? Tell us