Exercise: kernel functions and the kernel trick
Before this unit: Maximum margin and support vectors (previous unit); Day 33: Random forests.
See also: Day 36: Neural networks; Day 35: Gaussian mixtures.
Goal
By the end of this exercise you should be able to:
- lift 2D points with an explicit feature map and explain why a plane up there is a curve down here,
- check by hand that a kernel function equals a dot product of explicit features,
- evaluate an RBF decision function with a few support vectors and sketch its boundary,
- predict what \gamma and C do to an RBF SVM, and recognise an invalid kernel function.
Do the pen-and-paper part first, then the two demos.
Background
| Idea | What it means |
|---|---|
| Feature map | \varphi(\mathbf x): new, usually more, features; a plane in \varphi-space is a curve in \mathbf x-space |
| Kernel function | k(\mathbf x, \mathbf z) = \varphi(\mathbf x)\cdot\varphi(\mathbf z), computed without \varphi (not a convolution kernel) |
| Decision function | f(\mathbf x) = \sum_i \alpha_iy_i\,k(\mathbf x_i, \mathbf x) + b, a sum over the support vectors |
| Polynomial | k = (\mathbf x\cdot\mathbf z + c)^p: all monomials up to degree p |
| RBF | k = e^{-\gamma\|\mathbf x - \mathbf z\|^2}: a similarity; length scale 1/\sqrt\gamma; equals the graph-cut affinity e^{-\Delta^2/2\sigma^2} with \gamma = 1/(2\sigma^2) |
| Kernel matrix | K_{ij} = k(\mathbf x_i, \mathbf x_j); must be symmetric with no negative eigenvalues |
| \gamma and C | small \gamma: nearly linear; large \gamma with large C: an island around every point (overfitting) |
By hand
B1. The quadratic map \varphi(\mathbf x) = (x_1^2,\ \sqrt2\,x_1x_2,\ x_2^2). (a) For \mathbf x = (2, -1) and \mathbf z = (1, 3), compute \varphi(\mathbf x), \varphi(\mathbf z) and their dot product. Compare with (\mathbf x\cdot\mathbf z)^2. (b) The kernel function (\mathbf x\cdot\mathbf z + 1)^2 corresponds to a map with 6 coordinates. Guess it (hint: expand (x_1z_1 + x_2z_2 + 1)^2) and check it on \mathbf x = (1, 2), \mathbf z = (3, 1).
B2. Lift the four XOR points (class -1: (1, 1), (-1, -1); class +1: (1, -1), (-1, 1)) with \varphi(\mathbf x) = (x_1,\ x_2,\ x_1x_2). Write the four lifted points. Which plane separates them? What does it look like in the original plane?
B3. An RBF SVM with \gamma = 1, b = 0 and two support vectors: (0, 0) with \alpha y = +1 and (2, 0) with \alpha y = -1. (a) Compute f at (0, 0), (0.5, 0), (1, 0), (0, 1), (3, 0) and (-1, 0). (b) Where is the boundary f = 0? Sketch it and the two classes’ regions. (c) Far from both support vectors, what is f? What does the SVM say there?
B4. Training points are spaced about 1 apart. For an RBF SVM with \gamma = 0.01, \gamma = 1 and \gamma = 100: (a) what is the length scale 1/\sqrt\gamma, and the similarity k of two neighbouring points? (b) predict the shape of the boundary in each case. Which one overfits, which underfits?
B5. A pixel is described by 40 features. (a) How many coordinates has the explicit map of (\mathbf x\cdot\mathbf z + 1)^2 (all monomials of degree 0, 1 and 2)? How many multiplications does the kernel function need? (b) Which of the two would you compute for 65 536 pixels and 300 support vectors?
B6. A graph cut used contrast weights e^{-\Delta^2/2\sigma^2} with \sigma = 25 grey levels. Which \gamma gives the same function as an RBF kernel function of the grey level?
Math questions
B7 (math). Two training points only: \mathbf x_+ = (3, 1) (class +1) and \mathbf x_- = (1, 2) (class -1), linear kernel function, hard margin. (a) Use \sum_i\alpha_iy_i = 0 to show \alpha_+ = \alpha_- = \alpha, and maximise the dual 2\alpha - \tfrac12\alpha^2\|\mathbf x_+ - \mathbf x_-\|^2 to find \alpha. (b) Recover \mathbf w = \sum_i\alpha_iy_i\mathbf x_i and b (from f(\mathbf x_+) = 1), and the street width. Is the street what you expect?
B8 (math). A “similarity” gives k(\mathbf x, \mathbf x) = k(\mathbf z, \mathbf z) = 1 and k(\mathbf x, \mathbf z) = 2. Find the eigenvalues of the 2 \times 2 kernel matrix. Show that it cannot be a kernel function: compute the squared distance \|\varphi(\mathbf x) - \varphi(\mathbf z)\|^2 it implies.
B9 (math). Show that (\mathbf x\cdot\mathbf z + 1)^2 = \varphi(\mathbf x)\cdot\varphi(\mathbf z) for the 6-coordinate map of B1(b), for all \mathbf x, \mathbf z \in \mathbb R^2.
B1. (a) \varphi(\mathbf x) = (4,\ -2\sqrt2,\ 1), \varphi(\mathbf z) = (1,\ 3\sqrt2,\ 9), dot product 4 - 12 + 9 = 1. \mathbf x\cdot\mathbf z = 2 - 3 = -1, (\mathbf x\cdot\mathbf z)^2 = 1. Equal. (b) (x_1z_1 + x_2z_2 + 1)^2 = x_1^2z_1^2 + x_2^2z_2^2 + 1 + 2x_1z_1x_2z_2 + 2x_1z_1 + 2x_2z_2, so \varphi(\mathbf x) = (1,\ \sqrt2\,x_1,\ \sqrt2\,x_2,\ x_1^2,\ \sqrt2\,x_1x_2,\ x_2^2). Check: \varphi(1, 2) = (1, \sqrt2, 2\sqrt2, 1, 2\sqrt2, 4), \varphi(3, 1) = (1, 3\sqrt2, \sqrt2, 9, 3\sqrt2, 1), dot product 1 + 6 + 4 + 9 + 12 + 4 = 36 = (5 + 1)^2.
B2. (1, 1) \mapsto (1, 1, 1), (-1, -1) \mapsto (-1, -1, 1) (class -1, both at height +1); (1, -1) \mapsto (1, -1, -1), (-1, 1) \mapsto (-1, 1, -1) (class +1, both at height -1). The plane x_3 = 0 separates them: f = -x_1x_2 (i.e. \mathbf w = (0, 0, -1), b = 0). In the original plane the boundary x_1x_2 = 0 is the two axes: class +1 in the 2nd and 4th quadrants.
B3. (a) f(\mathbf x) = e^{-\|\mathbf x\|^2} - e^{-\|\mathbf x - (2, 0)\|^2}: f(0, 0) = 1 - e^{-4} = 0.982; f(0.5, 0) = e^{-0.25} - e^{-2.25} = 0.673; f(1, 0) = e^{-1} - e^{-1} = 0; f(0, 1) = e^{-1} - e^{-5} = 0.361; f(3, 0) = e^{-9} - e^{-1} = -0.368; f(-1, 0) = e^{-1} - e^{-9} = 0.368. (b) f = 0 where both distances are equal: the perpendicular bisector x_1 = 1. Left of it class +1, right of it class -1. (c) Far away both bumps vanish: f \to b = 0, on the boundary. The SVM has no opinion where there were no training points (with b \ne 0 it would default to one class).
B4. (a) \gamma = 0.01: length scale 10, k = e^{-0.01} = 0.99; \gamma = 1: length 1, k = e^{-1} = 0.37; \gamma = 100: length 0.1, k = e^{-100} \approx 0. (b) \gamma = 0.01: every bump covers the whole data set, all points look alike: a nearly straight, smooth boundary, which underfits curved classes. \gamma = 1: bumps overlap with their neighbours: smooth curves on the scale of the data. \gamma = 100: bumps do not even reach the neighbours: each training point gets its own island, every point is a support vector: overfitting (with a large C, zero training errors).
B5. (a) 1 + 40 + 40 + \binom{40}{2} = 1 + 40 + 40 + 780 = 861 coordinates. The kernel function needs one dot product (40 multiplications), one addition and one squaring. (b) The kernel function: 65\,536 \times 300 evaluations of about 40 multiplications each, instead of mapping every pixel to 861 numbers.
B6. \gamma = 1/(2\sigma^2) = 1/(2 \cdot 625) = 0.0008 (per squared grey level).
B7. (a) \alpha_+ y_+ + \alpha_- y_- = \alpha_+ - \alpha_- = 0, so both are \alpha. The dual \sum_i\alpha_i - \tfrac12\sum_{ij}\alpha_i\alpha_jy_iy_j\mathbf x_i\cdot\mathbf x_j = 2\alpha - \tfrac12\alpha^2\|\mathbf x_+ - \mathbf x_-\|^2 (expand \alpha^2(\mathbf x_+\cdot\mathbf x_+ - 2\mathbf x_+\cdot\mathbf x_- + \mathbf x_-\cdot\mathbf x_-)). Setting the derivative to 0: \alpha = 2/\|\mathbf x_+ - \mathbf x_-\|^2 = 2/5 = 0.4. (b) \mathbf w = 0.4\left((3, 1) - (1, 2)\right) = (0.8, -0.4). f(\mathbf x_+) = 2.4 - 0.4 + b = 1 gives b = -1; check f(\mathbf x_-) = 0.8 - 0.8 - 1 = -1. Width 2/\|\mathbf w\| = 2/\sqrt{0.8} = \sqrt5 = 2.236, the distance between the two points: the street is bounded by the two points, and the line is their perpendicular bisector, as expected.
B8. K = \begin{bmatrix}1 & 2\\2 & 1\end{bmatrix} has eigenvalues 1 \pm 2: 3 and -1. If k were \varphi(\mathbf x)\cdot\varphi(\mathbf z), then \|\varphi(\mathbf x) - \varphi(\mathbf z)\|^2 = k(\mathbf x, \mathbf x) + k(\mathbf z, \mathbf z) - 2k(\mathbf x, \mathbf z) = 1 + 1 - 4 = -2 < 0: impossible for a squared length. (The eigenvector (1, -1) is exactly this combination: (1, -1)K(1, -1)^\top = -2.)
B9. \varphi(\mathbf x)\cdot\varphi(\mathbf z) = 1 + 2x_1z_1 + 2x_2z_2 + x_1^2z_1^2 + 2x_1x_2z_1z_2 + x_2^2z_2^2 = (x_1z_1 + x_2z_2)^2 + 2(x_1z_1 + x_2z_2) + 1 = (\mathbf x\cdot\mathbf z + 1)^2.
Explore: lift and cut
Left: points of two classes in the plane (click to add, drag to move). Right: the same points lifted into 3D by a feature map (choose the map in the panel), on the lifted surface (grey), with the plane found by a linear SVM in 3D (orange) and the plane’s cut through the surface (black). Drag the 3D view to rotate it; the buttons give standard views. The left panel shows the cut seen from above: the 2D boundary and the two sides.
V1. Preset ring → plane (paraboloid). Rotate to a side view. Where do the inner points and the ring end up? How many training errors does the plane make? What shape is the cut in 2D?
V2. Preset XOR needs x₁x₂. With the saddle map, how many errors? Switch to the paraboloid map: how many now, and why does it not help? Then try (x_1^2, \sqrt2\,x_1x_2, x_2^2).
V3. Preset two blobs: lifting does not hurt. Errors with the paraboloid map? Now choose (x_1^2, \sqrt2\,x_1x_2, x_2^2): the errors jump. Why? (Look at what happens to a point and its mirror image -\mathbf x.)
V4. Preset two rings: one plane is not enough. Why can no plane separate the classes on the paraboloid? What would?
V1. The inner (red) points sit low on the paraboloid (small x_1^2 + x_2^2), the ring (blue) high. The plane is nearly horizontal between them: 0 training errors, with only 4 support vectors. Its cut through the paraboloid is a circle (an ellipse, if the plane is slightly tilted), seen from above as a closed curve around the inner class.
V2. Saddle map (x_1, x_2, x_1x_2): 0 errors. The paraboloid map: 31 errors of 70: x_1^2 + x_2^2 depends only on the distance from the centre, which says nothing about which diagonal a point is on. The quadratic map also has the product x_1x_2 (as its middle coordinate): 0 errors.
V3. Paraboloid: 0 errors (the map keeps x_1 and x_2; the plane is nearly vertical and its cut is almost a straight line). The map (x_1^2, \sqrt2\,x_1x_2, x_2^2) makes 22 errors of 50: it has no linear terms, so \mathbf x and -\mathbf x are lifted to the same point. Blobs on opposite sides of the centre cannot be told apart. The kernel function (\mathbf x\cdot\mathbf z)^2 has this blind spot; (\mathbf x\cdot\mathbf z + 1)^2 (B1(b)) does not.
V4. On the paraboloid the classes are bands of height: blue low (inside), red in the middle (the ring), blue high (outside). A plane cuts the surface into two parts only, so it can split off one end but not a middle band (14 errors of 110 here). A richer map would do: e.g. adding (x_1^2 + x_2^2)^2, so that two thresholds on the height become one plane, or the RBF kernel function, whose bumps can make any number of closed boundaries.
Explore: kernel functions in 2D
The demo of the last unit, with a kernel function menu (linear, polynomial with degree p, RBF with \gamma). The background is tinted by the sign of f; the solid curve is f = 0, the dashed curves f = \pm 1, the grey band the street; support vectors are ringed. Show the RBF bumps draws a circle of radius 1/\sqrt\gamma around each support vector; show the kernel matrix draws K_{ij} as a heat map below, points sorted by class (blue first).
K1. Preset ring: linear fails, RBF works. Compare linear, polynomial (degree 2) and RBF: training errors and number of support vectors. What does the readout say about the linear street?
K2. Preset XOR: degree 2. Errors with the linear and with the polynomial kernel function (degree 2)? Why exactly degree 2?
K3. Preset γ too large: islands. How many of the 80 points are support vectors? Lower \gamma step by step to 1, 0.32 and 0.1: how do the support vectors and the training errors change? Which setting would you trust on new points?
K4. Preset γ too small: a line again. Compare with the linear kernel function: errors? Raise \gamma until the training errors reach 0.
K5. Tick show the kernel matrix and compare \gamma = 0.01 with \gamma = 100. Describe the matrix in both cases. Relate it to the islands of K3.
K1. Linear: 21 errors of 80, and \mathbf w \approx 0 (the readout reports an infinite street: no line helps, so the SVM puts every point in the same class). Polynomial, degree 2: 0 errors, 13 support vectors, a closed curve. RBF (\gamma = 0.32): 0 errors, 15 support vectors.
K2. Linear: 38 errors of 80. Polynomial, degree 2: 0 errors (20 support vectors). XOR needs the product x_1x_2 (B2), which is a degree-2 monomial; degree 2 is the lowest that contains it.
K3. At \gamma = 20: 79 of 80 points are support vectors, 0 training errors, an island around each point. \gamma = 1: 35 support vectors, 1 error; \gamma = 0.32: 26 support vectors, 2 errors; \gamma = 0.1: 25 support vectors, 5 errors. The training error rises as \gamma falls, but the boundary becomes a smooth curve that follows the two moons instead of every (partly mislabelled) point: \gamma around 0.3–1 is the one to trust. Cross-validation (next unit) makes this choice by measurement.
K4. At \gamma = 0.01: 10 training errors and 40 support vectors, exactly like the linear kernel function (10 errors): the bumps are wider than the data, so f is nearly linear. At \gamma = 0.1: 2 errors; at \gamma = 0.32: 0 errors (25 support vectors).
K5. \gamma = 0.01: almost every entry is close to 1 (every point is “similar” to every other): the matrix carries little information, the boundary is nearly linear. \gamma = 100: the matrix is almost the identity (each point is similar only to itself): every point is its own island, as in K3. In between, the matrix has structure: each point is similar to its neighbours, which mostly belong to its own class.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in svm/src/kernel_trick/exercise.rs. A point is a list of features; the labels are +1 and -1.
C1. quadratic_map(x): the lifted point \varphi(\mathbf x) = (x_1^2,\ \sqrt2\,x_1x_2,\ x_2^2). The checks are the lecture’s “two routes” (\varphi(\mathbf x)\cdot\varphi(\mathbf z) = 25) and B1(a).
C2. kernel(k, x, z): the linear, polynomial (\mathbf x\cdot\mathbf z + c)^p and RBF e^{-\gamma\|\mathbf x - \mathbf z\|^2} kernel functions. The checks are B1 and B4(a).
C3. decision(points, labels, alpha, b, k, x): the decision value of a kernel SVM, a signed sum of similarities to the support vectors. The checks are your values of B3 and the lecture’s “two bumps”.
f = b
for every training point i with α_i > 0: # the support vectors
f = f + α_i · y_i · k(x_i, x)
C4. train_smo(points, labels, k, c, tol, max_steps): find the \alpha_i (slide “The math: how it is solved”). The dual keeps \sum_i \alpha_i y_i = 0, so SMO changes two \alphas at a time, the pair that most violates the optimality conditions:
K[i][j] = k(x_i, x_j) for all pairs; α = 0; g = 0 # g_t = Σ_l α_l y_l K[l][t]
repeat:
F_t = g_t − y_t for every point t
i = argmin F_t over the points whose α_t may move with y_t
(y_t = +1 and α_t < C, or y_t = −1 and α_t > 0)
j = argmax F_t over the points whose α_t may move against y_t
(y_t = −1 and α_t < C, or y_t = +1 and α_t > 0)
if F_j − F_i < 2 · tol: stop, with b = −(F_i + F_j)/2
η = K[i][i] + K[j][j] − 2 K[i][j]
α_j ← α_j + y_j (F_i − F_j)/η, clipped so that α_i and α_j stay in [0, C]
α_i ← α_i + y_i y_j (old α_j − new α_j) # keeps Σ α y
update every g_t with the two changes
The checks: B7 (\alpha = 0.4, b = -1), the previous unit’s example (\alpha = (0.25, 0.25, 0.5, 0) as in its B9), and XOR (B2), which the degree-2 polynomial kernel function separates and the linear one does not.
Then cargo run -p svm -- kernel-trick and open the pictures in out/kernel-trick/: the street in grey, the boundary in black, the support vectors ringed.
C5. The ring around a blob (ring-*.png) and XOR (xor-*.png). For each kernel function, how many training points are wrong, and how many are support vectors? What does the linear SVM do with the ring?
C6. Two noisy half-moons, for \gamma = 0.1, 2, 100 and C = 0.1, 1000 (moons-*.png). The program also classifies 2000 new points from the same recipe. Which setting is best on the new points? Which settings have 0 training errors, and are they good? Describe the pictures for \gamma = 100.
C7. Count the cost of predicting one pixel with 300 support vectors and 40 features with the RBF kernel function, and compare with the explicit map of B5.
The model solution is svm/src/kernel_trick/solution.rs in the download.
C5. Ring: linear 20 of 60 wrong with 47 support vectors (it gives up the 20 inner points: every point is called blue); degree 2: 0 wrong, 6 support vectors, a closed curve; RBF (\gamma = 0.5): 0 wrong, 15 support vectors. XOR: linear 30 of 60 wrong with 57 support vectors; degree 2: 0 wrong with only 5 support vectors.
C6.
| \gamma | C | support vectors | training errors | new points wrong |
|---|---|---|---|---|
| 0.1 | 0.1 | 78 | 10 | 17.2 % |
| 0.1 | 1000 | 13 | 2 | 13.6 % |
| 2 | 0.1 | 73 | 4 | 10.8 % |
| 2 | 1000 | 17 | 0 | 10.1 % |
| 100 | 0.1 | 80 | 0 | 32.8 % |
| 100 | 1000 | 78 | 0 | 19.1 % |
The best on new points is \gamma = 2, C = 1000 (10.1 %): its boundary is a smooth S between the moons. \gamma = 100 also has 0 training errors, but is the worst on new points: the bumps reach only 1/\sqrt{100} = 0.1, nearly every point is a support vector, and the red region is a tight outline around the red points, with a separate island around one isolated red point (large C); away from the points f falls back to b. With C = 0.1 the whole picture lies inside the street, and the boundary is a tight outline around the blue points instead. Zero training errors say nothing about new points. At \gamma = 0.1 the boundary is almost a straight line: underfitting.
C7. One RBF evaluation needs 40 subtractions, 40 squares and an exponential: about 300 \times 80 = 24\,000 operations per pixel. The explicit degree-2 map of B5 has 861 coordinates per pixel, but the RBF kernel function’s map has infinitely many: only the kernel route is possible.
Where this leads
The next unit takes the SVM back to images: pixel classification with a feature stack, where standardising the features, choosing (C, \gamma) by cross-validation by stroke, and handling more than two classes are what makes it work.