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}')$.
01 · Motivation
Why does this matter?
Chapter 02 ended on a remarkable observation: a linear model with cleverly chosen basis functions can fit almost any shape. Polynomials, Gaussians, sigmoids — pick the right and the same closed-form formula does the rest.
But there’s a catch — actually three.
Feature explosion
A quadratic mapping on a 100-feature input creates roughly new features. A degree-10 polynomial creates . 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 ). The matrix 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 . 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.
The whole chapter in one sentence
If your algorithm only ever uses the data through inner products , then you don’t need at all. Replace each inner product with a single function — 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 , prediction costs roughly and training costs roughly . 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 and , one blue point at . In 1D this is hopeless. But now apply the simple map . Suddenly every point lives in 2D, and a horizontal line at 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 , then form , 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 , we win. Take the polynomial example. In 2D, the quadratic feature map is . Now compute directly and expand it:
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 and you get all monomials of degree 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.
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 , 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)
. 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)
. 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 — 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 “.
- φ(x)
- a (possibly very high or infinite-dimensional) feature map .
- k(x, x′)
- the kernel — a similarity score.
- Φ
- the design matrix; row is .
- K
- the Gram matrix, , entries .
- a
- the dual coefficient vector; the weights become .
- λ
- the ridge regularisation strength (= the GP noise variance ).
The kernel function
The kernel associated with a feature map is
Two essential properties drop out for free: symmetry and positivity .
Two important families:
- Stationary kernels: — only the difference between inputs matters. Translation-invariant.
- Radial / homogeneous kernels: — only the distance matters. Rotation- and translation-invariant.
The simplest kernel of all is the linear kernel, corresponding to the identity feature map : . All kernels can be thought of as generalisations of this.
Dual representation of ridge regression
Recall the regularised least-squares objective from Ch. 02:
Set . You get . Rename the prefactors and the equation becomes
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) -dimensional subspace spanned by the data.
Substitute back into . After a few lines of algebra (done in §4) the objective in terms of becomes
where is the Gram matrix with entries . Notice — no appears anywhere except inside the kernel.
Setting gives the dual solution:
Compare with the primal ridge from Ch. 02, . The primal inverts an matrix; the dual inverts an one. The choice is dictated by which is smaller — and when the dual is the only option.
Predicting with kernels
The prediction on a new input is . The vector has -th entry , so:
The prediction is a weighted average of the training targets, with weights determined by how similar is (via ) 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.
Mercer's theorem (validity)
A symmetric function is a valid kernel if and only if for every finite set the Gram matrix is positive semi-definite:
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 , all of the following are also valid kernels:
| Rule | Why it works (sketch) |
|---|---|
| with | rescales the inner product by . |
| equivalent to the feature map . | |
| , polynomial with coeffs | sums and products of kernels are kernels. |
| limit of the previous rule via the Taylor series. | |
| concatenate the two feature maps. | |
| tensor product of feature spaces. | |
| , | factor ; the feature map is . |
| on disjoint coordinate blocks | sum rule on partitioned inputs. |
The kernel zoo
Linear
. The identity case — equivalent to ordinary linear regression. Often surprisingly strong, and a good baseline before reaching for anything fancier.
Polynomial
. The implicit feature map is all monomials of degree — a feature space whose dimension grows combinatorially. controls how much weight is placed on low-order terms.
Gaussian / RBF
. The default workhorse; the implicit feature space is infinite-dimensional. Bandwidth controls locality — small , only very close points count; large , everything looks similar.
Why is the Gaussian kernel valid? Expand the squared distance: . Then
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 for any valid kernel — 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 at all. Two clean examples:
- Sets: . The implicit feature map is the indicator vector over all subsets of the universe.
- From a generative model: if is a probability density, then is a valid kernel (one-dimensional feature map ). Two inputs are “similar” if both are individually likely under the model.
RBF networks and Nadaraya–Watson regression
The kernel prediction formula has a beautiful network interpretation. Each training point becomes a hidden unit centred at . The activation of that unit for input is — a radial bump. The output layer takes the weighted sum with learned weights . This is the RBF network.
Historically, RBF networks were first proposed for exact interpolation: choose weights so that for every training point. The system has a unique solution when 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 we added to get the dual ridge formula. Regularised kernel ridge = noise-tolerant RBF network.
Why normalise the basis functions?
For an input far from every training point, every Gaussian bump is near zero, so the prediction collapses to (essentially) zero regardless of the targets. To fix this dead-zone problem we normalise:
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 . 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 . Estimate with a Parzen window:
where 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 . Substitute the Parzen estimate, integrate out (which gives the marginal kernel ), and the equation collapses to exactly the normalised RBF formula above. Nadaraya–Watson is the regression function implied by a Parzen-window density estimate.
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 — 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 . Place a zero-mean Gaussian prior on the weights: . Stack the predictions on the training inputs into a vector . Since is a linear transformation of a Gaussian random vector, it is itself Gaussian:
So — 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 at all, just the covariance .
Now generalise: instead of choosing and deriving , pick the kernel directly. The result is a Gaussian process.
Gaussian process — definition
A Gaussian process is a distribution over functions such that for any finite collection of inputs , the vector is jointly Gaussian. A GP is fully specified by:
- a mean function — usually taken to be 0;
- a covariance function (kernel) .
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: with i.i.d. The joint distribution of the noisy targets is
Noise simply adds to the diagonal — exactly like the regulariser in the dual ridge formula. This is the equivalence: the GP noise parameter plays the role of the ridge regulariser .
The GP predictive distribution
For a new input , define with and . Then the joint distribution of all noisy targets is Gaussian with block-structured covariance:
Apply the standard partitioned-Gaussian conditioning formula. The conditional distribution of given is Gaussian:
- m(x)
- posterior mean — identical to kernel ridge with .
- σ²(x)
- posterior variance — how uncertain the model is at . Decreases near training points; increases far from them.
- C⁻¹t
- computed once at cost ; the same vector is reused for every prediction.
- c − kᵀC⁻¹k
- the prior variance minus the variance “explained” by the data. Always non-negative because 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 in concrete numbers.
1 · The data and the kernel
Three training points: , , . Pick the Gaussian kernel with : . Then , and pairwise
2 · Build the Gram matrix
The Gram matrix is symmetric, has 1’s on the diagonal (because for the Gaussian kernel), and decays away from the diagonal. The entry is smallest because points 0 and 2 are farthest apart.
3 · Solve the dual system
Pick (light regularisation). Bump each diagonal entry by to form , then solve the system with :
Sanity check. Row 1 of gives — close to ; carrying more decimals () reproduces to three decimals. The dual formula is exact; only finite-precision printing introduces error.
4 · Predict at a new point
Predict at . The similarity vector is
The prediction is the dot product :
The prediction sits between and , as you’d expect for an input between and , 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.
- Start from the regularised loss .
- Setting yields . Define . Then — the representer identity.
- Substitute back: . Multiply both sides by and use : .
- Solve and predict . Everywhere might appear, only kernel evaluations remain.
Map the example back onto the formalism
- training samples; kernel: Gaussian with .
- Gram matrix , entries .
- Dual coefficients .
- Prediction at : .
- No 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 cell tells you how similar points and 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.
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 — every training point contributes a tiny vote, weighted by how close 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.
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.
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.
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).
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.
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.
Derive the dual representation of ridge regression
Start from the primal . Set → . Define so that . Substitute back; multiply by :
Hence and predictions are with . Highlight: only kernel evaluations appear in the final formula.
Prove a given function is a valid kernel
Two standard strategies:
- By construction. Write down an explicit feature map such that . Example: with .
- By composition. Decompose 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.
Compare primal vs dual: which to use?
The primal inverts — an matrix. The dual inverts — an one.
| Use primal when | Use dual when |
|---|---|
| (low-dimensional features, lots of data) | (high-dimensional features, few data) |
| Feature map is cheap to compute | Only the kernel is available (strings, graphs) |
| You want fast prediction — per query | — primal is impossible |
Computational cost of kernel methods
Memorise:
- Build : kernel evaluations, each for vector inputs of dimension . Memory .
- Solve : via Cholesky or LU. Done once.
- Predict at a new point: kernel evaluations plus an 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).
Derive the Gaussian-process predictive distribution
Place a zero-mean GP prior with kernel on the latent function , and add i.i.d. Gaussian noise: . Then targets are jointly Gaussian with covariance . For a new input , the joint is Gaussian with covariance
Conditioning on gives with and . The mean is exactly the kernel-ridge prediction (with playing the role of ); the variance is the new and useful piece.
Derive the Nadaraya–Watson estimator
Start from a Parzen-window joint density estimate . Compute the conditional expectation:
Assume factorises as with and (a zero-mean window). The integrals separate and give
normalised kernel weights summing to 1 — the Nadaraya–Watson estimator. The prediction is a locally weighted average of training targets, closer points counting more.
Choose kernel hyperparameters
The default for GPs is to maximise the log marginal likelihood with respect to the kernel parameters . 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.
Memorise four formulas and you have the chapter
- Dual identity: .
- Dual ridge: .
- Prediction: .
- GP predictive variance: .
08 · Common mistakes
Where students get this wrong
'Positive semi-definite means all entries non-negative'
Definitely not. A kernel like is valid (its feature map lives in trig functions) yet its Gram matrix routinely has negative entries. PSD is a statement about quadratic forms: for every . 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 has four hyperparameters, each able to overfit. With small datasets, marginal-likelihood optimisation will happily walk into degenerate corners (e.g. 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 — 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 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 or , but it is a needless tax when . Always ask: how large are and ? 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 and 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 is a perfectly valid kernel. Kernel ridge with it is identical to ordinary ridge regression — the dual just does it via an inverse instead of a 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
- The kernel trick. If your algorithm only touches data through inner products , replace them with a single function and inherit the implicit feature space for free.
- Dual representation of ridge regression. The representer identity yields . Prediction is .
- Validity (Mercer). Symmetric 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.
- The kernel zoo. Linear () for a baseline; polynomial () for monomials of degree ; Gaussian / RBF () for an infinite-dimensional smooth-bump feature space.
- Kernels for non-vector data. Sets: . Probabilistic: . String, graph, and document kernels all exist.
- RBF networks & Nadaraya–Watson. An RBF network places one bump per training point and outputs . Exact interpolation overfits noisy data — regularisation (the 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.
- Gaussian processes. Derived from Bayesian linear regression: a Gaussian prior on induces a Gaussian prior on with covariance . A GP is any distribution over functions whose finite marginals are Gaussian, fully specified by mean and kernel . Add noise , condition on training targets via the partitioned-Gaussian formula: posterior mean (= kernel ridge with ), posterior variance .
- Costs and trade-offs. Training , prediction , memory . 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.