Gaussian process regression
Put data points on a plane and watch a Gaussian process fit them. See its uncertainty grow far from the data, change its beliefs by changing the kernel, and tune the kernel by maximizing the evidence.
A Gaussian process (GP) is a probability distribution over functions. Before we see data, it describes which functions we find plausible: smooth or rough, repeating or not, flat or with a trend. This belief is set by one function, the kernel . After we see data, Bayes' rule gives the posterior: the functions that agree with both the belief and the data. A GP gives more than one curve. It gives a mean prediction and an honest error bar at every .
In the playground you add data points with a tap and see four things live:
- the posterior mean , the best guess for the function,
- the 95% band , where the true function lies with probability 0.95 (if the model is right),
- three posterior samples: random functions that are plausible given the data,
- the log marginal likelihood (the evidence), a single number that says how well the kernel explains the data. Two buttons tune the kernel by making this number as large as possible.
1. The playground #
Tap empty space to add a point, tap a point to remove it, drag a point to move it. Blue: the posterior mean and the 95% band. Aqua, violet and magenta: three posterior samples. Orange, dashed: the true function of the example data. Press Clear to see the prior: what the GP believes before any data. Under the figure, the evidence and its three terms. The map shows the evidence over two hyperparameters (the orange dot is the current point, × is the best point of the map); click it to move there. Gradient ascent climbs the evidence step by step (its path is drawn on the map); Grid search jumps to the best point of the map.
2. Try this #
- From prior to posterior. Press Clear. The band is the same everywhere: . Now add one point near . Question: how wide is the band at , at and at ? What to see: at the point the band shrinks to about (the noise is all that is left). At the standard deviation is still . At it is , so the band is almost the prior band again. One point teaches the GP only about its neighbourhood, and the size of the neighbourhood is the length scale .
- The length scale. Pick 5 points and move from to . Question: what happens between the points, for example at ? Which value does the evidence prefer? What to see: with the mean returns to between the points and the band is as wide as the prior: the points are too far apart to say anything about each other. With the curve is stiff and the band is thin everywhere, but the evidence drops from about to about : such a confident, smooth curve explains these points badly. Now press Gradient ascent. It ends near with (mostly by making smaller), and it may say that the evidence is almost flat there. It is: every below about gives almost the same evidence. Five points far apart cannot tell these length scales apart. Here the evidence rules out long length scales, but not short ones.
- Two explanations of noisy data. Pick noisy (30 points, true noise ) and press Gradient ascent. Set Band for to and then to . Then move the slider all the way to the left () and the slider to about , and press Gradient ascent again. Question: do both runs end at the same place? What to see: the first run climbs from to in about 35 steps and ends near , : a smooth function plus noise (the true noise is ; 30 points give only a rough estimate). There, the band for misses 7 of the 30 points, and the band for contains all of them. The second run ends at , (the lower limit), : a wiggly function that passes through every point. Both are local maxima of the evidence. The data prefer the first by about 4.4 nats, a likelihood ratio of about .
- Kernels are beliefs: extrapolation. Pick periodic. The data stop near . Choose the RBF kernel and press Gradient ascent. Then pick periodic under Try again (this resets the hyperparameters and selects the periodic kernel) and press Gradient ascent. Question: what does each model predict for between and ? What to see: the RBF model ends near with . To the right of the data its mean falls back to and its band becomes the prior band: it knows nothing there. The periodic model finds the period (the true one) with , and it continues the pattern to with a thin band. The evidence prefers it by about 18 nats. Both runs say "not fully converged". More presses raise only a little: plain gradient ascent is slow on the flat ridge that is left.
- A local maximum and grid search. Pick trend + season: a straight trend plus a pattern with period , with the Sum kernel and a wrong start . Press Gradient ascent, then Grid search, then Gradient ascent again. Question: where does each step end? What to see: the first run ends at with (press again if it says "not fully converged"; then it stops at a local maximum). This is a real local maximum: a pattern that repeats every also repeats every . Grid search tries all values of on the map and jumps to ; the second gradient ascent climbs to with . Now switch to Linear and to RBF. The linear model continues the trend but not the season; the RBF model continues neither.
- A jump breaks the belief. Pick step: a function that jumps at , with noise . Press Gradient ascent with RBF and then with Matérn 3/2. Question: what noise level do the models choose? What to see: RBF ends at and Matérn 3/2 at , six to seven times the true noise. Both kernels believe that the function is equally smooth everywhere (they are stationary), so the best they can do is a long length scale plus a lot of "noise" that absorbs the jump. The rougher Matérn kernel explains the data a little better ( against ).
3. Kernels are prior beliefs #
A GP with mean and kernel is written . It means: for any finite set of inputs , the vector of function values is Gaussian,
So the kernel is a covariance function: is the covariance of and . If is large, the values at and move together; if it is near , they are independent. Every choice of kernel is a belief about the function. The matrix must be positive semi-definite for every set of inputs, so not every function of two variables is a kernel.
Switch kernels, move the sliders and drag the marker . Left: five random functions from the prior (colours) and the 95% band (grey). Below: the kernel , the covariance between the value at the marker and the value at . Right: the covariance matrix of the function values on a grid of 64 points. Notice how sets the width of the bump in and the speed of the wiggles; how the periodic kernel has bumps again at ; and how the matrix of the linear kernel is not constant along its diagonals.
The kernels of the playground ():
| Kernel | Belief about | |
|---|---|---|
| RBF (squared exponential) | very smooth: all derivatives exist; changes on a scale | |
| Matérn 3/2 | rougher: one derivative, not two | |
| Periodic | repeats exactly with period | |
| Linear | straight lines with | |
| Sum | a periodic pattern plus an independent trend |
- The length scale is the distance over which the function changes noticeably. For the RBF kernel, the correlation between and is .
- The signal standard deviation sets the typical size of : for the first three kernels at every .
- Stationary kernels depend only on , so the belief is the same everywhere. The linear kernel is not stationary: its variance grows with .
- Kernels can be combined. If and are independent, then . Products of kernels are kernels too.
The prior uses the RBF kernel with and . You observe 10 points, all in . What does the posterior say at ?
At every covariance is about , so . Then and . A stationary kernel does not extrapolate a trend; you need a kernel that believes in one (linear or periodic).
4. The math in short #
The posterior #
We observe with independent noise . Write for the matrix of the data inputs, , and for the vector of covariances between the data and a new input . Under the prior, and are jointly Gaussian:
Conditioning a Gaussian on part of its vector (a Schur complement) gives the posterior, again Gaussian:
- The mean is a weighted sum of kernel bumps: with .
- The variance is the prior variance minus what the data explain. It does not depend on , only on where the data are. Far from all data , so : back to the prior.
- This is the band for . A new observation has variance (the setting Band for: y).
- Posterior samples on a grid come from the full posterior covariance : draw and compute with .
Computing it. Never form . Factor once with the Cholesky decomposition , then use triangular solves:
The evidence and how to tune the kernel #
The hyperparameters are chosen by maximizing the log marginal likelihood: the log probability of the observed when is integrated out. Since ,
The two terms pull in opposite directions. A very short length scale lets pass through every point, so the data-fit term is good. But then is close to : the model spreads its probability over a huge set of wiggly functions, is large, and the penalty is large. A very long length scale is the opposite. The evidence picks the simplest model that explains the data: an automatic form of Occam's razor. This is why the evidence in experiment 2 rejects , and why it can have several local maxima (experiment 3).
The gradient has a closed form. With and using :
The playground optimizes (so every hyperparameter stays positive and all of them move on the same scale) with plain gradient ascent and a simple line search: . A step is kept only if the evidence increases; otherwise is made smaller and the step is tried again. After a good step grows by a factor , and no log value moves more than in one step. Each hyperparameter stays inside its slider range. The run stops when the evidence rises by less than in 50 steps; a test with the second derivatives (the Hessian) then says whether this is a maximum or an almost flat ridge. Plain gradient ascent is slow when the evidence is much more curved in one direction than in another. For the periodic kernel, the evidence is very sharp in and flat in , so it can need several presses. Gradient ascent finds only a local maximum near the start. Grid search evaluates the evidence at all points of the map (log-spaced values of two hyperparameters, the others fixed) and takes the best one: slow, but it cannot be trapped. Libraries such as scikit-learn and GPyTorch use L-BFGS or Adam with several random restarts.
Gradient ascent from a very short length scale ends at a curve that passes through every noisy point, with at its lower limit. Which term of the evidence makes this solution worse than a smooth curve with ?
The wiggly curve passes through the points, but its data-fit term is not better: in experiment 3 both solutions have a data-fit term of about , that is . The difference is the complexity term: with a short length scale the function values are less correlated, is larger and is lower ( against ). The constant does not depend on . So the smooth explanation wins by about 4.4 nats.
5. The cost: #
The Cholesky factorization of the matrix needs about floating-point operations, and the matrix needs numbers of memory. After that, the mean at a new point costs and the variance . Every new value of the hyperparameters needs a new factorization, so each step of gradient ascent costs , and a grid search costs (number of grid points) .
Press Measure on this device. It times the Cholesky factorization on your own computer or phone for growing . Blue: the measured times. Dashed: a line of slope 3 through the largest measurement. On log–log axes, time is a straight line of slope 3. The table extrapolates: what takes a fraction of a second for takes years for , and the matrix alone needs 8 TB.
This is why exact GPs are used for up to about points. For larger data sets there are approximations:
- Sparse GPs (inducing points): summarize the data with pseudo-points. The cost drops to .
- Iterative solvers: conjugate gradients with fast matrix–vector products (GPyTorch). Each iteration costs or less.
- Structure: in one dimension, a Matérn GP can be written as a state-space model, and the Kalman filter solves it in .
- Random features: replace the kernel by an explicit finite feature map, which gives Bayesian linear regression.
An exact GP with points needs 2 seconds for one Cholesky factorization on your laptop. About how long does it need with , and how much memory does need then (8 bytes per entry)?
The time grows like : doubling multiplies it by , so seconds. The memory grows like : bytes bytes MB. The option "4 seconds" scales the time like , a common mistake.
6. Related lessons #
- Positive definite matrices and Cholesky: why must be positive semi-definite, the Cholesky factor, and the Schur complement behind Gaussian conditioning.
- Factorizations and LU: solving with a factorization instead of an inverse, and low-rank (Nyström, inducing-point) approximations.
- Matrix calculus: and , the two rules behind the gradient of the evidence.
- Floating point and conditioning: why with a long length scale is badly conditioned, and why a small "jitter" on the diagonal helps.
- Eigenvalue algorithms and Krylov methods: conjugate gradients for large GPs.
- Gaussian integrals and Laplace's method: the marginal likelihood as a Gaussian integral.
- Line search and quasi-Newton methods: the optimizers used to tune GP hyperparameters.
- State-space models and the Kalman filter and the Kalman filter playground: a Matérn GP in time is a state-space model.
- Generalization in deep learning: the neural tangent kernel and the link between wide networks and kernel methods.
- ML for Science: a full lesson on Gaussian processes, scoring rules and calibration. ML Fundamentals: kernels and support vector machines. Probability and Statistics: the multivariate Gaussian and Bayesian inference.