Kernels
Look again at the dual, Equation 12.41. The examples enter only through — there is no term pairing an example with a parameter. So if the examples are first mapped through some , the only thing that changes is that inner product. Section 12.4 takes that observation and runs with it.
A kernel is an inner product you never compute
Section titled “A kernel is an inner product you never compute”A kernel is a similarity function for which such a feature map into some Hilbert space exists. Replacing by in the dual is the kernel trick, and the matrix with is the kernel matrix — the same Gram matrix Chapter 10 used for the trick of §10.5.
For the degree-2 polynomial kernel the feature map can be written out in full, so the identity is checkable:
import itertools
import numpy as np
def k_poly(A, B, degree=2, c=1.0):
return (A @ B.T + c) ** degree
def phi_poly2(Xa, c=1.0):
"""The explicit feature map of (x'z + c)^2."""
n, D = Xa.shape
cols = [np.full(n, c)] # constant
cols += [np.sqrt(2 * c) * Xa[:, i] for i in range(D)] # linear
cols += [Xa[:, i] ** 2 for i in range(D)] # squares
cols += [np.sqrt(2.0) * Xa[:, i] * Xa[:, j] # cross terms
for i, j in itertools.combinations(range(D), 2)]
return np.column_stack(cols)
rg = np.random.default_rng(0)
A, B = rg.normal(0, 1, (60, 3)), rg.normal(0, 1, (40, 3))
PA, PB = phi_poly2(A), phi_poly2(B)
print(f"explicit feature dimension : {PA.shape[1]}")
print(f"max |k(x,z) - <phi(x), phi(z)>| : "
f"{np.abs(k_poly(A, B) - PA @ PB.T).max():.3e}")explicit feature dimension : 10
max |k(x,z) - <phi(x), phi(z)>| : 2.132e-14The saving is not visible at . It becomes the whole point as grows, because the explicit map has coordinates:
| degree | degree | degree | the kernel | |
|---|---|---|---|---|
| multiplications | ||||
| multiplications | ||||
| multiplications | ||||
| multiplications | ||||
| multiplications |
At a degree-5 expansion has over eight trillion coordinates. The kernel takes one inner product of length and raises it to the fifth power.
What “infinite-dimensional” looks like from outside
Section titled “What “infinite-dimensional” looks like from outside”The book says the RBF kernel’s “corresponding feature space is infinite dimensional. In this case, we cannot explicitly represent the feature space.” That is a statement about something you cannot see — but it has a consequence you can measure.
A kernel whose feature map has dimension has a Gram matrix of rank at most , however many points you feed it. So watch the rank as grows:
from scipy.special import comb
def k_rbf(A, B, gamma=0.5):
d2 = ((A[:, None, :] - B[None, :, :]) ** 2).sum(-1)
return np.exp(-gamma * d2)
rg = np.random.default_rng(3)
print(f"{'kernel':>24} {'C(D+p,p)':>10} {'N=50':>6} {'N=100':>7} "
f"{'N=200':>7} {'N=400':>7} {'N=800':>7}")
for name, kf, fd in (
("polynomial, degree 2", lambda Z: k_poly(Z, Z, 2), int(comb(4, 2))),
("polynomial, degree 3", lambda Z: k_poly(Z, Z, 3), int(comb(5, 3))),
("polynomial, degree 5", lambda Z: k_poly(Z, Z, 5), int(comb(7, 5))),
("RBF, gamma = 0.5", lambda Z: k_rbf(Z, Z, 0.5), None),
("RBF, gamma = 5.0", lambda Z: k_rbf(Z, Z, 5.0), None)):
rs = [int(np.linalg.matrix_rank(kf(rg.normal(0, 1, (n, 2)))))
for n in (50, 100, 200, 400, 800)] # numpy's default tolerance
print(f"{name:>24} {str(fd) if fd else 'infinite':>10} "
f"{rs[0]:>6} {rs[1]:>7} {rs[2]:>7} {rs[3]:>7} {rs[4]:>7}") kernel C(D+p,p) N=50 N=100 N=200 N=400 N=800
polynomial, degree 2 6 6 6 6 6 6
polynomial, degree 3 10 10 10 10 10 10
polynomial, degree 5 21 21 21 21 21 21
RBF, gamma = 0.5 infinite 50 93 125 154 171
RBF, gamma = 5.0 infinite 50 100 200 392 597The polynomial rows are constant and equal to exactly. Eight hundred points in the plane cannot make a degree-3 polynomial kernel’s feature space bigger than ten dimensions — the data is irrelevant, the kernel decides.
The RBF rows never level off. That is what having no finite feature map looks like from the outside: no matter how many points you add, the Gram matrix keeps finding new directions.
The two RBF rows also say something the book does not: controls how fast the feature space fills up. A narrow kernel () reaches full rank up to and is still at of ; a wide one () is already down to of , because its spectrum decays faster and most directions fall below floating-point resolution.
Not every similarity function is a kernel
Section titled “Not every similarity function is a kernel”Equation 12.53 requires every kernel matrix to be positive semidefinite. The frequently-used “sigmoid kernel” is not:
| function | smallest eigenvalue of | PSD? |
|---|---|---|
| linear | yes | |
| polynomial, degree | yes | |
| RBF, | yes | |
| no |
Ten of its eigenvalues are negative, the most negative being . The first three rows are negative only at rounding level; the fourth is negative by fifty-five.
This matters beyond tidiness. Equation 12.41’s objective is , and it is convex only when is PSD. With a negative eigenvalue the dual is a non-convex quadratic, the duality guarantee of page 1206 no longer applies, and whatever the solver returns is not the solution to the problem Section 12.3 derived.
Figure 12.10, reproduced
Section titled “Figure 12.10, reproduced”Two concentric rings. No line in the plane separates them.
kernel train acc held-out acc support vectors
linear 0.6417 0.6367 120
polynomial, degree 2 1.0000 1.0000 6
polynomial, degree 3 1.0000 1.0000 9
RBF, gamma = 0.5 1.0000 1.0000 18The linear kernel gets and uses all examples as support vectors — a fit that has given up and is spending every multiplier. The degree-2 kernel gets everything right with six.
Why six is enough is worth spelling out, because it explains the whole section:
rad2 = (XC ** 2).sum(1) # the squared radius of each point
print(f"squared radius, class +1 : [{rad2[YC > 0].min():.4f}, "
f"{rad2[YC > 0].max():.4f}]")
print(f"squared radius, class -1 : [{rad2[YC < 0].min():.4f}, "
f"{rad2[YC < 0].max():.4f}]")
print(f"separable on that single coordinate : "
f"{bool(rad2[YC > 0].max() < rad2[YC < 0].min())}")squared radius, class +1 : [0.2941, 2.1170]
squared radius, class -1 : [6.4572, 12.6957]
separable on that single coordinate : TrueThe two classes are separated by one derived feature, , and the degree-2 map contains and as two of its six coordinates. A threshold on their sum is a hyperplane in that space. The kernel never builds the space; it just computes the inner products as though it had.
-
pch.quizShowAnswer
B — Because in the dual the examples appear only through inner products with each other, never paired with a parameter — so a feature map changes nothing but that one matrix
-
pch.quizShowAnswer
C — Exactly 10, which is C(D + p, p) — and it is 10 at N = 50, 100, 200, 400 and 800 alike
-
pch.quizShowAnswer
B — That the rank never saturates — unlike the polynomial rows it keeps climbing, which is what no finite feature map looks like from outside. The shortfall below N is the spectrum decaying past floating-point resolution
-
pch.quizShowAnswer
C — Equation 12.41's objective is convex only when K is positive semidefinite; with a negative eigenvalue the dual is a non-convex quadratic and the duality guarantee no longer applies
Exercises
Section titled “Exercises”Exercise 1 – Check that the kernel is an inner product
Section titled “Exercise 1 – Check that the kernel is an inner product”Exercise 2 – Watch a feature space saturate
Section titled “Exercise 2 – Watch a feature space saturate”Exercise 3 – Find a similarity function that is not a kernel
Section titled “Exercise 3 – Find a similarity function that is not a kernel”Recall card
Section titled “Recall card”- In the dual the examples appear only through their inner products with each other, never paired with a parameter, which is what makes a feature map cost one line.
- A kernel is a similarity function with a hidden feature map, and the kernel trick is using it without ever building that map.
- The explicit map of a degree-p polynomial has C(D + p, p) coordinates. At D equal to a thousand and degree five that is over eight trillion; the kernel is one inner product raised to a power.
- A feature space of dimension M gives a Gram matrix of rank at most M, which turns an invisible claim into a measurable one.
- Polynomial ranks saturate exactly. Degree two, three and five give rank 6, 10 and 21 at every N from 50 to 800 — the data cannot enlarge the feature space.
- The RBF’s rank never levels off, climbing from 50 to 171 as N goes from 50 to 800. That is what having no finite feature map looks like from outside.
- The bandwidth controls how fast the feature space fills. A narrow RBF reaches full rank up to N equal to 200 and 597 of 800; a wide one decays faster and reaches far less.
- Equation 12.53 is a requirement, not a convention. The dual’s objective is convex only when the kernel matrix is positive semidefinite.
- The tanh similarity function fails it, with ten negative eigenvalues and a smallest of minus 55.44, against roundoff-level negatives for the genuine kernels.
- Figure 12.10 reproduced: on two concentric rings a linear kernel reaches 64 percent and spends all 120 examples as support vectors, while a degree-2 kernel reaches 100 percent on six.
- Six suffices because the classes are separated by one derived feature, the squared radius, and the degree-2 map contains both squared coordinates.
- The decision boundary is curved and the hypothesis class is not. It is a hyperplane in the feature space, seen from the input space.
- Three unrelated things in this book are called a kernel: this one, the null space of Section 2.7.3, and the smoothing kernel of Section 11.5.
Next: Numerical Solution — §12.5, the subgradient of a loss that is not differentiable, and both SVMs written as standard quadratic programs.
pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading