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 and , but it is a very simple function of them. Its square is
Give every point this third coordinate. The map from the original coordinates to the new ones is called a feature map, written (the Greek letter phi):
A point on the inner ring, at radius about 1, gets about 1. A point on the outer ring, at radius about 2, gets 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 below 1.6 and every outer-ring point has above 2.8. A flat horizontal plane anywhere between those heights, for example (a circle of radius about 1.48), separates all 60 points, a clean 100%.
Things to try, in order:
- 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.
- 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.
- 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 were new columns, and the model stayed linear in its weights. A linear method on lifted features gives a nonlinear method on .
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 : all products of the inputs with total power at most , including the constant 1. For two inputs and , that is , six features. The count for inputs and degree at most is
(P3.A3 gave one example: 286 weights for , .) It grows quickly:
| Inputs | Degree | Monomials |
|---|---|---|
| 2 | 2 | 6 |
| 10 | 3 | 286 |
| 100 | 3 | 176,851 |
| 784 (a 28 × 28 image) | 2 | 308,505 |
| 784 | 3 | 80,931,145 |
A small grey-scale image of 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 (label ), and (label ) had multipliers . The weight vector turned out to be a weighted sum of the training points:
which gives 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 :
The prediction for a new point also needs only dot products with the training points:
In the 1-D example, with , the same line as before. Only the support vectors, the points with , contribute to the sum.
Now apply the lift. If you run the same algorithm on instead of , every dot product becomes , 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
the dot product of the two points after the lift. If there is a formula for that uses and directly, we can plug it in and never compute . 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
The strange-looking is chosen so that the cross term gets the right weight. Take and :
- and .
- Dot product in the lifted space: .
- Original dot product: , and .
The two ways agree. In general,
So the kernel 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 inputs, the lifted space for this kernel has coordinates (3 for , 307,720 for ), yet the kernel costs one dot product in numbers plus one squaring.
The variant also adds the constant and linear terms. It corresponds to six features, and equals 36 for the same and . The run below checks the identity on 1,000 random pairs.
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: . No lift at all, the ordinary algorithm.
- Polynomial: with . With it stands for all monomials up to degree (the above), with particular weights. With it stands for the monomials of degree exactly only. Evaluating takes about multiplications, whatever is.
- RBF or Gaussian: with . 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: . Then
Each term is a polynomial kernel of degree , 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 , and the kernel is , and the first 10 terms of the series already give .
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 . For two points at distance 1 the Gram matrix has rows and , with eigenvalues and . A negative eigenvalue means that no lifted space exists, so this function is not a kernel.
The Gram matrix
For a training set of points, collect all the kernel values in an table, the Gram matrix (or kernel matrix):
It is symmetric (), 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 matrix; its smallest eigenvalue is not below , 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:
and only the support vectors () are in the sum. In the Gaussian case this reads as a vote: each support vector contributes a bump of height centred on itself, and adds the bumps up.
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: , where each row of is one lifted point. There is an equivalent form that uses an matrix instead of a one. Writing ,
where is the Gram matrix. Only appears, so 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, with targets , and the Gaussian kernel with . The Gram matrix entries are for neighbours and for the outer pair:
- With the solution is and the curve passes exactly through the three targets. At and it predicts .
- With the solution is . The curve now misses the targets slightly (it gives at the training points) and predicts between them. The penalty 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 at work, which comes next.
Go deeper From the feature form of ridge regression to the Gram-matrix form
For any matrix and , the identity holds. (Multiply both sides by the two matrices in parentheses to see it.) It turns the weights into with . A prediction is then . A quick NumPy check with random matrices (8 points, 5 features, ) gives equal weight vectors to about . Notice the trade: the feature form solves a system of size (the number of features), the Gram form one of size (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 and the penalty control flexibility
A kernel does not remove the capacity question (P3.A3, P3.A5). It moves it into two settings.
- in the Gaussian kernel. says how fast similarity falls with distance. It is often described through the bandwidth , with : a large means a small . A small makes every point similar to many others, so the boundary is smooth and simple, and it can underfit. A very large 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.
- in the soft-margin SVM (P3.B6). is the price of a margin violation. A small tolerates many violations, giving a wide margin and a simpler boundary. A large 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 (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 with :
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 underfits (77% training). Large memorizes: at the training accuracy is 100% while the test accuracy drops to 61.5%. This is the U-shape of P3.A5 with as the knob. On this data matters much less than . 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 , and the boundary grows small islands around the mislabeled points.
Two practical notes. The right depends on the scale of the inputs, so scale the features first (P3.A11), and choose and on validation data (P3.A4), never on the test set. Scikit-learn’s default gamma="scale" sets , where is the number of features and is the variance of all entries of the training matrix.
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 to 1.000 at and above, while the test accuracy peaks at 1.000 for and falls to 0.887 at and 0.863 at . 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 is a valid kernel when every Gram matrix it produces is symmetric and positive semi-definite. Then some feature map exists with , and every formula above that has a dot product can take 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 matrix
The Gram matrix has entries for training points, and everything above reads it. That is the weak spot of kernel methods:
- Memory. Explicit features cost memory proportional to × (number of features); a kernel method needs , which is smaller only when the lifted space is huge. In 64-bit floats, needs 8 MB, needs 800 MB, needs 80 GB and needs 8 TB.
- Time. Solving kernel ridge regression takes time proportional to . Kernel SVM solvers usually scale somewhere between and in practice, depending on the data and on and .
- 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 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 from the data in place of fixing a kernel (P4.3).
Quiz
Check your understanding
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?
The inner ring has small z and the outer ring large z, so a horizontal plane lies between them. The plane z = h is the set of points with x₁² + x₂² = h, a circle. A linear classifier on the lifted features can do what no linear classifier on the original coordinates can. The boundary becomes a straight line in 2-D only when the plane has no z component. The rings do not get the same z: their values differ (about 1 against about 4).
What does the kernel trick avoid?
The kernel k(x, z) returns φ(x)·φ(z) directly from x and z, so the lifted vectors are never built. The labels are still used, C is still chosen, and a similarity between points is still computed; the kernel replaces the original dot product with a different similarity.
For x = (1, 2) and z = (3, 1), what is the kernel value k(x, z) = (x·z)², and where does it come from?
x·z = 3 + 2 = 5, so the kernel is 5² = 25, and the lifted dot product is 9 + 12 + 4 = 25. The ordinary dot product is 5 but it is not the kernel value. The number 36 belongs to the kernel (x·z + 1)², a different kernel.
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?
This is the overfitting pattern, and an overly large γ is a typical cause. A smaller γ makes the model smoother and simpler. A larger γ, alone or together with a larger C, pushes the model to memorize the training points even more. Training longer does not apply: the fit is already perfect on the training points, and the problem is that it does not carry over to new points.
You have 1,000,000 training examples. Why is a standard kernel SVM or kernel ridge regression hard to use?
The n × n Gram matrix has 10⁶ × 10⁶ = 10¹² entries, and each 64-bit float takes 8 bytes. The method itself has no limit on labels or on how many points a kernel can compare, and it never needs the explicit coordinates; the cost of the pairs is the problem.
Exercises
- How many monomials of degree at most 2 are there for inputs? List them.
Show answer
: ; ; ; . - For and , compute and with .
Show answer
, so the kernel is . and , so the dot product is . They agree. - For the Gaussian kernel with , what is when ? And for ?
Show answer
for and for . The smaller treats distant points as still quite similar. - In the dual SVM of P1.F7 (points with labels and multipliers ), use with to compute and say which points matter.
Show answer
. Only the support vectors ( and , with ) appear in the sum; the point has . - A data set has examples. Estimate the memory of its Gram matrix in 64-bit floats. How much less in 32-bit?
Show answer
entries, times 8 bytes is 3.2 GB; in 32-bit floats (4 bytes) it is 1.6 GB. - Why can a decision tree not use the kernel trick, while an SVM can?
Show answer
A tree splits on single coordinates ( 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. - In the widget’s RBF view, tick mislabel 4 training points and compare with . What happens to the training accuracy and the test accuracy, and why?
Show answer
At the training accuracy is 93% (56 of 60) and the test accuracy 100%: the smooth model ignores the four wrong labels. At 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.