Chapter 06

Kernel Methods

The kernel trick gives linear models non-linear superpowers without ever computing the feature map. The dual representation of ridge regression, valid kernels and Mercer's theorem, the kernel zoo (linear, polynomial, RBF), RBF networks and Nadaraya–Watson, and Gaussian processes with calibrated uncertainty — all from one idea: replace inner products with $k(\mathbf{x},\mathbf{x}')$.

Reading: ~46 min Interactive: 9 widgets Source: Bishop Ch. 6

01 · Motivation

Why does this matter?

Chapter 02 ended on a remarkable observation: a linear model with cleverly chosen basis functions ϕ(x)\boldsymbol{\phi}(\mathbf{x}) can fit almost any shape. Polynomials, Gaussians, sigmoids — pick the right ϕ\boldsymbol{\phi} and the same closed-form formula w^=(ΦΦ)1Φt\hat{\mathbf{w}} = (\boldsymbol{\Phi}^\top \boldsymbol{\Phi})^{-1}\boldsymbol{\Phi}^\top \mathbf{t} does the rest.

But there’s a catch — actually three.

Feature explosion

A quadratic mapping on a 100-feature input creates roughly 1002/25000100^2/2 \approx 5000 new features. A degree-10 polynomial creates (11010)4.6×1013\binom{110}{10} \approx 4.6 \times 10^{13}. You cannot even store the design matrix, let alone invert anything.

Infinite-dimensional features

For some problems the natural feature space has infinitely many dimensions (every smooth bump centred at every point of Rd\mathbb{R}^d). The matrix ΦΦ\boldsymbol{\Phi}^\top \boldsymbol{\Phi} literally does not fit in memory because it has no finite shape.

The input isn't a vector

Strings, graphs, sets, DNA sequences, documents — these objects don’t come with coordinates. You can’t just type xx\mathbf{x}^\top \mathbf{x}'. And yet you’d like to classify and regress on them.

The kernel trick solves all three at once. Its central insight is so simple it almost feels like cheating.

key

The whole chapter in one sentence

If your algorithm only ever uses the data through inner products ϕ(x)ϕ(x)\boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}'), then you don’t need ϕ\boldsymbol{\phi} at all. Replace each inner product with a single function k(x,x)k(\mathbf{x}, \mathbf{x}') — the kernel — and you’ve quietly upgraded a linear algorithm into a non-linear one, no matter how large or infinite the implicit feature space is.

Three payoffs follow immediately. First, you can use feature spaces so large you couldn’t write them down — even infinite ones — because the kernel computes the inner product directly. Second, you can define kernels on non-vector objects: a kernel on two strings, or two graphs, or two sets, is just a single real number that says “how similar are these two things?”. Third, the same trick instantly upgrades half a dozen algorithms you already know: ridge regression (this chapter), the perceptron, PCA, and most famously SVMs (Chapter 07).

The price you pay is computational. Kernel methods are memory-based — like nearest neighbours, the training points live inside the model and prediction touches all of them. For a training set of size NN, prediction costs roughly O(N)O(N) and training costs roughly O(N3)O(N^3). This is the trade-off the chapter circles back to repeatedly.

02 · Intuition

The idea in plain language

Imagine you’re given a dataset that no straight line can separate. Reds in the middle, blues around the edge — a classic frustration. You stare at the picture and think: “if only I could see this data from a higher viewpoint, maybe the classes would fall apart cleanly.” That instinct is exactly right. The kernel trick formalises it.

Lifting data to a higher dimension

Take a one-dimensional dataset that no line can split: two red points at x=1x = -1 and x=+1x = +1, one blue point at x=0x = 0. In 1D this is hopeless. But now apply the simple map x(x,x2)x \mapsto (x, x^2). Suddenly every point lives in 2D, and a horizontal line at x2=0.5x^2 = 0.5 splits them cleanly. We didn’t change the data. We changed the space.

That’s the geometric intuition. Push the data into a higher-dimensional space, do something linear there, project the answer back. Polynomial features, Gaussian bumps, sigmoid steps — every basis function from Ch. 02 was secretly doing this.

The trick: skip the lift, keep the answer

Here is where the magic enters. Suppose we want to do ridge regression in a feature space with a million dimensions. The normal pipeline says: build ΦRN×106\boldsymbol{\Phi} \in \mathbb{R}^{N \times 10^6}, then form ΦΦR106×106\boldsymbol{\Phi}^\top \boldsymbol{\Phi} \in \mathbb{R}^{10^6 \times 10^6}, then invert it. The first matrix barely fits in RAM; the second does not exist on any computer.

But notice: in the closed-form OLS pipeline, the feature vectors only ever appear inside dot products. If we can compute those dot products cheaply, without explicitly building ϕ(x)\boldsymbol{\phi}(\mathbf{x}), we win. Take the polynomial example. In 2D, the quadratic feature map is ϕ(x)=(x12,2x1x2,x22)\boldsymbol{\phi}(\mathbf{x}) = (x_1^2,\, \sqrt{2}\,x_1 x_2,\, x_2^2). Now compute (xx)2(\mathbf{x}^\top \mathbf{x}')^2 directly and expand it:

(xx)2  =  (x1x1+x2x2)2  =  x12x12+2x1x2x1x2+x22x22  =  ϕ(x)ϕ(x).(\mathbf{x}^\top \mathbf{x}')^2 \;=\; (x_1 x'_1 + x_2 x'_2)^2 \;=\; x_1^2 x'^2_1 + 2 x_1 x_2\, x'_1 x'_2 + x_2^2 x'^2_2 \;=\; \boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}').

The right-hand side is exactly the inner product in the 3-dimensional quadratic feature space. The left-hand side never visited that space. We computed an inner product in 3D using only operations in 2D.

That single observation is the kernel trick. Crank it up to degree pp and you get all monomials of degree p\le p for free. Push it to a Gaussian kernel and you implicitly visit an infinite-dimensional feature space — every smooth bump at every centre — while doing one exponential and one subtraction.

tip

A useful mantra

“A kernel is a similarity score between two inputs.” More similar inputs get a higher score. Mathematically it has to be a particular kind of similarity (an inner product in some space), but the intuition is exactly the everyday meaning of the word. Whenever you see k(x,x)k(\mathbf{x}, \mathbf{x}'), read it as “how alike are these two things, in the eyes of the model?”.

Two viewpoints, same kernel

The kernel function quietly wears two hats.

Algebraic view (feature space)

k(x,x)=ϕ(x)ϕ(x)k(\mathbf{x}, \mathbf{x}') = \boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}'). The kernel is an inner product in some (possibly huge or infinite) implicit feature space. Use this view when deriving the dual ridge solution, the SVM dual, or any closed form. It’s where Mercer’s theorem and the validity rules live.

Probabilistic view (covariance)

k(x,x)=cov(y(x),y(x))k(\mathbf{x}, \mathbf{x}') = \mathrm{cov}\bigl(y(\mathbf{x}),\, y(\mathbf{x}')\bigr). The kernel encodes how much function values at two inputs are expected to co-vary. Use this view for Gaussian processes, Bayesian optimisation, or any time you need calibrated uncertainty. The same kk — read differently.

Both viewpoints describe the same object — choose whichever helps you reason about the problem at hand. The exam tends to test the algebraic one; real applications usually live in the geometric one.

03 · Formalism

Definitions and equations

The notation builds directly on Ch. 02 — most of what follows is “linear regression, but inner products replaced by k(,)k(\cdot, \cdot)“.

φ(x)
a (possibly very high or infinite-dimensional) feature map ϕ:XF\boldsymbol{\phi} : \mathcal{X} \to \mathcal{F}.
k(x, x′)
the kernel ϕ(x)ϕ(x)\boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}') — a similarity score.
Φ
the N×MN \times M design matrix; row nn is ϕ(xn)\boldsymbol{\phi}(\mathbf{x}_n)^\top.
K
the N×NN \times N Gram matrix, K=ΦΦ\mathbf{K} = \boldsymbol{\Phi}\boldsymbol{\Phi}^\top, entries Knm=k(xn,xm)K_{nm} = k(\mathbf{x}_n, \mathbf{x}_m).
a
the dual coefficient vector; the weights become w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a}.
λ
the ridge regularisation strength (= the GP noise variance σn2\sigma_n^2).

The kernel function

The kernel associated with a feature map ϕ\boldsymbol{\phi} is

Kernel
k(x,x)    ϕ(x)ϕ(x).k(\mathbf{x}, \mathbf{x}') \;\equiv\; \boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}').

Two essential properties drop out for free: symmetry k(x,x)=k(x,x)k(\mathbf{x}, \mathbf{x}') = k(\mathbf{x}', \mathbf{x}) and positivity k(x,x)=ϕ(x)20k(\mathbf{x}, \mathbf{x}) = \|\boldsymbol{\phi}(\mathbf{x})\|^2 \ge 0.

Two important families:

  • Stationary kernels: k(x,x)=k(xx)k(\mathbf{x}, \mathbf{x}') = k(\mathbf{x} - \mathbf{x}') — only the difference between inputs matters. Translation-invariant.
  • Radial / homogeneous kernels: k(x,x)=k(xx)k(\mathbf{x}, \mathbf{x}') = k(\|\mathbf{x} - \mathbf{x}'\|) — only the distance matters. Rotation- and translation-invariant.

The simplest kernel of all is the linear kernel, corresponding to the identity feature map ϕ(x)=x\boldsymbol{\phi}(\mathbf{x}) = \mathbf{x}: klin(x,x)=xxk_{\text{lin}}(\mathbf{x}, \mathbf{x}') = \mathbf{x}^\top \mathbf{x}'. All kernels can be thought of as generalisations of this.

Dual representation of ridge regression

Recall the regularised least-squares objective from Ch. 02:

L(w)  =  12n=1N(wϕ(xn)tn)2+λ2ww.L(\mathbf{w}) \;=\; \tfrac{1}{2}\sum_{n=1}^{N}\bigl(\mathbf{w}^\top \boldsymbol{\phi}(\mathbf{x}_n) - t_n\bigr)^2 + \tfrac{\lambda}{2}\,\mathbf{w}^\top \mathbf{w}.

Set wL=0\nabla_{\mathbf{w}} L = 0. You get w=1λn(wϕ(xn)tn)ϕ(xn)\mathbf{w} = -\tfrac{1}{\lambda}\sum_n (\mathbf{w}^\top \boldsymbol{\phi}(\mathbf{x}_n) - t_n)\,\boldsymbol{\phi}(\mathbf{x}_n). Rename the prefactors an=1λ(wϕ(xn)tn)a_n = -\tfrac{1}{\lambda}(\mathbf{w}^\top \boldsymbol{\phi}(\mathbf{x}_n) - t_n) and the equation becomes

Dual identity
w  =  n=1Nanϕ(xn)  =  Φa.\mathbf{w} \;=\; \sum_{n=1}^{N} a_n\, \boldsymbol{\phi}(\mathbf{x}_n) \;=\; \boldsymbol{\Phi}^\top \mathbf{a}.

The optimal weight vector is a linear combination of the training features. This is the representer theorem in its simplest form: even in a high-dimensional feature space, the answer lives in the (at most) NN-dimensional subspace spanned by the data.

Substitute w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a} back into LL. After a few lines of algebra (done in §4) the objective in terms of a\mathbf{a} becomes

L(a)  =  12aKKa    aKt  +  12tt  +  λ2aKa,L(\mathbf{a}) \;=\; \tfrac{1}{2}\,\mathbf{a}^\top \mathbf{K}\mathbf{K}\mathbf{a} \;-\; \mathbf{a}^\top \mathbf{K}\mathbf{t} \;+\; \tfrac{1}{2}\,\mathbf{t}^\top \mathbf{t} \;+\; \tfrac{\lambda}{2}\,\mathbf{a}^\top \mathbf{K}\mathbf{a},

where K=ΦΦ\mathbf{K} = \boldsymbol{\Phi}\boldsymbol{\Phi}^\top is the N×NN \times N Gram matrix with entries Knm=k(xn,xm)K_{nm} = k(\mathbf{x}_n, \mathbf{x}_m). Notice — no ϕ\boldsymbol{\phi} appears anywhere except inside the kernel.

Setting aL=0\nabla_{\mathbf{a}} L = 0 gives the dual solution:

Dual ridge
a^  =  (K+λIN)1t.\hat{\mathbf{a}} \;=\; (\mathbf{K} + \lambda \mathbf{I}_N)^{-1}\,\mathbf{t}.

Compare with the primal ridge from Ch. 02, w^=(λIM+ΦΦ)1Φt\hat{\mathbf{w}} = (\lambda \mathbf{I}_M + \boldsymbol{\Phi}^\top \boldsymbol{\Phi})^{-1}\boldsymbol{\Phi}^\top \mathbf{t}. The primal inverts an M×MM \times M matrix; the dual inverts an N×NN \times N one. The choice is dictated by which is smaller — and when M=M = \infty the dual is the only option.

Predicting with kernels

The prediction on a new input x\mathbf{x} is y(x)=wϕ(x)=aΦϕ(x)y(\mathbf{x}) = \mathbf{w}^\top \boldsymbol{\phi}(\mathbf{x}) = \mathbf{a}^\top \boldsymbol{\Phi}\,\boldsymbol{\phi}(\mathbf{x}). The vector Φϕ(x)\boldsymbol{\Phi}\,\boldsymbol{\phi}(\mathbf{x}) has nn-th entry ϕ(xn)ϕ(x)=k(xn,x)\boldsymbol{\phi}(\mathbf{x}_n)^\top \boldsymbol{\phi}(\mathbf{x}) = k(\mathbf{x}_n, \mathbf{x}), so:

Kernel prediction
y(x)  =  k(x)(K+λIN)1t,k(x)=(k(x1,x),,k(xN,x)).y(\mathbf{x}) \;=\; \mathbf{k}(\mathbf{x})^\top (\mathbf{K} + \lambda \mathbf{I}_N)^{-1}\,\mathbf{t}, \qquad \mathbf{k}(\mathbf{x}) = \bigl(k(\mathbf{x}_1, \mathbf{x}), \dots, k(\mathbf{x}_N, \mathbf{x})\bigr)^\top.

The prediction is a weighted average of the training targets, with weights determined by how similar x\mathbf{x} is (via kk) to each training input. No feature vectors anywhere — the algorithm is now phrased purely in terms of pairwise similarities.

When is a function a valid kernel?

We can’t just write down any old function and call it a kernel. The kernel has to actually correspond to an inner product in some Hilbert space. The condition is clean.

key

Mercer's theorem (validity)

A symmetric function k:X×XRk : \mathcal{X} \times \mathcal{X} \to \mathbb{R} is a valid kernel if and only if for every finite set {x1,,xN}X\{\mathbf{x}_1, \dots, \mathbf{x}_N\} \subset \mathcal{X} the Gram matrix Knm=k(xn,xm)K_{nm} = k(\mathbf{x}_n, \mathbf{x}_m) is positive semi-definite:

cKc  =  n,mcncmk(xn,xm)    0for all cRN.\mathbf{c}^\top \mathbf{K}\mathbf{c} \;=\; \sum_{n,m} c_n c_m\, k(\mathbf{x}_n, \mathbf{x}_m) \;\ge\; 0 \qquad \text{for all } \mathbf{c} \in \mathbb{R}^N.

Note: positive semi-definite ≠ “all entries non-negative”. Indefinite-looking kernels with negative entries are fine; what matters is the quadratic form.

Building new kernels from old

Showing PSD directly is awkward. In practice you almost never do it — you compose new kernels from known-valid building blocks. Given valid k1,k2k_1, k_2, all of the following are also valid kernels:

RuleWhy it works (sketch)
k=ck1k = c \cdot k_1 with c0c \ge 0rescales the inner product by c\sqrt{c}.
k=f(x)k1f(x)k = f(\mathbf{x})\, k_1\, f(\mathbf{x}')equivalent to the feature map f(x)ϕ1(x)f(\mathbf{x})\,\boldsymbol{\phi}_1(\mathbf{x}).
k=q(k1)k = q(k_1), polynomial qq with 0\ge 0 coeffssums and products of kernels are kernels.
k=exp(k1)k = \exp(k_1)limit of the previous rule via the Taylor series.
k=k1+k2k = k_1 + k_2concatenate the two feature maps.
k=k1k2k = k_1 \cdot k_2tensor product of feature spaces.
k=xAxk = \mathbf{x}^\top \mathbf{A}\, \mathbf{x}', A0\mathbf{A} \succeq 0factor A=BB\mathbf{A} = \mathbf{B}^\top \mathbf{B}; the feature map is Bx\mathbf{B}\mathbf{x}.
k=ka(xa,xa)+kb(xb,xb)k = k_a(\mathbf{x}_a, \mathbf{x}'_a) + k_b(\mathbf{x}_b, \mathbf{x}'_b) on disjoint coordinate blockssum rule on partitioned inputs.

The kernel zoo

Linear

klin(x,x)=xxk_{\text{lin}}(\mathbf{x}, \mathbf{x}') = \mathbf{x}^\top \mathbf{x}'. The identity case — equivalent to ordinary linear regression. Often surprisingly strong, and a good baseline before reaching for anything fancier.

Polynomial

kpoly(x,x)=(xx+c)pk_{\text{poly}}(\mathbf{x}, \mathbf{x}') = (\mathbf{x}^\top \mathbf{x}' + c)^p. The implicit feature map is all monomials of degree p\le p — a feature space whose dimension grows combinatorially. c>0c > 0 controls how much weight is placed on low-order terms.

Gaussian / RBF

krbf(x,x)=exp ⁣(xx22σ2)k_{\text{rbf}}(\mathbf{x}, \mathbf{x}') = \exp\!\bigl(-\tfrac{\|\mathbf{x} - \mathbf{x}'\|^2}{2\sigma^2}\bigr). The default workhorse; the implicit feature space is infinite-dimensional. Bandwidth σ\sigma controls locality — small σ\sigma, only very close points count; large σ\sigma, everything looks similar.

Why is the Gaussian kernel valid? Expand the squared distance: xx2=xx2xx+xx\|\mathbf{x} - \mathbf{x}'\|^2 = \mathbf{x}^\top \mathbf{x} - 2\mathbf{x}^\top \mathbf{x}' + \mathbf{x}'^\top \mathbf{x}'. Then

krbf(x,x)  =  exp ⁣(xx2σ2)f(x)exp ⁣(xxσ2)exp(klin)exp ⁣(xx2σ2)f(x).k_{\text{rbf}}(\mathbf{x}, \mathbf{x}') \;=\; \underbrace{\exp\!\bigl(-\tfrac{\mathbf{x}^\top \mathbf{x}}{2\sigma^2}\bigr)}_{f(\mathbf{x})}\,\underbrace{\exp\!\bigl(\tfrac{\mathbf{x}^\top \mathbf{x}'}{\sigma^2}\bigr)}_{\exp(k_{\text{lin}})}\,\underbrace{\exp\!\bigl(-\tfrac{\mathbf{x}'^\top \mathbf{x}'}{2\sigma^2}\bigr)}_{f(\mathbf{x}')}.

The middle factor is the exponential of a valid kernel (valid by rule 4). The outer factors apply rule 2. Validity follows from composition.

The Gaussian kernel extends to non-Euclidean distances by the substitution xx2κ(x,x)+κ(x,x)2κ(x,x)\|\mathbf{x} - \mathbf{x}'\|^2 \mapsto \kappa(\mathbf{x},\mathbf{x}) + \kappa(\mathbf{x}',\mathbf{x}') - 2\,\kappa(\mathbf{x},\mathbf{x}') for any valid kernel κ\kappa — which opens the door to Gaussian kernels on strings, graphs, and other exotic objects.

Kernels on non-vector objects

Once you accept that a kernel is “any symmetric PSD similarity score”, you can build kernels on data types that aren’t Rd\mathbb{R}^d at all. Two clean examples:

  • Sets: k(A1,A2)=2A1A2k(A_1, A_2) = 2^{|A_1 \cap A_2|}. The implicit feature map is the indicator vector over all subsets of the universe.
  • From a generative model: if p(x)p(\mathbf{x}) is a probability density, then k(x,x)=p(x)p(x)k(\mathbf{x}, \mathbf{x}') = p(\mathbf{x})\, p(\mathbf{x}') is a valid kernel (one-dimensional feature map ϕ(x)=p(x)\boldsymbol{\phi}(\mathbf{x}) = p(\mathbf{x})). Two inputs are “similar” if both are individually likely under the model.

RBF networks and Nadaraya–Watson regression

The kernel prediction formula y(x)=nank(xn,x)y(\mathbf{x}) = \sum_n a_n\, k(\mathbf{x}_n, \mathbf{x}) has a beautiful network interpretation. Each training point xn\mathbf{x}_n becomes a hidden unit centred at xn\mathbf{x}_n. The activation of that unit for input x\mathbf{x} is k(xn,x)k(\mathbf{x}_n, \mathbf{x}) — a radial bump. The output layer takes the weighted sum with learned weights ana_n. This is the RBF network.

Historically, RBF networks were first proposed for exact interpolation: choose NN weights so that y(xn)=tny(\mathbf{x}_n) = t_n for every training point. The system Kw=t\mathbf{K}\,\mathbf{w} = \mathbf{t} has a unique solution when K\mathbf{K} is invertible. Sounds great — until you remember real data is noisy. Exact interpolation through noisy targets is a textbook case of overfitting. The cure is exactly the λI\lambda \mathbf{I} we added to get the dual ridge formula. Regularised kernel ridge = noise-tolerant RBF network.

why

Why normalise the basis functions?

For an input x\mathbf{x} far from every training point, every Gaussian bump k(xn,x)k(\mathbf{x}_n, \mathbf{x}) is near zero, so the prediction collapses to (essentially) zero regardless of the targets. To fix this dead-zone problem we normalise:

y(x)  =  nk(xn,x)tnmk(xm,x).y(\mathbf{x}) \;=\; \frac{\sum_n k(\mathbf{x}_n, \mathbf{x})\, t_n}{\sum_m k(\mathbf{x}_m, \mathbf{x})}.

The denominator forces the basis-function weights to sum to one, so the prediction is always a convex combination of training targets — bounded between the smallest and largest tnt_n. This is the Nadaraya–Watson estimator.

Nadaraya–Watson can be derived from a different angle that’s worth seeing — it changes how you think about the model. Treat the training set as samples from an unknown joint density p(x,t)p(\mathbf{x}, t). Estimate pp with a Parzen window:

p^(x,t)  =  1Nn=1Nf(xxn,ttn),\hat p(\mathbf{x}, t) \;=\; \tfrac{1}{N}\sum_{n=1}^{N} f(\mathbf{x} - \mathbf{x}_n,\, t - t_n),

where ff is a small kernel (a “window”) centred at the origin. The whole density is approximated as a sum of mini-densities, one per training point.

The regression function is the conditional expectation y(x)=E[tx]=tp(tx)dty(\mathbf{x}) = \mathbb{E}[t \mid \mathbf{x}] = \int t\, p(t \mid \mathbf{x})\, dt. Substitute the Parzen estimate, integrate tt out (which gives the marginal kernel g(x)=f(x,t)dtg(\mathbf{x}) = \int f(\mathbf{x}, t)\, dt), and the equation collapses to exactly the normalised RBF formula above. Nadaraya–Watson is the regression function implied by a Parzen-window density estimate.

Two faces, one formula
y(x)  =  n=1Ng(xxn)mg(xxm)normalised kernel weighttn.y(\mathbf{x}) \;=\; \sum_{n=1}^{N} \underbrace{\frac{g(\mathbf{x} - \mathbf{x}_n)}{\sum_m g(\mathbf{x} - \mathbf{x}_m)}}_{\text{normalised kernel weight}}\, t_n.

Read as “RBF network with normalised outputs”, or read as “local weighted average of training targets”. Same equation, two perspectives. The kernel chooses how to localise.

Bonus: because Nadaraya–Watson comes from a density estimate, it naturally supplies a full conditional distribution p(tx)p(t \mid \mathbf{x}) — not just a point prediction. Variance, quantiles, and confidence intervals all fall out without extra work.

From Bayesian linear regression to Gaussian processes

Gaussian processes sit at the probabilistic end of the kernel family. The cleanest way to introduce them is to derive them from a model you already know — Bayesian linear regression.

Start with the familiar linear-in-features model y(x,w)=wϕ(x)y(\mathbf{x}, \mathbf{w}) = \mathbf{w}^\top \boldsymbol{\phi}(\mathbf{x}). Place a zero-mean Gaussian prior on the weights: p(w)=N(w0,τI)p(\mathbf{w}) = \mathcal{N}(\mathbf{w}\mid \mathbf{0},\, \tau \mathbf{I}). Stack the predictions on the training inputs into a vector y=Φw\mathbf{y} = \boldsymbol{\Phi}\mathbf{w}. Since y\mathbf{y} is a linear transformation of a Gaussian random vector, it is itself Gaussian:

E[y]=ΦE[w]=0,cov[y]=Φcov[w]Φ=τΦΦ=τK.\mathbb{E}[\mathbf{y}] = \boldsymbol{\Phi}\,\mathbb{E}[\mathbf{w}] = \mathbf{0}, \qquad \mathrm{cov}[\mathbf{y}] = \boldsymbol{\Phi}\,\mathrm{cov}[\mathbf{w}]\,\boldsymbol{\Phi}^\top = \tau\,\boldsymbol{\Phi}\boldsymbol{\Phi}^\top = \tau\,\mathbf{K}.

So p(y)=N(y0,τK)p(\mathbf{y}) = \mathcal{N}(\mathbf{y} \mid \mathbf{0},\, \tau \mathbf{K}) — the joint distribution of training outputs is fully determined by the kernel. The weight-space view has quietly become a function-space view: we no longer need w\mathbf{w} at all, just the covariance K\mathbf{K}.

Now generalise: instead of choosing ϕ\boldsymbol{\phi} and deriving K\mathbf{K}, pick the kernel kk directly. The result is a Gaussian process.

def

Gaussian process — definition

A Gaussian process is a distribution over functions y(x)y(\mathbf{x}) such that for any finite collection of inputs x1,,xN\mathbf{x}_1, \dots, \mathbf{x}_N, the vector (y(x1),,y(xN))(y(\mathbf{x}_1), \dots, y(\mathbf{x}_N))^\top is jointly Gaussian. A GP is fully specified by:

  • a mean function m(x)m(\mathbf{x}) — usually taken to be 0;
  • a covariance function (kernel) k(x,x)=E[y(x)y(x)]k(\mathbf{x}, \mathbf{x}') = \mathbb{E}\bigl[y(\mathbf{x})\,y(\mathbf{x}')\bigr].

A subtle but important conceptual move just happened: the kernel is now interpreted as a covariance. Two inputs that the kernel rates as “similar” are inputs at which the model expects the function to produce correlated outputs. Smooth kernels → smooth functions; rapidly decaying kernels → wiggly functions.

Now add observation noise: tn=y(xn)+εnt_n = y(\mathbf{x}_n) + \varepsilon_n with εnN(0,σn2)\varepsilon_n \sim \mathcal{N}(0, \sigma_n^2) i.i.d. The joint distribution of the noisy targets is

p(t)  =  N(t0,CN),(CN)nm=k(xn,xm)+σn2δnm.p(\mathbf{t}) \;=\; \mathcal{N}(\mathbf{t} \mid \mathbf{0},\, \mathbf{C}_N), \qquad (\mathbf{C}_N)_{nm} = k(\mathbf{x}_n, \mathbf{x}_m) + \sigma_n^2\,\delta_{nm}.

Noise simply adds σn2\sigma_n^2 to the diagonal — exactly like the λI\lambda \mathbf{I} regulariser in the dual ridge formula. This is the equivalence: the GP noise parameter σn2\sigma_n^2 plays the role of the ridge regulariser λ\lambda.

The GP predictive distribution

For a new input xN+1\mathbf{x}_{N+1}, define kRN\mathbf{k} \in \mathbb{R}^N with kn=k(xn,xN+1)k_n = k(\mathbf{x}_n, \mathbf{x}_{N+1}) and c=k(xN+1,xN+1)+σn2c = k(\mathbf{x}_{N+1}, \mathbf{x}_{N+1}) + \sigma_n^2. Then the joint distribution of all N+1N+1 noisy targets is Gaussian with block-structured covariance:

CN+1  =  (CNkkc).\mathbf{C}_{N+1} \;=\; \begin{pmatrix} \mathbf{C}_N & \mathbf{k} \\ \mathbf{k}^\top & c \end{pmatrix}.

Apply the standard partitioned-Gaussian conditioning formula. The conditional distribution of tN+1t_{N+1} given t\mathbf{t} is Gaussian:

GP predictive distribution
p(tN+1t)  =  N(tN+1m(xN+1),σ2(xN+1)),p(t_{N+1} \mid \mathbf{t}) \;=\; \mathcal{N}\bigl(t_{N+1}\,\big|\, m(\mathbf{x}_{N+1}),\, \sigma^2(\mathbf{x}_{N+1})\bigr),m(xN+1)=kCN1t,σ2(xN+1)=ckCN1k.m(\mathbf{x}_{N+1}) = \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{t}, \qquad \sigma^2(\mathbf{x}_{N+1}) = c - \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{k}.
m(x)
posterior mean — identical to kernel ridge with λ=σn2\lambda = \sigma_n^2.
σ²(x)
posterior variance — how uncertain the model is at x\mathbf{x}. Decreases near training points; increases far from them.
C⁻¹t
computed once at cost O(N3)O(N^3); the same vector is reused for every prediction.
c − kᵀC⁻¹k
the prior variance cc minus the variance “explained” by the data. Always non-negative because CN\mathbf{C}_N is PSD.

Why this is worth the algebra: the GP gives you a full predictive distribution, not just a point estimate. Knowing where the model is uncertain is essential for active learning, Bayesian optimisation, and safety-critical applications.

04 · Worked example

Kernel ridge regression on three points, by hand

We’ll fit a kernel ridge regressor to a tiny 1-D dataset using a Gaussian kernel. Every matrix is small enough to track by hand, and you’ll see the dual formula a^=(K+λI)1t\hat{\mathbf{a}} = (\mathbf{K} + \lambda \mathbf{I})^{-1}\mathbf{t} in concrete numbers.

Worked example Kernel ridge on three points

1 · The data and the kernel

Three training points: (x1,t1)=(0,1)(x_1, t_1) = (0, 1), (x2,t2)=(1,2)(x_2, t_2) = (1, 2), (x3,t3)=(2,4)(x_3, t_3) = (2, 4). Pick the Gaussian kernel with σ=1\sigma = 1: k(x,x)=exp ⁣((xx)22)k(x, x') = \exp\!\bigl(-\tfrac{(x - x')^2}{2}\bigr). Then k(0,0)=k(1,1)=k(2,2)=1k(0, 0) = k(1, 1) = k(2, 2) = 1, and pairwise

k(0,1)=e0.50.6065,k(1,2)=e0.50.6065,k(0,2)=e20.1353.k(0,1) = e^{-0.5} \approx 0.6065, \qquad k(1,2) = e^{-0.5} \approx 0.6065, \qquad k(0,2) = e^{-2} \approx 0.1353.

2 · Build the Gram matrix

K  =  (1e1/2e2e1/21e1/2e2e1/21)    (10.60650.13530.606510.60650.13530.60651).\mathbf{K} \;=\; \begin{pmatrix} 1 & e^{-1/2} & e^{-2} \\ e^{-1/2} & 1 & e^{-1/2} \\ e^{-2} & e^{-1/2} & 1 \end{pmatrix} \;\approx\; \begin{pmatrix} 1 & 0.6065 & 0.1353 \\ 0.6065 & 1 & 0.6065 \\ 0.1353 & 0.6065 & 1 \end{pmatrix}.

The Gram matrix is symmetric, has 1’s on the diagonal (because ϕ(x)=1\|\boldsymbol{\phi}(\mathbf{x})\| = 1 for the Gaussian kernel), and decays away from the diagonal. The (1,3)(1,3) entry is smallest because points 0 and 2 are farthest apart.

3 · Solve the dual system

Pick λ=0.1\lambda = 0.1 (light regularisation). Bump each diagonal entry by 0.10.1 to form K+0.1I\mathbf{K} + 0.1\,\mathbf{I}, then solve the 3×33 \times 3 system (K+λI)a^=t(\mathbf{K} + \lambda \mathbf{I})\,\hat{\mathbf{a}} = \mathbf{t} with t=(1,2,4)\mathbf{t} = (1, 2, 4)^\top:

a^    (0.094,  1.060,  3.197).\hat{\mathbf{a}} \;\approx\; (0.094,\; 1.060,\; 3.197)^\top.

Sanity check. Row 1 of (K+0.1I)a^(\mathbf{K} + 0.1\,\mathbf{I})\,\hat{\mathbf{a}} gives 1.1(0.094)+0.6065(1.060)+0.1353(3.197)1.181.1(0.094) + 0.6065(1.060) + 0.1353(3.197) \approx 1.18 — close to t1=1t_1 = 1; carrying more decimals (a^1=0.0939,a^2=1.0599,a^3=3.1972\hat a_1 = 0.0939,\, \hat a_2 = 1.0599,\, \hat a_3 = 3.1972) reproduces (1,2,4)(1, 2, 4)^\top to three decimals. The dual formula is exact; only finite-precision printing introduces error.

4 · Predict at a new point

Predict at x=1.5x^\star = 1.5. The similarity vector is

k(1.5)=(k(0,1.5),k(1,1.5),k(2,1.5))=(e1.125,e0.125,e0.125)(0.325,0.882,0.882).\mathbf{k}(1.5) = \bigl(k(0, 1.5),\, k(1, 1.5),\, k(2, 1.5)\bigr)^\top = (e^{-1.125},\, e^{-0.125},\, e^{-0.125})^\top \approx (0.325,\, 0.882,\, 0.882)^\top.

The prediction is the dot product y(1.5)=k(1.5)a^y(1.5) = \mathbf{k}(1.5)^\top \hat{\mathbf{a}}:

y(1.5)    0.325(0.094)+0.882(1.060)+0.882(3.197)    0.031+0.935+2.820    3.79.y(1.5) \;\approx\; 0.325(0.094) + 0.882(1.060) + 0.882(3.197) \;\approx\; 0.031 + 0.935 + 2.820 \;\approx\; 3.79.

The prediction sits between t2=2t_2 = 2 and t3=4t_3 = 4, as you’d expect for an input between x2=1x_2 = 1 and x3=2x_3 = 2, and is pulled toward the larger value because point 3 is closer to 1.5.

Derivation Where did the dual formula come from? Four lines.
  1. Start from the regularised loss L(w)=12tΦw2+λ2w2L(\mathbf{w}) = \tfrac{1}{2}\|\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}\|^2 + \tfrac{\lambda}{2}\|\mathbf{w}\|^2.
  2. Setting wL=0\nabla_{\mathbf{w}} L = 0 yields w=1λΦ(tΦw)\mathbf{w} = \tfrac{1}{\lambda}\boldsymbol{\Phi}^\top(\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}). Define a=1λ(tΦw)RN\mathbf{a} = \tfrac{1}{\lambda}(\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}) \in \mathbb{R}^N. Then w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a} — the representer identity.
  3. Substitute back: a=1λ(tΦΦa)\mathbf{a} = \tfrac{1}{\lambda}(\mathbf{t} - \boldsymbol{\Phi}\boldsymbol{\Phi}^\top \mathbf{a}). Multiply both sides by λ\lambda and use ΦΦ=K\boldsymbol{\Phi}\boldsymbol{\Phi}^\top = \mathbf{K}: (K+λI)a=t(\mathbf{K} + \lambda \mathbf{I})\,\mathbf{a} = \mathbf{t}.
  4. Solve a^=(K+λI)1t\hat{\mathbf{a}} = (\mathbf{K} + \lambda \mathbf{I})^{-1}\mathbf{t} and predict y(x)=ak(x)y(\mathbf{x}) = \mathbf{a}^\top \mathbf{k}(\mathbf{x}). Everywhere ϕ\boldsymbol{\phi} might appear, only kernel evaluations remain.
map

Map the example back onto the formalism

  • N=3N = 3 training samples; kernel: Gaussian with σ=1\sigma = 1.
  • Gram matrix KR3×3\mathbf{K} \in \mathbb{R}^{3 \times 3}, entries e(xnxm)2/2e^{-(x_n - x_m)^2 / 2}.
  • Dual coefficients a^(0.09,1.06,3.20)\hat{\mathbf{a}} \approx (0.09, 1.06, 3.20)^\top.
  • Prediction at x=1.5x^\star = 1.5: y3.79y \approx 3.79.
  • No ϕ\boldsymbol{\phi} was ever computed — yet the implicit feature space is infinite-dimensional.

05 · Visual explanation

Pictures that lock the ideas in

The Gram matrix as a heatmap

For points scattered on a line, the Gram matrix is a heatmap whose (n,m)(n, m) cell tells you how similar points nn and mm are in the eyes of the kernel. Bright cells near the diagonal mean “neighbouring points see each other”; the matrix darkens as you move off-diagonal. The Gram matrix is also where validity is decided — a kernel is valid iff every such heatmap, for every possible point set, is a PSD matrix. The hands-on heatmap below lets you recompute it live.

A non-linear decision boundary, built from circular bumps

The left plot is a binary classification dataset that no straight line can solve — the classes are concentric. The right plot shows the boundary a Gaussian-kernel classifier learns. It bends, it curves, it does things linear methods can never do.

Linear boundary — fails
RBF-kernel boundary — succeeds

inner class (+1) outer class (−1)

The right-hand boundary is built from a sum of Gaussian bumps, one per training point. Each training point’s bump pulls the boundary toward its own class; where the bumps balance, the boundary forms. This is the geometric face of the dual formula y(x)=nank(xn,x)y(\mathbf{x}) = \sum_n a_n k(\mathbf{x}_n, \mathbf{x}) — every training point contributes a tiny vote, weighted by how close x\mathbf{x} is to it.

A Gaussian process and its uncertainty

Gaussian processes don’t just predict — they also tell you how confident they are. Where the data are dense, the predictive band is narrow (the model is confident); where there are no data, the band fans out (the model knows it doesn’t know). This calibrated uncertainty is what makes GPs irresistible for safety-critical applications. You can watch the band breathe in the RBF / GP explorer below.

view

All three pictures, one object

The Gram matrix from the heatmap is the same object whose inversion produces the boundary in the ring plot and the uncertainty ribbon of the GP. The kernel just changes hats — algebraic inverse for the dual ridge, geometric weight for the boundary, covariance function for the GP. Same maths, three personalities.

06 · Hands-on

Try it yourself

Three interactive labs, each isolating one concept. Slide, click, and watch the maths move — these are the moments where kernels stop being a list of formulas and start being something you can feel.

Hands-on 1

Watch 1-D data become linearly separable

Ten points on a line: orange (inner) near the origin, gold (outer) far out. In 1-D no single threshold separates them — the inner points are sandwiched between the outer ones. Apply the lift φ(x) = (x, x²) and the classes split by height. Drag lift amount to morph continuously from the raw line to the lifted parabola.

0.00
not separable
xinner (−1)outer (+1)
Try thisStart at 0.00 — every point sits on the x-axis and the two classes interleave; no threshold works. Push toward 1.00: the outer points climb the parabola (large ) while the inner cluster stays near the floor. Past about 0.45 the dashed line cleanly splits them and the badge flips to separable.
TakeawayThe data never changed — only the space did. A linear separator in the lifted space (x, x²) is a non-linear one back in x. The kernel trick reproduces this exact separation while only ever evaluating k(x, x′) = φ(x)ᵀφ(x′) — it never builds the lift.
Hands-on 2

The Gram matrix, live

Eight points on a line. Each cell is K[i][j] = k(x_i, x_j) — the kernel’s similarity score for that pair. Switch the kernel family and push its hyperparameters: the whole matrix recomputes. Brighter = more similar (after rescaling each matrix to its own min–max so the structure is visible).

0.70
1.000.770.440.180.040.010.000.000.771.000.850.520.180.050.010.000.440.851.000.850.440.180.050.010.180.520.851.000.770.440.180.040.040.180.440.771.000.850.520.180.010.050.180.440.851.000.850.440.000.010.050.180.520.851.000.770.000.000.010.040.180.440.771.00x₁x₈x₁x₈
Kernel
Gaussian / RBF
max entry
1.00
min entry
0.00
PSD?
yes ✓
Try thisOn Gaussian, shrink σ to 0.1 — only the diagonal stays bright; every point sees only itself (the matrix approaches the identity, which memorises and overfits). Grow σ to 2 — everything lights up (every point looks similar, the kernel becomes near-constant). Switch to Linear and note the negative entries when one point is positive and the other negative — yet the matrix is still valid.
TakeawayThe Gram matrix is the data, as the model sees it. Validity (Mercer) is the statement that this matrix is positive semi-definite for every possible point set — and notice that PSD ≠ all entries non-negative: the linear and polynomial kernels happily produce negative cells while remaining perfectly valid.
Hands-on 3

RBF bandwidth — the locality dial

The bold curve is the kernel-ridge fit y(x) = Σ a_n exp(−(x−x_n)²/(2σ²)); the faint curves are the individual weighted bumps, one per training point. Bandwidth σ sets how far each point’s influence reaches. Toggle the GP band to read the same kernel as a covariance with calibrated uncertainty.

0.50
10-2
well-tuned · smooth + faithful
xy
bandwidth σ
0.50
λ
0.01
Train MSE
0.000
basis bumps
8
Try thisAt small σ with tiny λ, each bump is sharp and the curve nearly interpolates every point, dipping to zero in the gaps — overfitting. Widen σ: bumps overlap and the fit smooths, until at large σ they merge into a near-flat line. Turn on the GP band and look at the right-hand gap: the band fans wide exactly where there are no data.
TakeawayOne Gaussian kernel, two readings. As an RBF network it is a sum of bumps with learned weights a_n; as a Gaussian process it is a covariance that also returns a predictive variance — large where data are absent, small where they are dense. The mean of the GP is exactly the kernel-ridge fit with λ = σ_n².

07 · Exam intel

What the exam actually tests

Kernel methods are an exam favourite: derivations are short, symbol-heavy, and very specific. Six question shapes appear essentially every year.

Q1

Derive the dual representation of ridge regression

Start from the primal L(w)=12tΦw2+λ2w2L(\mathbf{w}) = \tfrac{1}{2}\|\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}\|^2 + \tfrac{\lambda}{2}\|\mathbf{w}\|^2. Set L=0\nabla L = 0w=1λΦ(tΦw)\mathbf{w} = \tfrac{1}{\lambda}\boldsymbol{\Phi}^\top(\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}). Define a=1λ(tΦw)\mathbf{a} = \tfrac{1}{\lambda}(\mathbf{t} - \boldsymbol{\Phi}\mathbf{w}) so that w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a}. Substitute back; multiply by λ\lambda:

(K+λIN)a  =  t,K=ΦΦ.(\mathbf{K} + \lambda \mathbf{I}_N)\,\mathbf{a} \;=\; \mathbf{t}, \qquad \mathbf{K} = \boldsymbol{\Phi}\boldsymbol{\Phi}^\top.

Hence a^=(K+λIN)1t\hat{\mathbf{a}} = (\mathbf{K} + \lambda \mathbf{I}_N)^{-1}\mathbf{t} and predictions are y(x)=k(x)a^y(\mathbf{x}) = \mathbf{k}(\mathbf{x})^\top \hat{\mathbf{a}} with kn(x)=k(xn,x)k_n(\mathbf{x}) = k(\mathbf{x}_n, \mathbf{x}). Highlight: only kernel evaluations appear in the final formula.

Q2

Prove a given function is a valid kernel

Two standard strategies:

  1. By construction. Write down an explicit feature map ϕ\boldsymbol{\phi} such that k(x,x)=ϕ(x)ϕ(x)k(\mathbf{x}, \mathbf{x}') = \boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}'). Example: k(x,x)=(xx+1)2=1+2xx+(xx)2=ϕ(x)ϕ(x)k(x, x') = (xx' + 1)^2 = 1 + 2xx' + (xx')^2 = \boldsymbol{\phi}(x)^\top \boldsymbol{\phi}(x') with ϕ(x)=(1,2x,x2)\boldsymbol{\phi}(x) = (1, \sqrt{2}\,x, x^2).
  2. By composition. Decompose kk into sums, products, exponentials, and scaled versions of known-valid kernels. Reference the building-block table in §3.

Mention Mercer for credit: the abstract condition is “Gram matrix PSD for every finite input set”. In practice you almost never check this directly.

Q3

Compare primal vs dual: which to use?

The primal inverts ΦΦ+λIM\boldsymbol{\Phi}^\top \boldsymbol{\Phi} + \lambda \mathbf{I}_M — an M×MM \times M matrix. The dual inverts K+λIN\mathbf{K} + \lambda \mathbf{I}_N — an N×NN \times N one.

Use primal whenUse dual when
MNM \ll N (low-dimensional features, lots of data)MNM \gg N (high-dimensional features, few data)
Feature map ϕ\boldsymbol{\phi} is cheap to computeOnly the kernel is available (strings, graphs)
You want fast prediction — O(M)O(M) per queryM=M = \infty — primal is impossible
Q4

Computational cost of kernel methods

Memorise:

  • Build K\mathbf{K}: O(N2)O(N^2) kernel evaluations, each O(d)O(d) for vector inputs of dimension dd. Memory O(N2)O(N^2).
  • Solve (K+λI)1t(\mathbf{K} + \lambda \mathbf{I})^{-1}\mathbf{t}: O(N3)O(N^3) via Cholesky or LU. Done once.
  • Predict at a new point: O(N)O(N) kernel evaluations plus an O(N)O(N) dot product. Per query.

This is why kernel methods scale beautifully on small/medium datasets and choke on big ones. Workarounds: random features, Nyström approximation, inducing points (sparse GPs).

Q5

Derive the Gaussian-process predictive distribution

Place a zero-mean GP prior with kernel kk on the latent function y(x)y(\mathbf{x}), and add i.i.d. Gaussian noise: tn=y(xn)+εn,  εnN(0,σn2)t_n = y(\mathbf{x}_n) + \varepsilon_n,\; \varepsilon_n \sim \mathcal{N}(0, \sigma_n^2). Then targets are jointly Gaussian with covariance CN=K+σn2IN\mathbf{C}_N = \mathbf{K} + \sigma_n^2 \mathbf{I}_N. For a new input xN+1\mathbf{x}_{N+1}, the joint (t,tN+1)(\mathbf{t},\, t_{N+1}) is Gaussian with covariance

CN+1=(CNkkc),kn=k(xn,xN+1),c=k(xN+1,xN+1)+σn2.\mathbf{C}_{N+1} = \begin{pmatrix} \mathbf{C}_N & \mathbf{k} \\ \mathbf{k}^\top & c \end{pmatrix}, \quad k_n = k(\mathbf{x}_n, \mathbf{x}_{N+1}),\quad c = k(\mathbf{x}_{N+1}, \mathbf{x}_{N+1}) + \sigma_n^2.

Conditioning on t\mathbf{t} gives p(tN+1t)=N(m,σ2)p(t_{N+1} \mid \mathbf{t}) = \mathcal{N}(m, \sigma^2) with m(xN+1)=kCN1tm(\mathbf{x}_{N+1}) = \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{t} and σ2(xN+1)=ckCN1k\sigma^2(\mathbf{x}_{N+1}) = c - \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{k}. The mean is exactly the kernel-ridge prediction (with λ\lambda playing the role of σn2\sigma_n^2); the variance is the new and useful piece.

Q5b

Derive the Nadaraya–Watson estimator

Start from a Parzen-window joint density estimate p^(x,t)=1Nnf(xxn,ttn)\hat p(\mathbf{x}, t) = \tfrac{1}{N}\sum_n f(\mathbf{x} - \mathbf{x}_n,\, t - t_n). Compute the conditional expectation:

y(x)=E[tx]=tp^(x,t)dtp^(x,t)dt.y(\mathbf{x}) = \mathbb{E}[t \mid \mathbf{x}] = \frac{\int t\, \hat p(\mathbf{x}, t)\, dt}{\int \hat p(\mathbf{x}, t)\, dt}.

Assume ff factorises as f(x,t)=g(x)h(t)f(\mathbf{x}, t) = g(\mathbf{x})\,h(t) with h(t)dt=1\int h(t)\, dt = 1 and th(t)dt=0\int t\,h(t)\,dt = 0 (a zero-mean window). The integrals separate and give

y(x)=n=1Ng(xxn)mg(xxm)tn,y(\mathbf{x}) = \sum_{n=1}^{N} \frac{g(\mathbf{x} - \mathbf{x}_n)}{\sum_m g(\mathbf{x} - \mathbf{x}_m)}\, t_n,

normalised kernel weights summing to 1 — the Nadaraya–Watson estimator. The prediction is a locally weighted average of training targets, closer points counting more.

Q6

Choose kernel hyperparameters

The default for GPs is to maximise the log marginal likelihood lnp(tX,θ)\ln p(\mathbf{t} \mid \mathbf{X}, \boldsymbol{\theta}) with respect to the kernel parameters θ\boldsymbol{\theta}. Fast (one gradient step per evaluation) but the surface has multiple local optima — restart from a few random points. For non-probabilistic kernel methods (kernel ridge, SVMs) use cross-validation on a held-out fold. Robust but slow.

tip

Memorise four formulas and you have the chapter

  1. Dual identity: w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a}.
  2. Dual ridge: a^=(K+λI)1t\hat{\mathbf{a}} = (\mathbf{K} + \lambda \mathbf{I})^{-1}\mathbf{t}.
  3. Prediction: y(x)=k(x)a^y(\mathbf{x}) = \mathbf{k}(\mathbf{x})^\top \hat{\mathbf{a}}.
  4. GP predictive variance: σ2(x)=ckCN1k\sigma^2(\mathbf{x}) = c - \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{k}.

08 · Common mistakes

Where students get this wrong

×

'Positive semi-definite means all entries non-negative'

Definitely not. A kernel like k(x,x)=cos(xx)k(x, x') = \cos(x - x') is valid (its feature map lives in trig functions) yet its Gram matrix routinely has negative entries. PSD is a statement about quadratic forms: cKc0\mathbf{c}^\top \mathbf{K}\mathbf{c} \ge 0 for every c\mathbf{c}. Entries can be any sign.

×

'The kernel trick avoids high-dimensional features altogether'

Mathematically the features are still there — every kernel corresponds to some feature map, possibly infinite-dimensional. The trick is that we never have to compute them: every line of the algorithm touches features only through inner products, which the kernel hands back directly. The implicit features do all the non-linear work; you just don’t pay the cost of storing them.

×

'More kernel parameters always help'

A composite kernel like θ0krbf(x,x;θ1)+θ2+θ3xx\theta_0\, k_{\text{rbf}}(\mathbf{x}, \mathbf{x}'; \theta_1) + \theta_2 + \theta_3\, \mathbf{x}^\top \mathbf{x}' has four hyperparameters, each able to overfit. With small datasets, marginal-likelihood optimisation will happily walk into degenerate corners (e.g. σ0\sigma \to 0 so the kernel becomes the identity and every training target is memorised). Always cross-validate when you can; always check the predictive band looks sensible.

×

Forgetting to standardise features for the Gaussian kernel

The Gaussian kernel uses xx2\|\mathbf{x} - \mathbf{x}'\|^2 — a sum of squared coordinate differences. If one coordinate is in metres and another in kilograms, the bigger-valued coordinate dominates and the single bandwidth σ\sigma can’t fit both. Standardise to zero mean and unit variance before fitting.

×

Using the dual when the primal would be cheaper

The dual is unbeatable when M>NM > N or M=M = \infty, but it is a needless O(N3)O(N^3) tax when MNM \ll N. Always ask: how large are MM and NN? With 50 features and a million data points, never go dual. With 50,000 features and 200 data points, dual is the only sane choice. Same algorithm, very different cost.

×

'GPs give a single best prediction'

GPs return a distribution. The mean is what you’d usually call “the prediction” and it matches kernel ridge exactly. But ignoring the variance throws away the very feature that justifies the GP machinery. If you only need a point estimate, kernel ridge regression is faster and equally accurate.

×

'An exact-interpolation RBF network always works'

Without regularisation, one bump per training point forces the curve through every noisy target — high variance, terrible generalisation. The seemingly trivial difference between solving Kw=t\mathbf{K}\,\mathbf{w} = \mathbf{t} and (K+λI)a=t(\mathbf{K} + \lambda \mathbf{I})\,\mathbf{a} = \mathbf{t} is the difference between memorising noise and learning the signal. Always regularise kernel methods unless you have a very good reason not to.

×

'Kernel methods are always non-linear'

The linear kernel k(x,x)=xxk(\mathbf{x}, \mathbf{x}') = \mathbf{x}^\top \mathbf{x}' is a perfectly valid kernel. Kernel ridge with it is identical to ordinary ridge regression — the dual just does it via an N×NN \times N inverse instead of a d×dd \times d one. The point of kernels is flexibility; non-linearity is a special case, not a requirement.

09 · Self-check

Can you answer these?

Six quick checks in the style the chapter likes to be tested. Click an option for instant feedback.

The kernel trick lets you do non-linear learning by:

A symmetric function k(x, x′) is a valid kernel if and only if:

In kernel ridge regression with N training points and feature dimension M = ∞, the dual formula â = (K + λI)⁻¹t requires inverting a matrix of size:

A Gaussian process posterior gives a predictive distribution N(m(x), σ²(x)) at any new input. The predictive MEAN is:

The Nadaraya–Watson kernel regression estimator predicts y(x) as:

An exact-interpolation RBF network (one bump per training point, no regularisation) is fit to a noisy regression dataset. The most likely outcome is:

10 · Recap

One-screen summary

Chapter 06 — load-bearing ideas

  1. The kernel trick. If your algorithm only touches data through inner products ϕ(x)ϕ(x)\boldsymbol{\phi}(\mathbf{x})^\top \boldsymbol{\phi}(\mathbf{x}'), replace them with a single function k(x,x)k(\mathbf{x}, \mathbf{x}') and inherit the implicit feature space for free.
  2. Dual representation of ridge regression. The representer identity w=Φa\mathbf{w} = \boldsymbol{\Phi}^\top \mathbf{a} yields a^=(K+λIN)1t\hat{\mathbf{a}} = (\mathbf{K} + \lambda \mathbf{I}_N)^{-1}\mathbf{t}. Prediction is y(x)=k(x)a^y(\mathbf{x}) = \mathbf{k}(\mathbf{x})^\top \hat{\mathbf{a}}.
  3. Validity (Mercer). Symmetric kk is valid iff every finite Gram matrix is positive semi-definite. In practice we never check this directly — we build new kernels from known-valid blocks using sum, product, composition, exponential, and feature-rescaling rules.
  4. The kernel zoo. Linear (xx\mathbf{x}^\top \mathbf{x}') for a baseline; polynomial ((xx+c)p(\mathbf{x}^\top \mathbf{x}' + c)^p) for monomials of degree p\le p; Gaussian / RBF (exp(xx2/(2σ2))\exp(-\|\mathbf{x} - \mathbf{x}'\|^2/(2\sigma^2))) for an infinite-dimensional smooth-bump feature space.
  5. Kernels for non-vector data. Sets: 2A1A22^{|A_1 \cap A_2|}. Probabilistic: k(x,x)=p(x)p(x)k(\mathbf{x}, \mathbf{x}') = p(\mathbf{x})\,p(\mathbf{x}'). String, graph, and document kernels all exist.
  6. RBF networks & Nadaraya–Watson. An RBF network places one bump per training point and outputs y(x)=nank(xn,x)y(\mathbf{x}) = \sum_n a_n\, k(\mathbf{x}_n, \mathbf{x}). Exact interpolation overfits noisy data — regularisation (the λI\lambda \mathbf{I} term) is the fix. Normalising the bumps gives Nadaraya–Watson, derivable two ways: as a normalised RBF network, or as the conditional expectation under a Parzen-window joint density estimate. Predictions are weighted local averages of training targets.
  7. Gaussian processes. Derived from Bayesian linear regression: a Gaussian prior on w\mathbf{w} induces a Gaussian prior on y=Φw\mathbf{y} = \boldsymbol{\Phi}\mathbf{w} with covariance τK\tau \mathbf{K}. A GP is any distribution over functions whose finite marginals are Gaussian, fully specified by mean m(x)m(\mathbf{x}) and kernel k(x,x)k(\mathbf{x},\mathbf{x}'). Add noise σn2\sigma_n^2, condition on training targets via the partitioned-Gaussian formula: posterior mean m(x)=kCN1tm(\mathbf{x}) = \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{t} (= kernel ridge with λ=σn2\lambda = \sigma_n^2), posterior variance σ2(x)=ckCN1k\sigma^2(\mathbf{x}) = c - \mathbf{k}^\top \mathbf{C}_N^{-1}\mathbf{k}.
  8. Costs and trade-offs. Training O(N3)O(N^3), prediction O(N)O(N), memory O(N2)O(N^2). Brilliant for small/medium data, infeasible for very large data without approximations (random features, Nyström, sparse GPs).

Looking ahead → Chapter 07

We’ve used the kernel trick to upgrade ridge regression. Next we apply the very same trick to the maximum-margin classifier — and out comes the support vector machine, the most celebrated kernel method of all.