Simple Algorithm
Machine Learning · Descent · 24 min

Gaussian Processes

Distributions over functions with honest error bars.

Kernel ridge regression returns one curve. A Gaussian process returns a whole distribution over curves: put a prior on functions, observe a few noisy values, and condition. Out comes the same best-guess curve plus an error bar at every input, tight near the data and widening honestly where nobody has looked. The same machinery tunes its own hyperparameters, and it is the engine of Bayesian optimization.

What you’ll learn

  • Define a Gaussian process by its mean and covariance functions, and draw sample functions from a GP prior.
  • Derive the posterior mean and variance by conditioning a joint Gaussian, with and without observation noise.
  • Explain what the length scale, signal variance and noise do, and fit them by maximizing the log marginal likelihood, reading its data-fit and complexity terms.
  • Count the O(n3)\order{n^3} cost, relate the posterior mean to kernel ridge regression, and judge when the error bars can be trusted.

A prior over functions

A Gaussian process is a probability distribution over functions f:Rd→Rf:\R^d\to\R such that, for every finite set of inputs x1,…,xm\mathbf x_1,\dots,\mathbf x_m, the vector (f(x1),…,f(xm))(f(\mathbf x_1),\dots,f(\mathbf x_m)) is multivariate Gaussian. It is specified by a mean function m(x)=E[f(x)]m(\mathbf x)=\E[f(\mathbf x)] and a covariance function, a kernel, k(x,x′)=Cov⁡(f(x),f(x′))k(\mathbf x,\mathbf x')=\Cov\big(f(\mathbf x),f(\mathbf x')\big). One writes f∼GP(m,k)f\sim\mathcal{GP}(m,k), and then

(f(x1),…,f(xm))∼N(m,K),Kij=k(xi,xj).\big(f(\mathbf x_1),\dots,f(\mathbf x_m)\big)\sim\mathcal N(\mathbf m,K),\qquad K_{ij}=k(\mathbf x_i,\mathbf x_j).

The kernel must be positive semidefinite precisely because every such KK has to be a covariance matrix.

k(x,x′)=σf2exp⁡(−∥x−x′∥22ℓ2)k(\mathbf x,\mathbf x')=\sigma_f^2\exp\Big(-\frac{\norm{\mathbf x-\mathbf x'}^2}{2\ell^2}\Big)
The squared-exponential (RBF) kernel. The signal variance σf2\sigma_f^2 sets how far ff strays from its mean; the length scale ℓ\ell sets how far apart two inputs must be before their values become nearly uncorrelated. With m=0m=0, the usual default, the kernel alone decides which functions are plausible.

To draw a function, choose a fine grid of inputs, factor its covariance K=LL⊤K=LL^\top by Cholesky (adding a tiny "jitter" to the diagonal for numerical safety), draw z∼N(0,I)\mathbf z\sim\mathcal N(\mathbf 0,I) and set f=Lz\mathbf f=L\mathbf z. Then Cov⁡(f)=L E[zz⊤]L⊤=K\Cov(\mathbf f)=L\,\E[\mathbf z\mathbf z^\top]L^\top=K, and plotting f\mathbf f against the grid shows one random function.

Predict before you look

Rice's formula says a stationary zero-mean Gaussian process with kernel kk crosses zero on average 1π−k′′(0)/k(0)\frac1\pi\sqrt{-k''(0)/k(0)} times per unit length; for the RBF kernel −k′′(0)/k(0)=1/ℓ2-k''(0)/k(0)=1/\ell^2. About how many times does a prior sample with ℓ=0.5\ell=0.5 cross zero on [−5,5][-5,5]?

Show the answer

6.4 crossings

1πℓ\frac1{\pi\ell} crossings per unit length times a length of 10 gives 10/(0.5π)≈6.410/(0.5\pi)\approx6.4. At ℓ=1\ell=1 the same formula gives 3.23.2, matching the widget's samples. Halving the length scale doubles the wiggles.

Conditioning on data

Observations are noisy, yi=f(xi)+εiy_i=f(\mathbf x_i)+\varepsilon_i with independent εi∼N(0,σn2)\varepsilon_i\sim\mathcal N(0,\sigma_n^2). Under the prior (mean 0), the training targets y\mathbf y and the value f∗=f(x∗)f_*=f(\mathbf x_*) at a test input are jointly Gaussian, with k∗=(k(x1,x∗),…,k(xn,x∗))⊤\mathbf k_*=\big(k(\mathbf x_1,\mathbf x_*),\dots,k(\mathbf x_n,\mathbf x_*)\big)^\top:

(yf∗)∼N(0, (K+σn2Ik∗k∗⊤k(x∗,x∗)))\begin{pmatrix}\mathbf y\\ f_*\end{pmatrix}\sim\mathcal N\left(\mathbf 0,\ \begin{pmatrix}K+\sigma_n^2I & \mathbf k_*\\ \mathbf k_*^\top & k(\mathbf x_*,\mathbf x_*)\end{pmatrix}\right)
DerivationThe posterior is another Gaussian
  1. (ab)∼N(0,(ACC⊤B)) ⟹ b∣a∼N(C⊤A−1a, B−C⊤A−1C)\begin{pmatrix}\mathbf a\\\mathbf b\end{pmatrix}\sim\mathcal N\left(\mathbf 0,\begin{pmatrix}A&C\\C^\top&B\end{pmatrix}\right)\ \Longrightarrow\ \mathbf b\mid\mathbf a\sim\mathcal N\big(C^\top A^{-1}\mathbf a,\ B-C^\top A^{-1}C\big)

    For jointly Gaussian vectors with zero means, conditioning one block on another gives a Gaussian whose mean is a linear function of the observed block, and whose covariance is a Schur complement (derived in GP Regression in Depth):

  2. μ(x∗)=k∗⊤(K+σn2I)−1y,σ2(x∗)=k(x∗,x∗)−k∗⊤(K+σn2I)−1k∗\mu(\mathbf x_*)=\mathbf k_*^\top(K+\sigma_n^2I)^{-1}\mathbf y,\qquad\sigma^2(\mathbf x_*)=k(\mathbf x_*,\mathbf x_*)-\mathbf k_*^\top(K+\sigma_n^2I)^{-1}\mathbf k_*

    With a=y\mathbf a=\mathbf y and b=f∗\mathbf b=f_*, the posterior at any test input is

  3. μ(x∗)=∑i=1nαi k(xi,x∗),α=(K+σn2I)−1y\mu(\mathbf x_*)=\sum_{i=1}^n\alpha_i\,k(\mathbf x_i,\mathbf x_*),\qquad\boldsymbol\alpha=(K+\sigma_n^2I)^{-1}\mathbf y

    The mean is a weighted sum of kernel functions centered on the data, μ(x∗)=∑iαik(xi,x∗)\mu(\mathbf x_*)=\sum_i\alpha_ik(\mathbf x_i,\mathbf x_*) with α=(K+σn2I)−1y\boldsymbol\alpha=(K+\sigma_n^2I)^{-1}\mathbf y: exactly kernel ridge regression with λ=σn2\lambda=\sigma_n^2 (The Kernel Trick). The variance never mentions y\mathbf y: it is the prior variance minus what the inputs alone explain, so it depends only on where you have looked.

  4. y∗∣y∼N(μ(x∗), σ2(x∗)+σn2)y_*\mid\mathbf y\sim\mathcal N\big(\mu(\mathbf x_*),\ \sigma^2(\mathbf x_*)+\sigma_n^2\big)

    A new noisy observation y∗=f∗+ε∗y_*=f_*+\varepsilon_* has the same mean and the noise added to the variance, the posterior predictive distribution:

Predict before you look

One observation y=1y=1 at x=0x=0, with the RBF kernel (σf=1\sigma_f=1, ℓ=1\ell=1) and noise σn=1\sigma_n=1. What is the posterior mean at x=0x=0?

Show the answer

0.5

With one point, μ(0)=k(0,0) y/(k(0,0)+σn2)=1/(1+1)=0.5\mu(0)=k(0,0)\,y/(k(0,0)+\sigma_n^2)=1/(1+1)=0.5. The prior says f(0)f(0) is about 0±10\pm1, the observation says 1±11\pm1, and with equal variances the posterior splits the difference. With σn=0.1\sigma_n=0.1 the mean would be 1/1.01≈0.991/1.01\approx0.99.

Hyperparameters and the marginal likelihood

The kernel's hyperparameters θ=(ℓ,σf,σn)\boldsymbol\theta=(\ell,\sigma_f,\sigma_n) decide everything: ℓ\ell how fast the function may wiggle, σf\sigma_f how far it may stray, σn\sigma_n how closely it must honor each observation. A GP chooses them by maximizing the marginal likelihood, the probability of the observed targets with the function integrated out. Since y=f+ε\mathbf y=\mathbf f+\boldsymbol\varepsilon is Gaussian, p(y∣X,θ)=N(y;0,Kθ+σn2I)p(\mathbf y\mid X,\boldsymbol\theta)=\mathcal N(\mathbf y;\mathbf 0,K_{\boldsymbol\theta}+\sigma_n^2I), and its logarithm splits into three readable terms:

log⁡p(y∣X,θ)=−12 y⊤(K+σn2I)−1y⏟data fit − 12log⁡det⁡(K+σn2I)⏟complexity penalty − n2log⁡2π\log p(\mathbf y\mid X,\boldsymbol\theta)=\underbrace{-\tfrac12\,\mathbf y^\top(K+\sigma_n^2I)^{-1}\mathbf y}_{\text{data fit}}\ \underbrace{-\ \tfrac12\log\det(K+\sigma_n^2I)}_{\text{complexity penalty}}\ -\ \tfrac n2\log2\pi
A flexible model (short ℓ\ell) can fit many different datasets, so it spreads its probability thinly and its determinant is large: the complexity term punishes it. A rigid model (long ℓ\ell) concentrates its probability on smooth data and is punished by the data-fit term when the data are not smooth. The maximum balances the two, an automatic Occam's razor (Bayesian Model Selection).

In practice log⁡p\log p is maximized by gradient ascent over log⁡θ\log\boldsymbol\theta (the gradient has a closed form, derived in GP Regression in Depth), from several starting points, because the surface can have more than one local maximum: a short length scale with little noise and a long one with much noise can both explain the same data. Choosing hyperparameters this way is called type-II maximum likelihood or empirical Bayes; with only a handful of points it can return degenerate answers, a pitfall examined in Kernel Design for Gaussian Processes.

Check your understanding

A very short length scale lets the posterior mean pass through every observation. Why does maximizing the marginal likelihood usually not choose it?

  1. It does choose it; that is why GPs overfit
  2. Because the noise σn\sigma_n is held fixed during the fit
  3. Because the log-determinant term penalizes a model flexible enough to fit almost any dataset: it gives each particular dataset low probability
  4. Because the optimizer always starts at ℓ=1\ell=1
Show the answer

C. Because the log-determinant term penalizes a model flexible enough to fit almost any dataset: it gives each particular dataset low probability

The marginal likelihood is a probability over datasets and must integrate to one. A model that can produce almost anything gives low density to what it actually saw; the −12log⁡det⁡-\tfrac12\log\det term measures that spread. A short length scale also tells the model that neighboring values are unrelated, which these data contradict.

Cost, connections and honest error bars

StepCost
Cholesky factorization of K+σn2IK+\sigma_n^2IO(n3)\order{n^3} time (n3/6n^3/6 multiply–adds), O(n2)\order{n^2} memory
Weights α\boldsymbol\alpha and log⁡p\log p, from the factorO(n2)\order{n^2}
Posterior mean at a new inputO(n)\order{n}
Posterior variance at a new inputO(n2)\order{n^2} (one triangular solve)
Gradient of log⁡p\log pO(n3)\order{n^3} once, then O(n2)\order{n^2} per hyperparameter
Exact inference is routine for a few thousand points on a laptop. Beyond that come inducing-point approximations (GP Regression in Depth) and the iterative and low-rank methods of Scaling Kernel Methods.
python
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import ConstantKernel, RBF, WhiteKernel

kernel = ConstantKernel(1.0) * RBF(length_scale=1.0) + WhiteKernel(noise_level=0.01)
gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=5)
gp.fit(X_train, y_train)          # maximizes the log marginal likelihood
print(gp.kernel_)                 # fitted signal variance, length scale and noise level
mean, std = gp.predict(X_test, return_std=True)
lower, upper = mean - 2 * std, mean + 2 * std

ConstantKernel plays σf2\sigma_f^2 and WhiteKernel plays σn2\sigma_n^2. Because the noise is part of the kernel here, the returned std describes a new noisy observation y∗y_*, not f∗f_*: subtract the fitted noise variance to get the band of ff.

Key takeaways

  • A Gaussian process f∼GP(m,k)f\sim\mathcal{GP}(m,k) makes every finite vector of function values Gaussian with covariance Kij=k(xi,xj)K_{ij}=k(\mathbf x_i,\mathbf x_j). Prior samples are LzL\mathbf z with K=LL⊤K=LL^\top; the length scale sets their wiggle rate.
  • Conditioning the joint Gaussian gives μ(x∗)=k∗⊤(K+σn2I)−1y\mu(\mathbf x_*)=\mathbf k_*^\top(K+\sigma_n^2I)^{-1}\mathbf y and σ2(x∗)=k(x∗,x∗)−k∗⊤(K+σn2I)−1k∗\sigma^2(\mathbf x_*)=k(\mathbf x_*,\mathbf x_*)-\mathbf k_*^\top(K+\sigma_n^2I)^{-1}\mathbf k_*. The mean is kernel ridge regression with λ=σn2\lambda=\sigma_n^2; the variance depends only on where the inputs are.
  • The hyperparameters ℓ,σf,σn\ell,\sigma_f,\sigma_n are fitted by maximizing log⁡p(y∣X)\log p(\mathbf y\mid X) = data fit + complexity penalty + constant, an automatic Occam's razor; the surface can have several local maxima.
  • Exact GP regression costs O(n3)\order{n^3} time and O(n2)\order{n^2} memory. Its error bars are honest only up to the kernel: far from the data it reverts to the prior, and a wrong kernel gives confident mistakes.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Which property defines a Gaussian process?

  1. At every single input, f(x)f(\mathbf x) has a Gaussian distribution
  2. For every finite set of inputs, the vector of function values is jointly Gaussian
  3. The function is a weighted sum of Gaussian bumps
  4. The observation noise is Gaussian
Show the answer

B. For every finite set of inputs, the vector of function values is jointly Gaussian

A GP is defined by its finite-dimensional distributions: every finite collection of values is multivariate Gaussian, with mean m(xi)m(\mathbf x_i) and covariance k(xi,xj)k(\mathbf x_i,\mathbf x_j). That joint structure is what lets an observation at one input inform the value at another.

Question 2

You double every observed value yiy_i and refit with the same hyperparameters. What happens to the posterior standard deviation at a test input?

  1. It doubles
  2. It is unchanged: the posterior variance depends on the inputs and hyperparameters, not on the observed values
  3. It halves, because the signal is stronger
  4. It grows by 2\sqrt2
Show the answer

B. It is unchanged: the posterior variance depends on the inputs and hyperparameters, not on the observed values

σ2(x∗)=k(x∗,x∗)−k∗⊤(K+σn2I)−1k∗\sigma^2(\mathbf x_*)=k(\mathbf x_*,\mathbf x_*)-\mathbf k_*^\top(K+\sigma_n^2I)^{-1}\mathbf k_* contains no y\mathbf y. The mean doubles, the band does not. (Refitting the hyperparameters would change it, through σf\sigma_f and σn\sigma_n.)

Question 3

A zero-mean GP with an RBF kernel has observations only on [0,2][0,2]. What are its posterior mean and variance at x=50x=50?

  1. The last observed value, with variance σn2\sigma_n^2
  2. A linear extrapolation of the trend in the data, with growing variance
  3. Mean 0 and variance σf2\sigma_f^2: the prior, untouched by data that far away
  4. Undefined, because the kernel matrix becomes singular
Show the answer

C. Mean 0 and variance σf2\sigma_f^2: the prior, untouched by data that far away

At x=50x=50 every k(xi,50)k(\mathbf x_i,50) is essentially 0, so μ≈0\mu\approx0 and σ2≈k(50,50)=σf2\sigma^2\approx k(50,50)=\sigma_f^2. The RBF kernel encodes no trend, so the GP reverts to its prior instead of extrapolating.

Question 4

With an RBF kernel, distinct inputs and σn→0\sigma_n\to0, what does the GP posterior do at the training inputs?

  1. The mean interpolates the data exactly and the variance there goes to 0
  2. The mean is the average of the observations
  3. The variance there stays at σf2\sigma_f^2
  4. The posterior no longer exists
Show the answer

A. The mean interpolates the data exactly and the variance there goes to 0

With σn=0\sigma_n=0, μ(xj)=kj⊤K−1y=yj\mu(\mathbf x_j)=\mathbf k_j^\top K^{-1}\mathbf y=y_j because kj\mathbf k_j is the jj-th column of KK, and σ2(xj)=Kjj−kj⊤K−1kj=0\sigma^2(\mathbf x_j)=K_{jj}-\mathbf k_j^\top K^{-1}\mathbf k_j=0. The GP becomes an interpolator, the minimum-RKHS-norm one (Reproducing Kernel Hilbert Spaces).

Question 5

On some data, the log marginal likelihood peaks at ℓ≈1\ell\approx1 and is far lower at ℓ=5\ell=5. Which term is mainly responsible?

  1. The complexity term −12log⁡det⁡(K+σn2I)-\tfrac12\log\det(K+\sigma_n^2I), which grows more negative
  2. The constant −n2log⁡2π-\tfrac n2\log2\pi
  3. The noise variance, which the length scale changes
  4. The data-fit term −12y⊤(K+σn2I)−1y-\tfrac12\mathbf y^\top(K+\sigma_n^2I)^{-1}\mathbf y, which collapses because very smooth functions explain wiggly data badly
Show the answer

D. The data-fit term −12y⊤(K+σn2I)−1y-\tfrac12\mathbf y^\top(K+\sigma_n^2I)^{-1}\mathbf y, which collapses because very smooth functions explain wiggly data badly

A long length scale makes KK nearly singular along wiggly directions, so y⊤(K+σn2I)−1y\mathbf y^\top(K+\sigma_n^2I)^{-1}\mathbf y explodes: in the widget the data fit goes from −3.61-3.61 at ℓ=1\ell=1 to −193.6-193.6 at ℓ=5\ell=5, while the complexity term actually improves, from 1.96 to 10.72.

Go deeper

Further reading

  • C. E. Rasmussen & C. K. I. Williams, Gaussian Processes for Machine Learning (MIT Press, 2006), chapters 2 and 5.
  • C. K. I. Williams & C. E. Rasmussen, "Gaussian processes for regression," Advances in Neural Information Processing Systems 8 (1996).
  • A. O'Hagan, "Curve fitting and optimal design for prediction," Journal of the Royal Statistical Society B 40(1), 1–24 (1978).
  • G. Matheron, "Principles of geostatistics," Economic Geology 58(8), 1246–1266 (1963).