Gaussian Process Regression
Chapter 7 ended with a prior: a Gaussian process that assigns a probability to every function before any data arrives. This chapter adds the data. We evaluate the unknown function at a few inputs, and ask what the prior, together with those values, says about the function everywhere else.
The answer needs no new machinery. A Gaussian process says that any finite set of function values is jointly Gaussian, and Section 4.5 showed how to condition a joint Gaussian on some of its coordinates. Gaussian process regression is that one formula, applied with the observed inputs on one side and the inputs we want to predict on the other. Everything else in the chapter is about reading the result: what the posterior mean does between and beyond the data, why the uncertainty depends on where we looked but not on what we saw, what changes when observations are noisy, and how to compute all of it without numerical trouble.
The posterior uncertainty is the quantity the rest of the book spends. Every acquisition function in Chapter 12 is a rule for turning it into the next query, so it is worth knowing its shape well.
8.1 Conditioning on observations #
Write for the unknown function on an input domain , and suppose it has a Gaussian process prior with mean zero and kernel :
We observe at inputs , collected in a set , and for now the observations are exact: . Stack the values into a vector . We want the distribution of at new inputs , whose unknown values we stack into .
The smallest case was worked in Example 4.3: two function values with correlation 0.8, one of them observed at 1.2, and a belief about the other that moved to mean 0.96 and standard deviation 0.6. What follows is that computation with observed values, any number of unobserved ones, and a kernel supplying the correlations.
By the definition of a Gaussian process, and are jointly Gaussian. Their covariance is built entry by entry from the kernel, so it has four blocks: covariances among the observed inputs, between observed and new inputs, and among the new inputs.
Here holds the covariances among observed inputs, those between observed and new inputs, and those among new inputs.
Conditioning on is now the operation from Section 4.5.
By Equation (4.15), for a joint Gaussian with blocks and , the conditional of given is Gaussian with mean and covariance .
- Take and . Both prior means are zero, so .
- Read the blocks from Equation (8.1): , , .
- Substitute. The conditional mean is and the conditional covariance is .
So the posterior over the new values is
Nothing in this derivation depended on how many new inputs we chose, or which. The posterior is again a Gaussian process: for any finite set of new inputs, the predictions are jointly Gaussian with the mean and covariance above. That closure is what makes the method practical. The data are absorbed once, and the result can be queried anywhere.
For a single new input , the blocks become a vector and two numbers. Write for the covariances between and the observed inputs. Then the posterior mean and variance are
These two lines are the working form of the whole chapter. The rest of the book writes and , always with their argument, when the number of observations matters. They are not to be confused with the noise standard deviation of Section 8.3, which has no argument and whose subscript stands for noise.
The variance in Equation (8.3) contains the inputs and the kernel but not the observed values . With the kernel fixed, how uncertain the model is at depends only on where we have looked, never on what we found there. The values enter only through the mean. When the kernel's hyperparameters are fitted to the data (Chapter 9), the values reach the variance indirectly, through the fitted lengthscale and amplitude.
8.2 Reading the posterior #
The figure below computes Equation (8.3) on a grid of 160 inputs. The blue line is the posterior mean; the shaded band covers the mean plus and minus 1.96 posterior standard deviations, which holds 95% of the posterior probability at each input. The strip underneath plots the standard deviation by itself.
A few experiments make the equations concrete.
Add a point far from the others. The band pinches to nearly nothing at the new input and opens again on either side. How quickly it opens is set by the lengthscale of the kernel: the RBF kernel has fallen to about two lengthscales away, so an observation says little about inputs more than two lengthscales from it.
Watch the mean between and beyond the data. Between nearby observations the mean interpolates smoothly. Far from all observations it returns to zero, the prior mean, and the band returns to the prior width. The model does not extrapolate trends; it reverts to what it believed before seeing data.
Shrink the lengthscale. The mean starts to wiggle back to zero between points, and the band balloons in every gap. Lengthen it and the mean becomes a stiff curve that may miss the points entirely if they disagree. Choosing the lengthscale is the subject of Chapter 9.
The case of a single observation shows the structure without any matrices.
Observe under an RBF prior with unit amplitude, so . Then , , and Equation (8.3) becomes
The mean is a copy of the kernel, centered at and scaled to pass through . The variance is zero at and rises to 1 as falls to zero. Every feature of the posterior in Figure 8.1 is a superposition of this picture, corrected for how the observations overlap.
8.2.1 The mean is a sum of bumps #
The single-observation case generalizes. Define the weights . Then the mean in Equation (8.3) is
a weighted sum of kernels, one centered on each observation. Turning on the kernel bumps in the figure draws each term. When two observations are close, their kernels overlap and the weights must compensate for each other, which is why a weight can be much larger than the value it helps to fit, or of the opposite sign.
Equation (8.4) is also the prediction of kernel ridge regression, a method with no probabilistic reading, when its regularization strength equals the noise variance introduced in the next section. The Gaussian process adds the variance, which ridge regression does not have, and which Bayesian optimization needs (Kanagawa et al., 2018).
Sources cited in Section 8.2 1
- Kanagawa et al. (2018) Gaussian Processes and Kernel Methods: A Review on Connections and Equivalences
8.3 Noisy observations #
Real evaluations are rarely exact. A training run with a different random seed gives a different accuracy; a person walking in an exoskeleton has good and bad strides. The standard model adds independent Gaussian noise to each observation:
Because the noise is independent of and across observations, it adds to the variance of each observation and nothing to any covariance. The joint distribution Equation (8.1) keeps its shape with replaced by , and so does the derivation:
Two things change in the picture. Move the noise slider in Figure 8.1 and the mean stops passing through the points: it now trades fit against smoothness, the way ridge regression does. The band also stops pinching to zero, because a noisy observation cannot pin down exactly.
Equation (8.6) gives the posterior variance of the latent value . A new noisy observation at would vary more, by the noise: . Which one a method needs depends on the question. Expected improvement in Section 12.3 asks about , so it uses ; a prediction interval for the next measurement uses the sum. Libraries differ in which one they return by default.
The noise variance is usually not known. It is a hyperparameter, fitted along with the lengthscale in Chapter 9. Too little noise makes the model chase every fluctuation; too much makes it ignore real structure. The two can also trade off against each other: a short lengthscale with little noise and a long lengthscale with much noise can explain the same wiggly data, which is one reason fitted hyperparameters deserve a skeptical look.
8.4 Computing it #
The formulas contain a matrix inverse, but a careful implementation never forms one. The matrix is symmetric and positive definite, so it has a Cholesky factorization with lower triangular (Section 3.5). Solving a triangular system costs and is numerically stable; inverting a nearly singular matrix is neither.
Input: inputs , observations , kernel , noise variance , test input .
- , so that .
- , two triangular solves.
- .
- .
- .
Here denotes the solution of . This is Algorithm 2.1 of Rasmussen and Williams (2006), which also returns the log marginal likelihood used in Section 9.3.
Step 4 is the variance formula in disguise: .
The cost splits into a part paid once per data set and a part paid per prediction. The factorization in step 1 takes time and memory. After that, each mean costs and each variance . A laptop factorizes a matrix with a few thousand rows in well under a second, and a Bayesian optimization run rarely has more than a few hundred observations, so the cubic cost is seldom the bottleneck in this book. Larger data sets need approximations that summarize the data with a smaller set of inducing points (Quiñonero-Candela and Rasmussen, 2005; Titsias, 2009).
import numpy as np
def rbf(a, b, ell=0.12):
return np.exp(-0.5 * (a[:, None] - b[None, :]) ** 2 / ell**2)
def gp_posterior(x, y, xs, noise=1e-4, ell=0.12):
L = np.linalg.cholesky(rbf(x, x, ell) + noise * np.eye(len(x)))
alpha = np.linalg.solve(L.T, np.linalg.solve(L, y))
Ks = rbf(x, xs, ell) # n x m
mean = Ks.T @ alpha
v = np.linalg.solve(L, Ks) # n x m
var = 1.0 - np.sum(v**2, axis=0) # k(x, x) = 1 for this kernel
return mean, var
A production implementation would use a triangular solver
(scipy.linalg.solve_triangular) for the solves, which is faster and states
the structure. Appendix C builds on this function.
Even a well-posed kernel matrix can fail to factorize in floating point when two inputs are nearly identical, because two rows become nearly equal and the smallest eigenvalue rounds to zero or below. Implementations add a small "jitter", a constant such as , to the diagonal and retry with a larger one if the factorization still fails. With observation noise the problem rarely arises, since already plays that role.
Sources cited in Section 8.4 3
- Rasmussen and Williams (2006) Gaussian Processes for Machine Learning
- Quiñonero-Candela and Rasmussen (2005) A Unifying View of Sparse Approximate Gaussian Process Regression
- Titsias (2009) Variational Learning of Inducing Variables in Sparse Gaussian Processes
8.5 Posterior samples #
The mean and the band summarize the posterior one input at a time. They do not show what a single plausible function looks like, because neighboring values are strongly correlated. To see whole functions, draw samples from the joint posterior Equation (8.2) on a grid of inputs. With the posterior covariance and its Cholesky factor, each sample is
the sampling recipe of Section 4.3. Turn on the samples in Figure 8.1. Each violet curve passes through (or near) every observation, stays inside the band most of the time, and is as smooth as the kernel allows. Each is a function the model considers possible.
Samples are not only a visualization. Thompson sampling, one of the acquisition rules in Section 12.5, draws one posterior sample and evaluates the objective where that sample is largest. On a grid of points, sampling costs for the factorization, which limits grids to a few thousand points; for larger or continuous domains, samples can be drawn as functions using random features or pathwise updates (Rahimi and Recht, 2007; Wilson et al., 2020).
Sources cited in Section 8.5 2
- Rahimi and Recht (2007) Random Features for Large-Scale Kernel Machines
- Wilson et al. (2020) Efficiently Sampling Functions from Gaussian Process Posteriors
8.6 Pitfalls #
Three habits prevent most surprises in practice.
Standardize the outputs. The zero prior mean and unit amplitude assume the function's values are centered near zero with spread near one. A function whose values sit around 1000 would be pulled toward zero away from the data. Subtract the mean of the observations and divide by their standard deviation before fitting, and undo the transformation on the predictions. Libraries such as BoTorch do this with an outcome transform (Balandat et al., 2020).
Scale the inputs. A single lengthscale assumes all input directions vary on comparable scales. Map each input to first, and give each dimension its own lengthscale when they matter differently (Section 9.2).
Distrust extrapolation. Beyond the data, the posterior returns to the prior by construction. If the objective has a trend that continues past the observed range, a stationary kernel will not predict it. That is usually acceptable in optimization over a bounded domain, but it is a reason to make the domain no larger than it needs to be.
Sources cited in Section 8.6 1
- Balandat et al. (2020) BoTorch: A Framework for Efficient Monte-Carlo Bayesian Optimization
8.7 Exercises #
Two observations and are made under a noise-free RBF prior with unit amplitude and lengthscale . Let . Compute the posterior variance at the midpoint in terms of , and check that it tends to the single-observation value as .
Solution
Here and, with the kernel value between the midpoint and each observation, . The inverse is , so and
Since , as both and tend to 1 and the variance tends to , the same as observing the midpoint itself. For small the second observation adds almost nothing: two nearly equal inputs carry almost the same information as one.
With noise variance and observations all at the same input , show that the posterior variance at is for a unit-amplitude kernel. What does this say about repeating an evaluation instead of trying a new input?
Solution
All entries of are 1, so and . Since , , and so (Exercise B.1 reaches the same result with the Sherman-Morrison formula). So and the variance is . Repeating an evaluation shrinks uncertainty at that input like , the rate of averaging noisy measurements, and teaches little about anywhere else. Bayesian optimization repeats an input only when the noise is large relative to the differences it is trying to resolve.
Further reading #
- Rasmussen and Williams (2006), chapter 2, is the standard derivation, in both the weight-space and function-space views, with the algorithm used here.
- Garnett (2023), chapters 2 to 4, develops Gaussian processes with Bayesian optimization in mind, including the inference choices this chapter treats as fixed.
- Görtler et al. (2019) is an interactive visual introduction that complements the figures in this chapter.
- Williams and Rasmussen (1996) introduced Gaussian process regression to machine learning. The same predictor had long been used in geostatistics as kriging (Krige, 1951; Matheron, 1963).
- Kanagawa et al. (2018) sets out the exact correspondences between Gaussian process regression and kernel methods such as kernel ridge regression.
References
- (2020). BoTorch: A Framework for Efficient Monte-Carlo Bayesian Optimization. Advances in Neural Information Processing Systems 33 (NeurIPS 2020). Cited in §8.6
- (2023). Bayesian Optimization. Cambridge University Press.
- (2019). A Visual Exploration of Gaussian Processes. Distill. doi:10.23915/distill.00017.
- (2018). Gaussian Processes and Kernel Methods: A Review on Connections and Equivalences. arXiv preprint. preprint Cited in §8.2
- (1951). A Statistical Approach to Some Basic Mine Valuation Problems on the Witwatersrand. Journal of the Southern African Institute of Mining and Metallurgy.
- (1963). Principles of Geostatistics. Economic Geology.
- (2005). A Unifying View of Sparse Approximate Gaussian Process Regression. Journal of Machine Learning Research. Cited in §8.4
- (2007). Random Features for Large-Scale Kernel Machines. Advances in Neural Information Processing Systems 20 (NeurIPS 2007). Cited in §8.5
- (2006). Gaussian Processes for Machine Learning. MIT Press. Cited in §8.4
- (2009). Variational Learning of Inducing Variables in Sparse Gaussian Processes. Proceedings of the 12th International Conference on Artificial Intelligence and Statistics (AISTATS 2009). Cited in §8.4
- (1996). Gaussian Processes for Regression. Advances in Neural Information Processing Systems 8 (NeurIPS 1995).
- (2020). Efficiently Sampling Functions from Gaussian Process Posteriors. Proceedings of the 37th International Conference on Machine Learning (ICML 2020). Cited in §8.5