Machine learningLoading progress…

Kernels

Compare nearest-neighbor, naive Bayes and margin-based predictions using their actual assumptions.

When no straight line works, lift the data

Look at 1D data where class 1 sits at both ends and class 0 in the middle. No single cut on the number line separates them: the best cut still gets 4 points wrong. Now give every point a second coordinate, its square, so x becomes (x, x²). The points land on a parabola, and the outer points are higher than the inner ones. A horizontal line separates them. In the original space that line is two cuts at ±√t.

-4-2024original: x only (no single cut works)
0481216lifted: (x, x squared)
Rule: class 1 when x² > t, that is when |x| > 1.7321
Mistakes with this line: 0 of 14. The best single cut on x alone makes at least 4.
Move the line in the lifted view. The two purple marks on the number line follow it.

That is the idea behind feature maps: a boundary that is linear in a higher-dimensional space can be curved in the original one.

The kernel trick: get the inner product without building the features

A margin classifier only ever needs inner products between points. A kernel K(a, b) is a function that returns the inner product of the lifted points, without constructing them. A concrete case in 2D: lift with φ(v) = (v₁², √2·v₁v₂, v₂²). For a = (1, 2) and b = (3, −1):

a · b = 1, so (a · b)² = 1
φ(a) = (1, 2.8284, 4), φ(b) = (9, -4.2426, 1)
φ(a) · φ(b) = 1

The same number, but the kernel only needed a dot product and a square. The RBF (Gaussian) kernel K(a, b) = exp(−γ‖a−b‖²) corresponds to a feature space with infinitely many coordinates, yet one evaluation costs the same as a distance. It is 1 for identical points and falls towards 0 with distance; γ sets how fast. A valid kernel must give a symmetric, positive semidefinite matrix for any set of points. An arbitrary similarity function, such as the negative distance, is not guaranteed to.

Gamma is the width dial

Below, the boundary between two classes is a wave, with 8% of the labels flipped as noise. A kernel classifier (kernel ridge regression on labels of −1 and +1) uses the RBF kernel. Small γ makes every bump huge, so the model is nearly a smooth bowl and cannot follow the wave: at γ = 0.003 training accuracy is 76.7% and validation 77%. Large γ gives each training point its own tiny bump: at γ = 30 training accuracy is 100% while validation falls to 81.3%. In between, γ = 0.3 reaches 85.3% on validation.

class 0class 1
Training accuracy 96.7%, validation accuracy 80.7% (300 unseen points).
This is in between.
gamma0.0030.010.030.10.3131030100
train7777778290979898100100
valid.77787985858180808181

The classifier is kernel ridge regression on labels of -1 and +1 with lambda = 0.3: the same kernel idea as an SVM, with a simpler fit.

Slide gamma from left to right and watch the regions go from smooth, to wavy, to speckled. Compare the two accuracy rows.

Predict first. You raise gamma until training accuracy is 100%. Is the model now the best choice?

The common mistake

Chapter context

Different model families turn different notions of similarity into predictions. A geometric distance, a conditional-independence assumption and a kernel are distinct modeling decisions rather than variations of the same formula.

Chapter reference: math, worked example & code

This section belongs to the whole chapter, so it is the same on every lesson in it and may cover a different lesson's topic. The code for the experiment you just ran is inside the experiment itself.

Math and notation

∥x−y∥22=∑j(xj−yj)2,K(x,y)=exp⁡(−γ∥x−y∥2),  γ>0.\|x-y\|_2^2=\sum_j(x_j-y_j)^2,\quad K(x,y)=\exp(-\gamma\|x-y\|^2),\;\gamma>0.

For SVM canonical boundary planes wTx+b=±1w^Tx+b=\pm1, their separation is 2/∥w∥2/\|w\|. A naive-Bayes posterior is proportional to P(c)∏jP(xj∣c)P(c)\prod_jP(x_j\mid c).

A numerically convenient naive-Bayes decision rule is

c^=arg⁡max⁡c[log⁡P(c)+∑jlog⁡P(xj∣c)].\hat c=\arg\max_c\left[\log P(c)+\sum_j\log P(x_j\mid c)\right].

This avoids multiplying many small probabilities, but it does not remove the need to handle zero likelihoods or choose an appropriate feature distribution.

Worked example

For query [1,1], squared distances to [0,0], [2,1] and [3,3] are 2, 1 and 8. The nearest point is [2,1]. Separately, a canonical SVM with w=[3,4] has norm 5 and margin width 2/5=0.4.

Reference code

The following example uses the Python standard library and does not call a remote service.

from math import sqrt, isclose
q = [1,1]
points = [[0,0],[2,1],[3,3]]
distances = [sum((a-b)**2 for a,b in zip(q,p)) for p in points]
assert distances == [2,1,8]
assert distances.index(min(distances)) == 1
assert isclose(2/sqrt(3**2+4**2), .4)

Python examples are provided for study and local execution; this page does not execute Python.

Common mistakes

Changing feature scale can change neighbors. Kernel similarity is not automatically calibrated probability. The SVM margin formula assumes a particular normalization of the separating planes.