Bayesian Optimization
Part I: Foundations
中文

The Gaussian Distribution

The previous two chapters built a language and a toolkit. Chapter 2 gave the rules for reasoning about uncertain quantities: distributions, the sum rule that marginalizes, and the product rule that conditions. Chapter 3 gave the matrices those rules turn into when there are many quantities at once: covariance matrices, their Cholesky factors, and block matrices. This chapter puts the two together in a single distribution, the Gaussian, which carries the rest of the book.

One distribution deserves a chapter because of what a Bayesian optimizer does with its beliefs. It keeps a belief about an unknown function, updates the belief after each evaluation, and asks it where to look next. Each step is an operation on a probability distribution, and for most distributions these operations are integrals with no closed form. For the Gaussian, each has an exact answer in a few lines of linear algebra: a linear map of a Gaussian is Gaussian, ignoring some of its coordinates leaves a Gaussian, and conditioning on some of its coordinates leaves a Gaussian. A Gaussian process (Section 7.3) is a Gaussian over function values, so these three closure properties are also what make Gaussian process regression and Bayesian optimization computable.

The chapter starts with one variable, where the formulas can be read at a glance, moves to many variables, where a covariance matrix gives the distribution its shape, and then derives the three operations in turn. The last of them, conditioning, is the chapter's main result; Chapter 8 applies it without change. A later section separates two ways of combining Gaussians that are easy to confuse, and prepares the Bayesian updating of Chapter 5.

4.1 One dimension #

Suppose a training run with a new learning rate has not happened yet. From experience with similar runs you expect a validation accuracy of about 0.82, rarely off by more than 0.06 in either direction. That belief has a center and a spread, treats deviations up and down alike, and makes large deviations rarer than small ones. The Gaussian distribution, also called the normal distribution, is the standard way to write such a belief with two numbers.

A random variable XX is Gaussian with mean μ\mu and variance σ2>0\sigma^2 > 0, written X∼N(μ,σ2)X \sim \N(\mu, \sigma^2), when its density is

N(x; μ,σ2)=12πσ2exp⁡ ⁣(−(x−μ)22σ2).\N(x;\, \mu, \sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x - \mu)^2}{2\sigma^2}\right).
(4.1)

The semicolon separates the point xx where the density is evaluated from the parameters μ\mu and σ2\sigma^2. As Section 2.3 explained, a density is not a probability; probabilities are areas under it.

Read the formula from the inside out. The exponent −(x−μ)2/2σ2-(x - \mu)^2 / 2\sigma^2 is a downward parabola with its peak at x=μx = \mu. The exponential turns the parabola into a bell: it equals 1 at the peak and falls quickly as the parabola goes negative. The factor in front scales the bell so that its total area is one. Taking logarithms undoes the exponential:

log⁡N(x; μ,σ2)=−(x−μ)22σ2−12log⁡(2πσ2).\log \N(x;\, \mu, \sigma^2) = -\frac{(x - \mu)^2}{2\sigma^2} - \tfrac12 \log(2\pi\sigma^2).

A Gaussian is the exponential of a quadratic. The converse is the fact that does most of the work in this chapter: any density whose logarithm is a quadratic function of xx, opening downward, is Gaussian, and its parameters can be read off the coefficients. If

log⁡p(x)=−12αx2+βx+const,α>0,thenp(x)=N ⁣(x; β/α,  1/α).\log p(x) = -\tfrac12 \alpha x^2 + \beta x + \text{const}, \quad \alpha > 0, \qquad\text{then}\qquad p(x) = \N\!\left(x;\, \beta/\alpha,\; 1/\alpha\right).
(4.2)

To see it, complete the square: −12αx2+βx=−12α(x−β/α)2+β2/2α-\tfrac12\alpha x^2 + \beta x = -\tfrac12\alpha(x - \beta/\alpha)^2 + \beta^2/2\alpha, and the last term is a constant that the normalization absorbs. The coefficient α\alpha, the reciprocal of the variance, is called the precision. To show that some distribution is Gaussian, we will repeatedly show that its log density is quadratic and then apply this recipe.

The two parameters mean what their names say. The mean is the expected value, E[X]=μ\E[X] = \mu, and the variance is the expected squared deviation, Var⁡[X]=E[(X−μ)2]=σ2\Var[X] = \E[(X - \mu)^2] = \sigma^2 (Section 2.6). The standard deviation σ\sigma, the square root of the variance, is in the units of xx, so it is the number to think with. The accuracy belief above is about N(0.82,0.032)\N(0.82, 0.03^2): a standard deviation of 0.03, with deviations of twice that size rare.

4.1.1 The standard normal #

Every Gaussian is a shifted and stretched copy of one reference distribution, the standard normal Z∼N(0,1)Z \sim \N(0, 1). If X∼N(μ,σ2)X \sim \N(\mu, \sigma^2), then Z=(X−μ)/σZ = (X - \mu)/\sigma is standard normal, and conversely X=μ+σZX = \mu + \sigma Z. The value z=(x−μ)/σz = (x - \mu)/\sigma, the number of standard deviations by which xx lies above the mean, is called its z-score. The standard normal has its own symbols, used throughout the book:

ϕ(z)=12π e−z2/2,Φ(z)=∫−∞zϕ(t) dt.\phi(z) = \frac{1}{\sqrt{2\pi}}\, e^{-z^2/2}, \qquad \Phi(z) = \int_{-\infty}^{z} \phi(t)\,\dd t.
(4.3)

The function ϕ\phi is the density and Φ\Phi the cumulative distribution function: Φ(z)\Phi(z) is the probability that Z≤zZ \le z. There is no formula for Φ\Phi in elementary functions. Libraries compute it through the error function, Φ(z)=12(1+erf⁡(z/2))\Phi(z) = \tfrac12\left(1 + \operatorname{erf}(z/\sqrt{2})\right), to full floating-point precision.

Standardizing turns every probability question about XX into one about Φ\Phi:

P(a≤X≤b)=Φ ⁣(b−μσ)−Φ ⁣(a−μσ).\Prob(a \le X \le b) = \Phi\!\left(\frac{b - \mu}{\sigma}\right) - \Phi\!\left(\frac{a - \mu}{\sigma}\right).
(4.4)

A few values are worth remembering. The interval μ±σ\mu \pm \sigma holds 68.3% of the probability, μ±1.96σ\mu \pm 1.96\sigma holds 95%, μ±2σ\mu \pm 2\sigma holds 95.4%, and μ±3σ\mu \pm 3\sigma holds 99.7%. The tails fall off fast: a value more than five standard deviations from the mean, in either direction, has probability about 5.7×10−75.7 \times 10^{-7}.

Example 4.1 Will the new run beat the best so far?

Keep the belief f∼N(0.82,0.032)f \sim \N(0.82, 0.03^2) about the accuracy ff of the new run, and suppose the best run so far reached 0.85. By Equation (4.4), the probability that the new run does better is

P(f>0.85)=1−Φ ⁣(0.85−0.820.03)=1−Φ(1)≈0.159.\Prob(f > 0.85) = 1 - \Phi\!\left(\frac{0.85 - 0.82}{0.03}\right) = 1 - \Phi(1) \approx 0.159.

A belief centered 0.03 below the best result still gives the new run about one chance in six. Computed at every candidate input from a Gaussian process posterior, this number is the acquisition function called probability of improvement (Section 12.2). Expected improvement (Section 12.3) is assembled from ϕ\phi and Φ\Phi in the same way.

4.1.2 Why this distribution #

A reader may wonder why this particular bell curve, and not some other, is the default. There are three reasons, of different kinds.

The first comes from a theorem. The central limit theorem says that a sum of many independent random quantities with finite variance, none of which dominates, is approximately Gaussian once standardized, whatever the distribution of the individual terms (Blitzstein and Hwang, 2019). Measurement noise is often the sum of many small disturbances, such as thermal fluctuations, timing jitter, and rounding, and is then close to Gaussian. A classic demonstration: the sum of twelve independent uniform numbers on [0,1][0, 1], minus 6, has mean 0 and variance 1, and its histogram is already hard to tell from ϕ\phi.

The second is a principle. Among all distributions on the real line with a given mean and variance, the Gaussian has the largest entropy, a measure of how spread out a distribution is that Section 6.1 makes precise (Cover and Thomas, 2006, ch. 12). If all we are willing to commit to is a center and a spread, the Gaussian is the choice that assumes nothing more.

The third is convenience, and it is why this book uses Gaussians even where the first two reasons do not apply: every operation in the rest of this chapter has a closed form. Convenience is a reason to choose a model, not evidence that the world is Gaussian. Real quantities can be skewed, bounded, or heavy-tailed, with extreme values far more common than the 5.7×10−75.7 \times 10^{-7} above suggests. A comparison between two options, the observation at the heart of Part IV, is not Gaussian at all; Chapter 17 shows how to approximate the resulting posterior by a Gaussian so that the machinery of this chapter still applies.

Sources cited in Section 4.1 2
  1. Blitzstein and Hwang (2019) Introduction to Probability
  2. Cover and Thomas (2006) Elements of Information Theory

4.2 Many dimensions #

A Bayesian optimizer never holds a belief about a single number. It holds beliefs about the objective at many inputs at once, and those beliefs are linked: if the accuracy at a learning rate of 0.010 turns out high, the accuracy at 0.011 is probably high too. A list of separate one-dimensional Gaussians cannot express that link. We need a joint distribution over a vector of values that records how each pair of values moves together.

Start with two independent coordinates. If x1∼N(0,σ12)x_1 \sim \N(0, \sigma_1^2) and x2∼N(0,σ22)x_2 \sim \N(0, \sigma_2^2) are independent, their joint density is the product of the two densities (Section 2.7), and multiplying exponentials adds the exponents:

p(x1,x2)∝exp⁡ ⁣(−x122σ12−x222σ22).p(x_1, x_2) \propto \exp\!\left(-\frac{x_1^2}{2\sigma_1^2} - \frac{x_2^2}{2\sigma_2^2}\right).

The density is constant wherever the exponent is, on the curves x12/σ12+x22/σ22=r2x_1^2/\sigma_1^2 + x_2^2/\sigma_2^2 = r^2. These are ellipses with axes along the coordinate directions, and circles when σ1=σ2\sigma_1 = \sigma_2. To link the two coordinates, we allow the quadratic in the exponent a cross term x1x2x_1 x_2. The ellipses then tilt, so that a large x1x_1 makes a large x2x_2 more likely, or less likely, depending on the direction of the tilt. All of this is recorded in one matrix.

The matrix is the covariance matrix Σ\mSigma of Section 2.6.3. For a random vector x=(x1,…,xd)⊤\vx = (x_1, \dots, x_d)^\T with mean vector μ\vmu, its entries are Σij=Cov⁡[xi,xj]=E[(xi−μi)(xj−μj)]\Sigma_{ij} = \Cov[x_i, x_j] = \E[(x_i - \mu_i)(x_j - \mu_j)], with the variances on the diagonal. It is symmetric and positive semidefinite (Section 3.3), and dividing an entry by the two standard deviations gives the correlation ρij=Σij/ΣiiΣjj\rho_{ij} = \Sigma_{ij} / \sqrt{\Sigma_{ii}\Sigma_{jj}}.

Definition 4.1 Multivariate Gaussian

A random vector x∈Rd\vx \in \R^d has a Gaussian distribution with mean μ∈Rd\vmu \in \R^d and positive definite covariance matrix Σ∈Rd×d\mSigma \in \R^{d \times d}, written x∼N(μ,Σ)\vx \sim \N(\vmu, \mSigma), when its density is

N(x; μ,Σ)=1(2π)d/2 ∣Σ∣1/2exp⁡ ⁣(−12(x−μ)⊤Σ−1(x−μ)),\N(\vx;\, \vmu, \mSigma) = \frac{1}{(2\pi)^{d/2}\, \lvert\mSigma\rvert^{1/2}} \exp\!\left(-\tfrac12 (\vx - \vmu)^\T \mSigma^{-1} (\vx - \vmu)\right),
(4.5)

where ∣Σ∣\lvert\mSigma\rvert is the determinant of Σ\mSigma.

Every piece has a one-dimensional counterpart. With d=1d = 1 and Σ=[σ2]\mSigma = [\sigma^2] the formula is Equation (4.1). The exponent is again a quadratic, now a quadratic form in the vector x−μ\vx - \vmu, with the inverse covariance Σ−1\mSigma^{-1} in the role of 1/σ21/\sigma^2. The inverse covariance is called the precision matrix, and it is the natural object in several derivations below. The determinant in the normalizer measures the volume over which the distribution spreads (Section 3.6) and plays the role of σ\sigma: a more spread-out distribution has a lower peak, so that the total probability stays one.

The recipe Equation (4.2) carries over unchanged. If a density satisfies

log⁡p(x)=−12x⊤Λx+h⊤x+const\log p(\vx) = -\tfrac12 \vx^\T \bm{\Lambda} \vx + \mathbf{h}^\T \vx + \text{const}

for a positive definite matrix Λ\bm{\Lambda} and a vector h\mathbf{h}, then pp is Gaussian with precision Λ\bm{\Lambda}, that is,

x∼N ⁣(Λ−1h,  Λ−1).\vx \sim \N\!\left(\bm{\Lambda}^{-1}\mathbf{h},\; \bm{\Lambda}^{-1}\right).
(4.6)

Completing the square works as before, and expanding the right side checks it:

−12x⊤Λx+h⊤x=−12(x−Λ−1h)⊤Λ(x−Λ−1h)+12h⊤Λ−1h.-\tfrac12\vx^\T\bm{\Lambda}\vx + \mathbf{h}^\T\vx = -\tfrac12(\vx - \bm{\Lambda}^{-1}\mathbf{h})^\T\bm{\Lambda}(\vx - \bm{\Lambda}^{-1}\mathbf{h}) + \tfrac12\mathbf{h}^\T\bm{\Lambda}^{-1}\mathbf{h}.

The last term does not depend on x\vx.

4.2.1 Shape #

The quantity in the exponent has a name. The Mahalanobis distance of x\vx from μ\vmu is

r(x)=(x−μ)⊤Σ−1(x−μ),r(\vx) = \sqrt{(\vx - \vmu)^\T \mSigma^{-1} (\vx - \vmu)},
(4.7)

the multivariate z-score. In one dimension it is ∣x−μ∣/σ\lvert x - \mu\rvert / \sigma, the number of standard deviations. In general it measures distance in units of the distribution's own spread, direction by direction: a point can be far from the mean in ordinary distance and still close in Mahalanobis distance, if it lies along a direction in which the distribution is wide. The density depends on x\vx only through rr, so its contours are the sets where rr is constant: ellipses in two dimensions, ellipsoids in more.

Where do the ellipses point? Write the covariance in its eigendecomposition Σ=UΛeU⊤\mSigma = \mathbf{U}\bm{\Lambda}_{\mathrm{e}}\mathbf{U}^\T, with orthonormal eigenvectors ui\mathbf{u}_i in the columns of U\mathbf{U} and eigenvalues λi\lambda_i on the diagonal of Λe\bm{\Lambda}_{\mathrm{e}} (Section 3.4). In the rotated coordinates y=U⊤(x−μ)\mathbf{y} = \mathbf{U}^\T(\vx - \vmu) the quadratic form becomes ∑iyi2/λi\sum_i y_i^2/\lambda_i, with no cross terms. The axes of every contour therefore point along the eigenvectors, and the ellipse at Mahalanobis distance rr has semi-axes of length rλir\sqrt{\lambda_i}. The eigenvalues are the variances along the principal directions, and their product is ∣Σ∣\lvert\mSigma\rvert. A multivariate Gaussian is an axis-aligned bell in some rotated coordinate system, and the eigenvectors say which one.

For two coordinates with standard deviations σ1,σ2\sigma_1, \sigma_2 and correlation ρ\rho, the covariance matrix and its determinant are

Σ=[σ12ρσ1σ2ρσ1σ2σ22],∣Σ∣=σ12σ22(1−ρ2).\mSigma = \begin{bmatrix} \sigma_1^2 & \rho\sigma_1\sigma_2 \\ \rho\sigma_1\sigma_2 & \sigma_2^2 \end{bmatrix}, \qquad \lvert\mSigma\rvert = \sigma_1^2\sigma_2^2(1 - \rho^2).
(4.8)

The figure below draws this case with mean zero.

−202x1−202x2u1u2Covariance matrixΣ =1.000.700.701.00eigenvalues λ1 = 1.70, λ2 = 0.30det Σ = σ1²σ2²(1 − ρ²) = 0.51Ellipses at Mahalanobis distance1, 2, 3 hold 39%, 86%, 99%Dashed: eigenvector axes
−202x1−202x2u1u2Covariance matrixΣ =1.000.700.701.00eigenvalues λ1 = 1.70, λ2 = 0.30det Σ = σ1²σ2²(1 − ρ²) = 0.51Ellipses at Mahalanobis distance1, 2, 3 hold 39%, 86%, 99%Dashed: eigenvector axes
Figure 4.1 A two-dimensional Gaussian with mean zero and the covariance Equation (4.8). The shaded ellipses are the contours at Mahalanobis distance 1, 2, and 3; the dashed lines are the eigenvector axes; the strips above and to the right show the marginal densities of x1x_1 and x2x_2. The sliders set the two standard deviations and the correlation. The Samples and Condition views belong to Section 4.3 and Section 4.5.

Set ρ\rho to zero and the two standard deviations equal. The ellipses become circles. The distribution looks the same in every direction, and the eigenvectors could point anywhere.

Move ρ\rho toward 0.95. The ellipses narrow into a needle along the diagonal. With both standard deviations at 1 the eigenvalues are 1+ρ1 + \rho and 1−ρ1 - \rho, so the first approaches 2 while the second and the determinant approach zero: the distribution concentrates near a line, and once x1x_1 is known, x2x_2 is nearly determined. At ρ=±1\rho = \pm 1 the covariance would be singular, the density of Equation (4.5) would not exist, and a Cholesky factorization would fail. This is the floating-point trouble that a small diagonal jitter repairs (Section 8.4).

Make ρ\rho negative. The ellipses tilt the other way: a large x1x_1 now goes with a small x2x_2.

Watch the two strips while you move ρ\rho. They do not change. Section 4.4 explains why.

How much probability does each ellipse hold? Less than the one-dimensional numbers suggest. In two dimensions the probability inside the ellipse at Mahalanobis distance rr is 1−e−r2/21 - e^{-r^2/2}: 39% inside r=1r = 1, 86% inside r=2r = 2, and 99% inside r=3r = 3. Enclosing 95% takes r≈2.45r \approx 2.45, not 1.96. The gap widens with the dimension.

One more property is special to Gaussians. When Σ\mSigma is diagonal, the quadratic form has no cross terms and the density factorizes into a product of one-dimensional densities, so the coordinates are independent. For a Gaussian vector, uncorrelated therefore means independent. For other distributions it does not (Section 2.7), and Exercise 4.3 shows two variables that are each Gaussian and uncorrelated, yet dependent, because they are not jointly Gaussian.

4.3 Linear maps and sampling #

Two practical questions lead to the same result. First, if f(x1)f(\vx_1) and f(x2)f(\vx_2) are jointly Gaussian, what is the distribution of their difference, or of their average? Part IV needs the difference whenever a person compares two options. Second, a random number generator produces independent standard normal numbers. How do we turn them into a draw from N(μ,Σ)\N(\vmu, \mSigma) with an arbitrary covariance? Every picture of functions drawn from a model needs such draws, and so does Thompson sampling (Section 12.5), a rule that draws one plausible objective from the model and evaluates where that draw is highest.

Both answers follow from one closure property. Let x∼N(μ,Σ)\vx \sim \N(\vmu, \mSigma) in dd dimensions, let A\mA be an m×dm \times d matrix, and let c\mathbf{c} be a vector in Rm\R^m. Then

y=Ax+c  ∼  N ⁣(Aμ+c,  AΣA⊤).\vy = \mA\vx + \mathbf{c} \;\sim\; \N\!\left(\mA\vmu + \mathbf{c},\; \mA\mSigma\mA^\T\right).
(4.9)

A linear map of a Gaussian is Gaussian. The mean is mapped like a point, and the covariance is sandwiched between the matrix and its transpose.

One caveat. The density of Definition 4.1 needs a positive definite covariance, and AΣA⊤\mA\mSigma\mA^\T is positive definite only when no row of A\mA is a combination of the others. When it is not, as when A\mA has more rows than columns, y\vy is still Gaussian in the sense used in step 6 below, but it is confined to a flat of lower dimension and has no density on Rm\R^m. The formulas for its mean and covariance hold in both cases.

Derivation A linear map of a Gaussian
  1. By linearity of expectation (Section 2.6), E[y]=A E[x]+c=Aμ+c\E[\vy] = \mA\,\E[\vx] + \mathbf{c} = \mA\vmu + \mathbf{c}.
  2. Subtracting the mean, y−E[y]=A(x−μ)\vy - \E[\vy] = \mA(\vx - \vmu).
  3. By the definition of the covariance matrix, Cov⁡[y]=E[(y−E[y])(y−E[y])⊤]=E[A(x−μ)(x−μ)⊤A⊤]\Cov[\vy] = \E\big[(\vy - \E[\vy])(\vy - \E[\vy])^\T\big] = \E\big[\mA(\vx - \vmu)(\vx - \vmu)^\T\mA^\T\big].
  4. A\mA is constant, so it moves outside the expectation: Cov⁡[y]=A E[(x−μ)(x−μ)⊤]A⊤=AΣA⊤\Cov[\vy] = \mA\,\E\big[(\vx - \vmu)(\vx - \vmu)^\T\big]\mA^\T = \mA\mSigma\mA^\T.
  5. That y\vy is Gaussian, and not merely some distribution with this mean and covariance, needs one more argument. When A\mA is square and invertible, substituting x=A−1(y−c)\vx = \mA^{-1}(\vy - \mathbf{c}) into Equation (4.5) leaves an exponent that is a quadratic function of y\vy, so y\vy is Gaussian by Equation (4.6).
  6. For a general A\mA, such as the single row that forms a difference, use the equivalent definition that a vector is Gaussian exactly when every linear combination of its coordinates is a one-dimensional Gaussian (Blitzstein and Hwang, 2019). A linear combination of the coordinates of y\vy is a linear combination of the coordinates of x\vx, so it is Gaussian, and so is y\vy.

4.3.1 Sampling with the Cholesky factor #

Sampling runs the map in the useful direction. Let z∼N(0,I)\vz \sim \N(\mathbf{0}, \mI) be a vector of dd independent standard normal numbers, which every numerical library provides (the classic construction from uniform random numbers is the transform of Box and Muller (1958)). Choose any matrix L\mL with LL⊤=Σ\mL\mL^\T = \mSigma and set

x=μ+Lz.\vx = \vmu + \mL\vz.
(4.10)

By Equation (4.9), x\vx is Gaussian with mean μ\vmu and covariance LIL⊤=Σ\mL\mI\mL^\T = \mSigma. The Cholesky factor of Section 3.5, lower triangular with a positive diagonal, is the usual choice of L\mL: it exists for every positive definite Σ\mSigma, it costs O(d3)O(d^3) operations to compute once, and after that each draw costs one triangular matrix-vector product (Rasmussen and Williams, 2006, app. A.2). Any other square root would do, such as UΛe1/2\mathbf{U}\bm{\Lambda}_{\mathrm{e}}^{1/2} from the eigendecomposition. It would map a given z\vz to a different point, but the distribution of the points would be the same.

In two dimensions the Cholesky factor of Equation (4.8) can be written down, and multiplying it by z\vz shows how each coordinate is built:

L=[σ10ρσ2σ21−ρ2],x1=σ1z1,x2=ρσ2z1+σ21−ρ2 z2.\mL = \begin{bmatrix} \sigma_1 & 0 \\ \rho\sigma_2 & \sigma_2\sqrt{1 - \rho^2} \end{bmatrix}, \qquad \begin{aligned} x_1 &= \sigma_1 z_1, \\ x_2 &= \rho\sigma_2 z_1 + \sigma_2\sqrt{1 - \rho^2}\, z_2. \end{aligned}
(4.11)

Multiplying out confirms LL⊤=Σ\mL\mL^\T = \mSigma. The formula also says what correlation is, mechanically. The coordinate x2x_2 is built partly from the same random number z1z_1 that drives x1x_1 and partly from fresh randomness z2z_2; a fraction ρ2\rho^2 of its variance comes from the shared part. At ρ=0\rho = 0 the two coordinates share nothing, and at ρ=±1\rho = \pm 1 they share everything.

−202x1−202x2Cholesky factor, L Lᵀ = ΣL =1.000.000.700.71x = L z, z ~ N(0, I)grey: 250 draws of zblue: the same draws as L zsample correlation 0.70 (ρ = 0.70)
−202x1−202x2Cholesky factor, L Lᵀ = ΣL =1.000.000.700.71x = L z, z ~ N(0, I)grey: 160 draws of zblue: the same draws as L zsample correlation 0.70 (ρ = 0.70)
Figure 4.2 Sampling with the Cholesky factor, Equation (4.10). Gray points are draws of a standard normal z\vz; blue points are the same draws after the map Lz\mL\vz, which has the covariance set by the sliders. Orange arrows follow six draws from z\vz to Lz\mL\vz. The dashed ellipse is the contour at Mahalanobis distance 2. New samples draws a fresh set.

Follow the arrows. Every gray point is moved by the same matrix. Because L\mL is lower triangular, x1=σ1z1x_1 = \sigma_1 z_1 depends on z1z_1 alone; with σ1=1\sigma_1 = 1 the map leaves the first coordinate unchanged and every arrow is vertical. With a positive ρ\rho, the map adds ρσ2z1\rho\sigma_2 z_1 to the second coordinate, which pushes points on the left down and points on the right up, and it shrinks z2z_2 by the factor 1−ρ2\sqrt{1 - \rho^2}. The round cloud becomes a tilted ellipse.

Compare the sample correlation with ρ\rho. The readout computes the correlation of the blue points. It differs from ρ\rho by a few hundredths, and a fresh set of samples gives a different error: sampling noise, with a standard deviation of roughly (1−ρ2)/n(1 - \rho^2)/\sqrt{n} for nn points.

Set ρ\rho to zero with unequal standard deviations. L\mL is then diagonal and only stretches the cloud along the axes.

For a Gaussian process, x\vx holds the function values on a grid of inputs, one coordinate per grid point, and the cubic cost of the factorization is what limits posterior samples to grids of a few thousand points (Section 8.5). Grids run out quickly as the input dimension grows: 20 points per axis is 20 values on a line, 400 on a square, and 8,000 in a three-dimensional cube, whose covariance matrix has 64 million entries. Beyond two or three input dimensions, samples are drawn at a few thousand scattered candidate points instead of a grid.

The difference of two function values is the other question this section began with.

Example 4.2 The difference of two function values

Let A=f(x1)A = f(\vx_1) and B=f(x2)B = f(\vx_2) be jointly Gaussian with means μA,μB\mu_A, \mu_B, variances vA,vBv_A, v_B, and covariance cc. The difference D=A−BD = A - B is the map with the single row (1,−1)(1, -1), so by Equation (4.9) it is Gaussian with mean μA−μB\mu_A - \mu_B and variance

[1−1][vAccvB][1−1]=vA+vB−2c.\begin{bmatrix} 1 & -1 \end{bmatrix} \begin{bmatrix} v_A & c \\ c & v_B \end{bmatrix} \begin{bmatrix} 1 \\ -1 \end{bmatrix} = v_A + v_B - 2c.

The covariance enters with a minus sign. When the two values are strongly positively correlated, as for two nearby inputs under a smooth Gaussian process, their difference is much less uncertain than either value alone. A model can be confident that one of two similar options is better while being unsure how good either one is. Section 16.3 builds a model of human comparisons on this difference, and Section 19.4 uses it to score pairs of queries.

Sources cited in Section 4.3 3
  1. Blitzstein and Hwang (2019) Introduction to Probability
  2. Box and Muller (1958) A Note on the Generation of Random Normal Deviates
  3. Rasmussen and Williams (2006) Gaussian Processes for Machine Learning

4.4 Marginalizing #

A Gaussian process describes infinitely many function values, but a computer holds finitely many. For that to make sense, the belief about a few values must not depend on which other values we chose to keep track of. In the terms of Section 2.4, we need the marginal distribution of a sub-vector, which the sum rule obtains by integrating out everything else. For most joint densities that integral is the hard part of a calculation. For a Gaussian it costs nothing.

Split the vector into two blocks: a\mathbf{a}, the coordinates we keep, and b\mathbf{b}, the coordinates we drop. Partition the mean and the covariance to match:

[ab]∼N ⁣([μaμb],  [ΣaaΣabΣab⊤Σbb]).\begin{bmatrix} \mathbf{a} \\ \mathbf{b} \end{bmatrix} \sim \N\!\left( \begin{bmatrix} \vmu_a \\ \vmu_b \end{bmatrix},\; \begin{bmatrix} \mSigma_{aa} & \mSigma_{ab} \\ \mSigma_{ab}^\T & \mSigma_{bb} \end{bmatrix} \right).
(4.12)

The diagonal blocks Σaa\mSigma_{aa} and Σbb\mSigma_{bb} hold the covariances within each block, and Σab\mSigma_{ab} holds the covariances between a coordinate of a\mathbf{a} and a coordinate of b\mathbf{b}. The marginal distribution of a\mathbf{a} is

a∼N(μa,Σaa).\mathbf{a} \sim \N(\vmu_a, \mSigma_{aa}).
(4.13)

Marginalizing a Gaussian is reading off a sub-block. The proof is one line from the previous section: keeping a\mathbf{a} and dropping b\mathbf{b} is the linear map with matrix [I    0][\mI \;\; \mathbf{0}], an identity block beside a block of zeros, and Equation (4.9) gives mean [I    0]μ=μa[\mI \;\; \mathbf{0}]\vmu = \vmu_a and covariance [I    0]Σ[I    0]⊤=Σaa[\mI \;\; \mathbf{0}]\mSigma[\mI \;\; \mathbf{0}]^\T = \mSigma_{aa}. The integral the sum rule calls for has been done once and for all; it can also be carried out directly by completing the square (Bishop, 2006, sec. 2.3.2).

Two consequences matter later. First, marginals are consistent: the distribution of a\mathbf{a} does not depend on how many other coordinates b\mathbf{b} contains, or which. A Gaussian process relies on this to be well defined, since its definition specifies only the joint distributions of finite sets of function values (Section 7.3). Second, the marginal discards the cross-covariances Σab\mSigma_{ab}, and with them everything the two blocks say about each other. In Figure 4.1 the strips above and to the right of the plot are the two marginals, and moving the correlation slider rotates and squeezes the joint density without changing either strip. Many joint distributions share the same marginals.

The marginal of x2x_2 answers the question "what do I believe about x2x_2 if I ignore x1x_1?" The next section answers a different question: "what do I believe about x2x_2 once I know x1x_1?"

Sources cited in Section 4.4 1
  1. Bishop (2006) Pattern Recognition and Machine Learning

4.5 Conditioning #

This is the operation the rest of the book runs on. A Bayesian optimizer has evaluated the objective at a few inputs and wants its belief about the objective everywhere else. If the prior belief about the values at all these inputs is a joint Gaussian, the question becomes: once some coordinates of a Gaussian vector have been observed, what is the distribution of the others? Unlike the marginal, the answer must use what was observed.

4.5.1 A slice through the bell #

Look at two dimensions first. By the product rule, the conditional density of x2x_2 given x1=ax_1 = a is

p(x2 ∣ x1=a)=p(a,x2)p(a).p(x_2 \given x_1 = a) = \frac{p(a, x_2)}{p(a)}.

The numerator is the joint density along the vertical line x1=ax_1 = a: a slice through the bell. The denominator does not depend on x2x_2; it only rescales the slice so that its area is one. So the conditional density has the shape of the slice. Along the slice, the exponent of the joint density is a quadratic function of x2x_2, because fixing one variable of a quadratic in two variables leaves a quadratic in the other. The slice is therefore itself a bell, a Gaussian by Equation (4.2).

Working out that quadratic gives the slice's mean and variance. With the covariance Equation (4.8) and means μ1,μ2\mu_1, \mu_2,

x2 ∣ x1=a  ∼  N ⁣(μ2+ρ σ2σ1(a−μ1),    σ22(1−ρ2)).x_2 \given x_1 = a \;\sim\; \N\!\left(\mu_2 + \rho\,\frac{\sigma_2}{\sigma_1}(a - \mu_1),\;\; \sigma_2^2(1 - \rho^2)\right).
(4.14)

Exercise 4.2 obtains this from the general formula below. Each part has a reading. The observation enters through its z-score (a−μ1)/σ1(a - \mu_1)/\sigma_1. The mean of x2x_2 moves away from μ2\mu_2 by ρ\rho times that many of x2x_2's own standard deviations: a value of x1x_1 one standard deviation above its mean predicts x2x_2 to lie ρ\rho standard deviations above its mean. The variance shrinks by the factor 1−ρ21 - \rho^2, the fraction of x2x_2's variance that x1x_1 does not explain, and it does not depend on aa at all.

−202x1−202x2Observed x1 = 1.50x2 | x1 ~ N(m, s²)m = ρ (σ2/σ1) x1 = 1.05s = σ2 √(1 − ρ²) = 0.71before observing: sd σ2 = 1.00variance removed: ρ² = 49%conditional of x2marginal of x2conditional mean E[x2 | x1]
−202x1−202x2Observed x1 = 1.50x2 | x1 ~ N(m, s²)m = ρ (σ2/σ1) x1 = 1.05s = σ2 √(1 − ρ²) = 0.71before observing: sd σ2 = 1.00variance removed: ρ² = 49%conditional of x2marginal of x2conditional mean E[x2 | x1]
Figure 4.3 Conditioning as slicing, Equation (4.14). The orange line marks the observed value x1x_1; drag across the plot to move it, or use the buttons. The strip on the right compares the marginal density of x2x_2 (blue) with its conditional density given the observation (orange), and the orange bar on the slice marks the conditional mean with its 95% interval. The dashed magenta line traces the conditional mean for every observed value.

Drag the slice from left to right. The conditional density slides along the dashed line but keeps its width. The width depends on the correlation, never on the value observed.

Move ρ\rho toward ±0.95\pm 0.95. The conditional density collapses, and the readout shows the fraction of variance removed, ρ2\rho^2, passing 90%. At ρ=0\rho = 0 nothing is removed and the conditional equals the marginal: an observation uncorrelated with x2x_2 teaches nothing about it.

Compare the dashed line with the ellipses. The line of conditional means is not the long axis of the ellipses; it is flatter. It passes through the leftmost and rightmost points of every ellipse, because along a vertical slice the density is highest where the slice just touches an ellipse.

That flattening has a long history. Francis Galton noticed that the children of unusually tall parents were, on average, less unusual than their parents, and called the effect regression toward mediocrity (Galton, 1886); the statistical term "regression" descends from it. In Equation (4.14) with equal standard deviations, the predicted deviation of x2x_2 is ρ\rho times the observed deviation of x1x_1, closer to the mean whenever ∣ρ∣<1\lvert\rho\rvert < 1. Nothing pulls the children back. The shrinkage is what conditioning a correlated Gaussian does.

4.5.2 The general formula #

The same reasoning works in any number of dimensions, with blocks in place of numbers. Partition the vector into an observed block a\mathbf{a} and an unobserved block b\mathbf{b} as in Equation (4.12). Then

b ∣ a  ∼  N ⁣(μb+Σab⊤Σaa−1(a−μa),    Σbb−Σab⊤Σaa−1Σab).\mathbf{b} \given \mathbf{a} \;\sim\; \N\!\left( \vmu_b + \mSigma_{ab}^\T \mSigma_{aa}^{-1} (\mathbf{a} - \vmu_a),\;\; \mSigma_{bb} - \mSigma_{ab}^\T \mSigma_{aa}^{-1} \mSigma_{ab} \right).
(4.15)

Compare the two-dimensional case. The matrix Σab⊤Σaa−1\mSigma_{ab}^\T\mSigma_{aa}^{-1} plays the role of ρσ2/σ1=Σ12/Σ11\rho\sigma_2/\sigma_1 = \Sigma_{12}/\Sigma_{11}, and the subtracted term Σab⊤Σaa−1Σab\mSigma_{ab}^\T\mSigma_{aa}^{-1}\mSigma_{ab} that of ρ2σ22=Σ122/Σ11\rho^2\sigma_2^2 = \Sigma_{12}^2/\Sigma_{11}.

The dimensions in this formula are easy to misread, so consider a real-sized case. A machine learning model has six hyperparameters to tune, and 40 training runs have finished. In a Bayesian optimizer, a\mathbf{a} holds the 40 observed validation errors and b\mathbf{b} the unknown errors at, say, 1,000 untried configurations, so Σaa\mSigma_{aa} is 40×4040 \times 40 and Σab\mSigma_{ab} is 40×100040 \times 1000. The number six appears nowhere: the Gaussian lives over function values, one coordinate per configuration, and the dimension of the input space enters only through the covariances that a kernel assigns to pairs of configurations (Chapter 9). The cost of conditioning grows with the number of evaluations, not with the number of hyperparameters, though in more dimensions more evaluations are needed to pin the function down (Chapter 30). This is the computation that Snoek et al. (2012) used to tune latent Dirichlet allocation, structured support vector machines, and convolutional networks, reaching or surpassing the settings chosen by human experts; Chapter 22 works through such a tuning problem on real data.

The derivation needs one fact from Section 3.7, restated in the notation of Equation (4.12). The Schur complement of the block Σaa\mSigma_{aa} is

S=Σbb−Σab⊤Σaa−1Σab,\mathbf{S} = \mSigma_{bb} - \mSigma_{ab}^\T \mSigma_{aa}^{-1} \mSigma_{ab},
(4.16)

and the precision matrix Λ=Σ−1\bm{\Lambda} = \mSigma^{-1} has the blocks

[ΛaaΛabΛab⊤Λbb]=[Σaa−1+Σaa−1ΣabS−1Σab⊤Σaa−1−Σaa−1ΣabS−1−S−1Σab⊤Σaa−1S−1].\begin{bmatrix} \bm{\Lambda}_{aa} & \bm{\Lambda}_{ab} \\ \bm{\Lambda}_{ab}^\T & \bm{\Lambda}_{bb} \end{bmatrix} = \begin{bmatrix} \mSigma_{aa}^{-1} + \mSigma_{aa}^{-1}\mSigma_{ab}\mathbf{S}^{-1}\mSigma_{ab}^\T\mSigma_{aa}^{-1} & -\mSigma_{aa}^{-1}\mSigma_{ab}\mathbf{S}^{-1} \\ -\mathbf{S}^{-1}\mSigma_{ab}^\T\mSigma_{aa}^{-1} & \mathbf{S}^{-1} \end{bmatrix}.
(4.17)

Multiplying Σ\mSigma by this matrix gives the identity, block by block, which is how the formula is checked (Petersen and Pedersen, 2012). Only the bottom row is needed: Λbb=S−1\bm{\Lambda}_{bb} = \mathbf{S}^{-1} and Λab⊤=−S−1Σab⊤Σaa−1\bm{\Lambda}_{ab}^\T = -\mathbf{S}^{-1}\mSigma_{ab}^\T\mSigma_{aa}^{-1}.

Derivation Conditioning a Gaussian through the Schur complement
  1. By the product rule, p(b ∣ a)=p(a,b)/p(a)p(\mathbf{b} \given \mathbf{a}) = p(\mathbf{a}, \mathbf{b}) / p(\mathbf{a}). With a\mathbf{a} held fixed, p(a)p(\mathbf{a}) is a constant, so as a function of b\mathbf{b} the conditional is proportional to the joint density Equation (4.5).
  2. Write u=a−μa\mathbf{u} = \mathbf{a} - \vmu_a and v=b−μb\mathbf{v} = \mathbf{b} - \vmu_b. The log of the joint density is −12Q-\tfrac12 Q plus a constant, where Q=(x−μ)⊤Λ(x−μ)Q = (\vx - \vmu)^\T\bm{\Lambda}(\vx - \vmu) with the blocks of Equation (4.17).
  3. Expand QQ block by block: Q=u⊤Λaau+2 v⊤Λab⊤u+v⊤ΛbbvQ = \mathbf{u}^\T\bm{\Lambda}_{aa}\mathbf{u} + 2\,\mathbf{v}^\T\bm{\Lambda}_{ab}^\T\mathbf{u} + \mathbf{v}^\T\bm{\Lambda}_{bb}\mathbf{v}. The two cross terms u⊤Λabv\mathbf{u}^\T\bm{\Lambda}_{ab}\mathbf{v} and v⊤Λab⊤u\mathbf{v}^\T\bm{\Lambda}_{ab}^\T\mathbf{u} are equal, because each is a number and the transpose of the other.
  4. Keep only the terms that involve v\mathbf{v}; the rest are constant given a\mathbf{a}. Then log⁡p(b ∣ a)=−12v⊤Λbbv−v⊤Λab⊤u+const\log p(\mathbf{b} \given \mathbf{a}) = -\tfrac12\mathbf{v}^\T\bm{\Lambda}_{bb}\mathbf{v} - \mathbf{v}^\T\bm{\Lambda}_{ab}^\T\mathbf{u} + \text{const}.
  5. This is the form of Equation (4.6) in the variable v\mathbf{v}, with precision Λbb\bm{\Lambda}_{bb} and h=−Λab⊤u\mathbf{h} = -\bm{\Lambda}_{ab}^\T\mathbf{u}. (Λbb\bm{\Lambda}_{bb} is positive definite, as is every diagonal block of a positive definite matrix.) So v\mathbf{v} given a\mathbf{a} is Gaussian with covariance Λbb−1\bm{\Lambda}_{bb}^{-1} and mean −Λbb−1Λab⊤u-\bm{\Lambda}_{bb}^{-1}\bm{\Lambda}_{ab}^\T\mathbf{u}, and b=μb+v\mathbf{b} = \vmu_b + \mathbf{v} has the same covariance and its mean shifted by μb\vmu_b.
  6. Substitute the bottom row of Equation (4.17). The covariance is Λbb−1=S\bm{\Lambda}_{bb}^{-1} = \mathbf{S}, the Schur complement.
  7. The mean offset is −S (−S−1Σab⊤Σaa−1) u=Σab⊤Σaa−1(a−μa)-\mathbf{S}\,(-\mathbf{S}^{-1}\mSigma_{ab}^\T\mSigma_{aa}^{-1})\,\mathbf{u} = \mSigma_{ab}^\T\mSigma_{aa}^{-1}(\mathbf{a} - \vmu_a).
  8. Together: b ∣ a\mathbf{b} \given \mathbf{a} is Gaussian with mean μb+Σab⊤Σaa−1(a−μa)\vmu_b + \mSigma_{ab}^\T\mSigma_{aa}^{-1}(\mathbf{a} - \vmu_a) and covariance Σbb−Σab⊤Σaa−1Σab\mSigma_{bb} - \mSigma_{ab}^\T\mSigma_{aa}^{-1}\mSigma_{ab}, which is Equation (4.15).

The derivation follows section 2.3.1 of Bishop (2006), and Section B.3 collects the result with related identities. Two remarks follow from it. The conditional covariance is the Schur complement Equation (4.16) itself. And step 5 shows that the conditional precision is the block Λbb\bm{\Lambda}_{bb} of the joint precision: conditioning reads off a block of the precision matrix, just as marginalizing reads off a block of the covariance matrix.

Key idea Conditioning a Gaussian

Observing part of a Gaussian vector leaves a Gaussian. The mean of the rest shifts by a linear function of how far the observation fell from its expectation, and the covariance shrinks by an amount that depends on which coordinates were observed but not on the values observed.

The second half of the key idea is the reason a Gaussian process's uncertainty depends on where we evaluated and not on what we found (Section 8.1). A second derivation makes the Schur complement less mysterious.

A small numerical case shows the whole of Gaussian process regression in miniature.

Example 4.3 A Gaussian process in miniature

Two inputs x\vx and x′\vx' lie close together. A prior says the objective values f(x)f(\vx) and f(x′)f(\vx') are each N(0,1)\N(0, 1) with correlation 0.8, the kind of value a smooth kernel assigns to nearby inputs (Section 7.2). We evaluate f(x)=1.2f(\vx) = 1.2. By Equation (4.14) with σ1=σ2=1\sigma_1 = \sigma_2 = 1 and ρ=0.8\rho = 0.8,

f(x′) ∣ f(x)=1.2  ∼  N(0.8×1.2,  1−0.82)=N(0.96,  0.36).f(\vx') \given f(\vx) = 1.2 \;\sim\; \N(0.8 \times 1.2,\; 1 - 0.8^2) = \N(0.96,\; 0.36).

The belief about the unevaluated input moved 80% of the way toward the observation, and its standard deviation fell from 1 to 0.6. Had we observed −1.2-1.2, the mean would have moved to −0.96-0.96, and the standard deviation would again have been 0.6. Section 8.1 does the same with a kernel supplying the correlations, for every unevaluated input at once.

4.5.3 Computing it #

In code, Equation (4.15) is evaluated with the Cholesky factor of Σaa\mSigma_{aa} and triangular solves, never with an explicit inverse (Section 3.5). With LL⊤=Σaa\mL\mL^\T = \mSigma_{aa}, set V=L−1Σab\mathbf{V} = \mL^{-1}\mSigma_{ab} and w=L−1(a−μa)\vw = \mL^{-1}(\mathbf{a} - \vmu_a). Since Σaa−1=L−⊤L−1\mSigma_{aa}^{-1} = \mL^{-\T}\mL^{-1}, the mean offset is V⊤w\mathbf{V}^\T\vw and the subtracted covariance is V⊤V\mathbf{V}^\T\mathbf{V}.

In code NumPy
import numpy as np

def condition(mu, Sigma, ia, ib, a):
    """Mean and covariance of x[ib] given x[ia] = a, for x ~ N(mu, Sigma)."""
    Saa = Sigma[np.ix_(ia, ia)]
    Sab = Sigma[np.ix_(ia, ib)]
    Sbb = Sigma[np.ix_(ib, ib)]
    L = np.linalg.cholesky(Saa)
    V = np.linalg.solve(L, Sab)          # L^{-1} Sigma_ab
    w = np.linalg.solve(L, a - mu[ia])   # L^{-1} (a - mu_a)
    return mu[ib] + V.T @ w, Sbb - V.T @ V

With a zero mean and a kernel matrix as Sigma, this function is the Gaussian process predictor of Algorithm 8.1 under different names.

When the observed coordinates nearly determine the others, the subtraction Σbb−V⊤V\mSigma_{bb} - \mathbf{V}^\T\mathbf{V} cancels most of its digits, and the result can come out slightly asymmetric or with tiny negative eigenvalues. Symmetrizing it and adding a small jitter before factorizing it again, for example to draw samples, repairs the damage.

Sources cited in Section 4.5 4
  1. Galton (1886) Regression Towards Mediocrity in Hereditary Stature
  2. Snoek et al. (2012) Practical Bayesian Optimization of Machine Learning Algorithms
  3. Petersen and Pedersen (2012) The Matrix Cookbook
  4. Bishop (2006) Pattern Recognition and Machine Learning

4.6 Sums and products #

Two more operations combine Gaussians, and they are easy to confuse because both take two Gaussians and return one. Adding two independent Gaussian random variables describes a quantity built from two uncertain parts, such as a function value plus measurement noise. Multiplying two Gaussian densities describes two independent pieces of evidence about one quantity, which is what Bayes' rule does with a Gaussian prior and a Gaussian likelihood. The first operation makes the uncertainty larger; the second makes it smaller.

4.6.1 Sums of independent Gaussians #

If X∼N(μ1,σ12)X \sim \N(\mu_1, \sigma_1^2) and Y∼N(μ2,σ22)Y \sim \N(\mu_2, \sigma_2^2) are independent, the pair (X,Y)(X, Y) is jointly Gaussian with a diagonal covariance, and X+YX + Y is the linear map with the single row (1,1)(1, 1). By Equation (4.9),

X+Y∼N ⁣(μ1+μ2,  σ12+σ22).X + Y \sim \N\!\left(\mu_1 + \mu_2,\; \sigma_1^2 + \sigma_2^2\right).
(4.18)

Variances add; standard deviations do not. Two independent errors with standard deviations 3 and 4 add up to an error with standard deviation 5, not 7. If XX and YY are correlated, the same map gives the variance σ12+σ22+2Cov⁡[X,Y]\sigma_1^2 + \sigma_2^2 + 2\Cov[X, Y]. Two uses recur in the book. An observation y=f(x)+εy = f(\vx) + \varepsilon with independent noise ε∼N(0,σn2)\varepsilon \sim \N(0, \sigma_n^2) has variance Var⁡[f(x)]+σn2\Var[f(\vx)] + \sigma_n^2, the predictive variance of Section 8.3. And the average of nn independent measurements, each with variance σ2\sigma^2, has variance σ2/n\sigma^2/n, so its standard deviation falls like 1/n1/\sqrt{n}.

4.6.2 Products of Gaussian densities #

Now take two Gaussian densities over the same variable xx and multiply them pointwise. The result is not normalized, but its shape is Gaussian: the sum of two quadratic exponents is quadratic.

Derivation The product of two Gaussian densities

Take the densities N(x; μ1,σ12)\N(x;\, \mu_1, \sigma_1^2) and N(x; μ2,σ22)\N(x;\, \mu_2, \sigma_2^2).

  1. Multiplying exponentials adds the exponents: −12[(x−μ1)2/σ12+(x−μ2)2/σ22]-\tfrac12\left[(x - \mu_1)^2/\sigma_1^2 + (x - \mu_2)^2/\sigma_2^2\right].
  2. Collect powers of xx: the coefficient of −12x2-\tfrac12 x^2 is 1/σ12+1/σ221/\sigma_1^2 + 1/\sigma_2^2, and the coefficient of xx is μ1/σ12+μ2/σ22\mu_1/\sigma_1^2 + \mu_2/\sigma_2^2.
  3. By Equation (4.2), the product is proportional to a Gaussian density with precision 1/σ2=1/σ12+1/σ221/\sigma^2 = 1/\sigma_1^2 + 1/\sigma_2^2 and mean μ=σ2(μ1/σ12+μ2/σ22)\mu = \sigma^2\left(\mu_1/\sigma_1^2 + \mu_2/\sigma_2^2\right).
  4. The terms that do not involve xx are −12[μ12/σ12+μ22/σ22−μ2/σ2]-\tfrac12\left[\mu_1^2/\sigma_1^2 + \mu_2^2/\sigma_2^2 - \mu^2/\sigma^2\right]. Over a common denominator the bracket simplifies to (μ1−μ2)2/(σ12+σ22)(\mu_1 - \mu_2)^2/(\sigma_1^2 + \sigma_2^2).
  5. The normalizing factors multiply to 1/(2πσ1σ2)1/(2\pi\sigma_1\sigma_2). Since σ2(σ12+σ22)=σ12σ22\sigma^2(\sigma_1^2 + \sigma_2^2) = \sigma_1^2\sigma_2^2, this equals [1/2πσ2][1/2π(σ12+σ22)]\big[1/\sqrt{2\pi\sigma^2}\big]\big[1/\sqrt{2\pi(\sigma_1^2 + \sigma_2^2)}\big].
  6. Collecting the factors: N(x; μ1,σ12) N(x; μ2,σ22)=N(μ1; μ2,σ12+σ22)  N(x; μ,σ2)\N(x;\, \mu_1, \sigma_1^2)\,\N(x;\, \mu_2, \sigma_2^2) = \N(\mu_1;\, \mu_2, \sigma_1^2 + \sigma_2^2)\;\N(x;\, \mu, \sigma^2).

In dd dimensions the same steps, with Equation (4.6) in place of Equation (4.2), give

N(x; μ1,Σ1) N(x; μ2,Σ2)=Z  N(x; μ,Σ),Σ=(Σ1−1+Σ2−1)−1,    μ=Σ(Σ1−1μ1+Σ2−1μ2),\N(\vx;\, \vmu_1, \mSigma_1)\,\N(\vx;\, \vmu_2, \mSigma_2) = Z\;\N(\vx;\, \vmu, \mSigma), \qquad \mSigma = \left(\mSigma_1^{-1} + \mSigma_2^{-1}\right)^{-1},\;\; \vmu = \mSigma\left(\mSigma_1^{-1}\vmu_1 + \mSigma_2^{-1}\vmu_2\right),
(4.19)

with the constant Z=N(μ1; μ2, Σ1+Σ2)Z = \N(\vmu_1;\, \vmu_2,\, \mSigma_1 + \mSigma_2) (Rasmussen and Williams, 2006, app. A.2).

Read the result in terms of precision. The precisions add, so the product is narrower than either factor. The mean is a weighted average of the two means, with weights proportional to the precisions, so the sharper density pulls harder. The constant ZZ is the area under the raw product. It is large when the two densities agree and tiny when they put their mass in different places.

This is Bayes' rule for a Gaussian prior and a Gaussian measurement. Suppose a prior belief about a quantity θ\theta is N(μ0,σ02)\N(\mu_0, \sigma_0^2), and we observe y=θ+εy = \theta + \varepsilon with noise ε∼N(0,σn2)\varepsilon \sim \N(0, \sigma_n^2). As a function of θ\theta, the likelihood N(y; θ,σn2)\N(y;\, \theta, \sigma_n^2) is the density N(θ; y,σn2)\N(\theta;\, y, \sigma_n^2), since the formula is symmetric in yy and θ\theta. The posterior is proportional to prior times likelihood, so it is Gaussian with precision 1/σ02+1/σn21/\sigma_0^2 + 1/\sigma_n^2 and a mean between the prior mean and the observation. The constant Z=N(y; μ0,σ02+σn2)Z = \N(y;\, \mu_0, \sigma_0^2 + \sigma_n^2) is the density of the observation under the prior, which Section 5.6 calls the model evidence. Notice that it is the distribution of the sum θ+ε\theta + \varepsilon from Equation (4.18): the two operations of this section meet. Section 5.1 develops this view, and Section 5.4 extends it from one number to a vector of weights.

p(x) = N(x; μ1, σ1²)q(x) = N(x; μ2, σ2²)normalized productraw product p(x) q(x)0.00.20.40.60.8density−6−4−20246xprecision 1/σ² = 1/σ1² + 1/σ2² = 3.47, sd 0.54mean = 0.20 μ1 + 0.80 μ2 = 1.00 (weights ∝ precision)area of the raw product Z = N(μ1; μ2, σ1² + σ2²) = 0.052
p(x) = N(x; μ1, σ1²)q(x) = N(x; μ2, σ2²)normalized productraw product p(x) q(x)0.00.20.40.60.8density−6−4−20246xprecision 1/σ² = 1/σ1² + 1/σ2² = 3.47, sd 0.54mean = 0.20 μ1 + 0.80 μ2 = 1.00 (weights ∝ precision)area of the raw product Z = N(μ1; μ2, σ1² + σ2²) = 0.052
Figure 4.4 Two ways to combine two Gaussians. Sum of variables shows the density of X+YX + Y for independent XX and YY, Equation (4.18): wider than both inputs. Product of densities shows the normalized pointwise product of the two density curves, Equation (4.19): narrower than both, with its mean pulled toward the sharper input. The dashed curve is the raw product, whose area is ZZ. Set the means and standard deviations with the sliders, or drag near a peak to move it.

Switch between the two operations with the same inputs. The sum is centered at μ1+μ2\mu_1 + \mu_2 and is wider than either input. The product lies between μ1\mu_1 and μ2\mu_2 and is narrower than either.

In the product, make one input very wide. With σ1\sigma_1 at 2.5 the product nearly coincides with the second input. A vague prior hardly changes what a precise measurement says.

Pull the two means apart. The normalized product keeps its width, because the precisions do not depend on the means, but the raw product sinks toward zero, and ZZ with it. Two confident densities that disagree produce a confident compromise in a region where neither puts much mass. A small ZZ is the warning sign that the prior and the measurement are in conflict.

Pitfall The product of two Gaussian variables is not Gaussian

Equation (4.19) multiplies density functions. Multiplying two Gaussian random variables is a different operation with a different answer: if XX and YY are independent standard normals, their product XYXY has a density that grows without bound near zero and has heavier tails than any Gaussian. Gaussian random variables are closed under addition and linear maps; Gaussian densities are closed under multiplication. Keep the two apart when reading a derivation.

Sources cited in Section 4.6 1
  1. Rasmussen and Williams (2006) Gaussian Processes for Machine Learning

4.7 Working with Gaussians in code #

Three habits avoid most numerical trouble.

Work with log densities. In many dimensions the density Equation (4.5) is a product of many small factors and underflows. For a standard Gaussian in d=1000d = 1000 dimensions, even the density at the mean, (2π)−500(2\pi)^{-500}, is about 10−39910^{-399}, below the smallest positive double-precision number. The log density is a sum of moderate numbers. Compute it from the Cholesky factor L\mL of Σ\mSigma: with w=L−1(x−μ)\vw = \mL^{-1}(\vx - \vmu) the quadratic form is w⊤w\vw^\T\vw, and log⁡∣Σ∣=2∑ilog⁡Lii\log\lvert\mSigma\rvert = 2\sum_i \log L_{ii} (Section 3.6).

In code NumPy
import numpy as np

def gaussian_logpdf(x, mu, Sigma):
    L = np.linalg.cholesky(Sigma)
    w = np.linalg.solve(L, x - mu)       # L^{-1} (x - mu)
    d = len(mu)
    return -0.5 * w @ w - np.log(np.diag(L)).sum() - 0.5 * d * np.log(2 * np.pi)

Never form Σ−1\mSigma^{-1}. Every formula in this chapter that contains an inverse is evaluated with a Cholesky factorization and triangular solves, as in the conditioning code above, for the reasons of Section 3.5.1.

Check the parameterization. The notation N(μ,σ2)\N(\mu, \sigma^2) puts the variance second, but most libraries take the standard deviation: NumPy's random.normal(loc, scale), SciPy's stats.norm(loc, scale), and PyTorch's Normal(loc, scale) all expect σ\sigma. Passing a variance where a standard deviation is expected is a silent and common bug. Multivariate versions take the covariance matrix, or sometimes its Cholesky factor, as in PyTorch's MultivariateNormal(loc, scale_tril=L).

4.8 Exercises #

Exercise 4.1

The values f(x1)f(\vx_1) and f(x2)f(\vx_2) are jointly Gaussian with means 0.3 and 0.1, standard deviations 0.2 each, and correlation 0.75. Compute the probability that f(x1)>f(x2)f(\vx_1) > f(\vx_2). Repeat with correlation 0 and explain the difference.

Solution

By Example 4.2, D=f(x1)−f(x2)D = f(\vx_1) - f(\vx_2) has mean 0.20.2 and variance 0.04+0.04−2×0.75×0.04=0.020.04 + 0.04 - 2 \times 0.75 \times 0.04 = 0.02, so its standard deviation is 0.1410.141 and P(D>0)=Φ(0.2/0.141)=Φ(1.41)≈0.92\Prob(D > 0) = \Phi(0.2/0.141) = \Phi(1.41) \approx 0.92. With correlation 0 the variance is 0.080.08, the standard deviation 0.2830.283, and the probability Φ(0.71)≈0.76\Phi(0.71) \approx 0.76. Positive correlation means the two values tend to err in the same direction, so the errors partly cancel in the difference, and the ordering is more certain than either value.

Exercise 4.2

Derive Equation (4.14) from Equation (4.15). Then show that, in general, observing a\mathbf{a} never increases the variance of any linear combination w⊤b\vw^\T\mathbf{b}.

Solution

Take a=x1\mathbf{a} = x_1 and b=x2\mathbf{b} = x_2, so Σaa=σ12\mSigma_{aa} = \sigma_1^2, Σab=ρσ1σ2\mSigma_{ab} = \rho\sigma_1\sigma_2, and Σbb=σ22\mSigma_{bb} = \sigma_2^2. The mean is μ2+(ρσ1σ2/σ12)(a−μ1)=μ2+ρ(σ2/σ1)(a−μ1)\mu_2 + (\rho\sigma_1\sigma_2/\sigma_1^2)(a - \mu_1) = \mu_2 + \rho(\sigma_2/\sigma_1)(a - \mu_1), and the variance is σ22−ρ2σ12σ22/σ12=σ22(1−ρ2)\sigma_2^2 - \rho^2\sigma_1^2\sigma_2^2/\sigma_1^2 = \sigma_2^2(1 - \rho^2). In general, the variance of w⊤b\vw^\T\mathbf{b} falls from w⊤Σbbw\vw^\T\mSigma_{bb}\vw to w⊤Σbbw−w⊤Σab⊤Σaa−1Σabw\vw^\T\mSigma_{bb}\vw - \vw^\T\mSigma_{ab}^\T\mSigma_{aa}^{-1}\mSigma_{ab}\vw. With q=Σabw\mathbf{q} = \mSigma_{ab}\vw, the subtracted amount is q⊤Σaa−1q≥0\mathbf{q}^\T\mSigma_{aa}^{-1}\mathbf{q} \ge 0, because the inverse of a positive definite matrix is positive definite. The decrease is zero exactly when q=0\mathbf{q} = \mathbf{0}, that is, when w⊤b\vw^\T\mathbf{b} is uncorrelated with every observed coordinate.

Exercise 4.3

Let X∼N(0,1)X \sim \N(0, 1), and let SS be independent of XX and equal to +1+1 or −1-1 with probability one half each. Set Y=SXY = SX. Show that YY is standard normal and that XX and YY are uncorrelated, but that they are not independent and not jointly Gaussian.

Solution

Because N(0,1)\N(0, 1) is symmetric, −X-X has the same distribution as XX, so P(Y≤y)=12P(X≤y)+12P(−X≤y)=Φ(y)\Prob(Y \le y) = \tfrac12\Prob(X \le y) + \tfrac12\Prob(-X \le y) = \Phi(y). The covariance is E[XY]=E[S] E[X2]=0×1=0\E[XY] = \E[S]\,\E[X^2] = 0 \times 1 = 0. They are dependent, because ∣Y∣=∣X∣\lvert Y\rvert = \lvert X\rvert: knowing XX leaves only two possible values for YY. They are not jointly Gaussian, because the linear combination X+Y=(1+S)XX + Y = (1 + S)X equals zero with probability one half and is otherwise N(0,4)\N(0, 4); a linear combination of jointly Gaussian variables would be Gaussian (Section 4.3). Uncorrelated implies independent only for jointly Gaussian variables.

Exercise 4.4

A quantity θ\theta has prior N(0,σ02)\N(0, \sigma_0^2) and is measured nn times, yi=θ+εiy_i = \theta + \varepsilon_i, with independent noise εi∼N(0,σn2)\varepsilon_i \sim \N(0, \sigma_n^2). Use Equation (4.19) to find the posterior of θ\theta. What happens as σ0→∞\sigma_0 \to \infty? What is the posterior variance for σ0=1\sigma_0 = 1?

Solution

Each measurement contributes a likelihood factor N(θ; yi,σn2)\N(\theta;\, y_i, \sigma_n^2). Multiplying the prior by the nn factors one at a time, the precisions add: the posterior precision is 1/σ02+n/σn21/\sigma_0^2 + n/\sigma_n^2, and the posterior mean is (∑iyi/σn2)/(1/σ02+n/σn2)\left(\sum_i y_i/\sigma_n^2\right)\big/\left(1/\sigma_0^2 + n/\sigma_n^2\right). As σ0→∞\sigma_0 \to \infty the prior's precision vanishes, the mean tends to the sample average yˉ\bar{y}, and the variance to σn2/n\sigma_n^2/n, the familiar standard error of an average. For σ0=1\sigma_0 = 1 the variance is 1/(1+n/σn2)=σn2/(n+σn2)1/(1 + n/\sigma_n^2) = \sigma_n^2/(n + \sigma_n^2). The same number returns in Exercise 8.2, where a Gaussian process is evaluated nn times at one input.

Further reading #

  • Bishop (2006), section 2.3, derives the conditional and marginal distributions of a partitioned Gaussian by completing the square, the route taken here, and continues to the linear Gaussian models of Chapter 5.
  • Rasmussen and Williams (2006), appendix A, collects the Gaussian and matrix identities that Gaussian processes need, including products of Gaussian densities and sampling with the Cholesky factor.
  • Murphy (2022), chapter 3, treats the multivariate Gaussian and linear Gaussian systems with many worked examples.
  • Blitzstein and Hwang (2019) is a gentle probability text whose treatment of the multivariate normal defines it through linear combinations, the definition used in Section 4.3.
  • Petersen and Pedersen (2012) lists the block-inverse and Gaussian identities in a compact reference form.
  • Galton (1886) is the paper that named regression toward the mean, the effect the conditioning figure shows.

References

  1. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. Cited in §4.4 §4.5
  2. Blitzstein, J. K., and Hwang, J. (2019). Introduction to Probability. Chapman and Hall/CRC. Cited in §4.1 §4.3
  3. Box, G. E. P., and Muller, M. E. (1958). A Note on the Generation of Random Normal Deviates. The Annals of Mathematical Statistics. Cited in §4.3
  4. Cover, T. M., and Thomas, J. A. (2006). Elements of Information Theory. Wiley. Cited in §4.1
  5. Galton, F. (1886). Regression Towards Mediocrity in Hereditary Stature. The Journal of the Anthropological Institute of Great Britain and Ireland. Cited in §4.5
  6. Murphy, K. P. (2022). Probabilistic Machine Learning: An Introduction. MIT Press.
  7. Petersen, K. B., and Pedersen, M. S. (2012). The Matrix Cookbook. Technical University of Denmark. non-peer-reviewed Cited in §4.5
  8. Rasmussen, C. E., and Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press. Cited in §4.3 §4.6
  9. Snoek, J., Larochelle, H., and Adams, R. P. (2012). Practical Bayesian Optimization of Machine Learning Algorithms. Advances in Neural Information Processing Systems 25 (NeurIPS 2012). Cited in §4.5