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 is Gaussian with mean and variance , written , when its density is
The semicolon separates the point where the density is evaluated from the parameters and . 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 is a downward parabola with its peak at . 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:
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 , opening downward, is Gaussian, and its parameters can be read off the coefficients. If
To see it, complete the square: , and the last term is a constant that the normalization absorbs. The coefficient , 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, , and the variance is the expected squared deviation, (Section 2.6). The standard deviation , the square root of the variance, is in the units of , so it is the number to think with. The accuracy belief above is about : 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 . If , then is standard normal, and conversely . The value , the number of standard deviations by which lies above the mean, is called its z-score. The standard normal has its own symbols, used throughout the book:
The function is the density and the cumulative distribution function: is the probability that . There is no formula for in elementary functions. Libraries compute it through the error function, , to full floating-point precision.
Standardizing turns every probability question about into one about :
A few values are worth remembering. The interval holds 68.3% of the probability, holds 95%, holds 95.4%, and holds 99.7%. The tails fall off fast: a value more than five standard deviations from the mean, in either direction, has probability about .
Keep the belief about the accuracy 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
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 and 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 , minus 6, has mean 0 and variance 1, and its histogram is already hard to tell from .
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 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
- Blitzstein and Hwang (2019) Introduction to Probability
- 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 and are independent, their joint density is the product of the two densities (Section 2.7), and multiplying exponentials adds the exponents:
The density is constant wherever the exponent is, on the curves . These are ellipses with axes along the coordinate directions, and circles when . To link the two coordinates, we allow the quadratic in the exponent a cross term . The ellipses then tilt, so that a large makes a large 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 of Section 2.6.3. For a random vector with mean vector , its entries are , 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 .
A random vector has a Gaussian distribution with mean and positive definite covariance matrix , written , when its density is
where is the determinant of .
Every piece has a one-dimensional counterpart. With and the formula is Equation (4.1). The exponent is again a quadratic, now a quadratic form in the vector , with the inverse covariance in the role of . 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 : 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
for a positive definite matrix and a vector , then is Gaussian with precision , that is,
Completing the square works as before, and expanding the right side checks it:
The last term does not depend on .
4.2.1 Shape #
The quantity in the exponent has a name. The Mahalanobis distance of from is
the multivariate z-score. In one dimension it is , 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 only through , so its contours are the sets where is constant: ellipses in two dimensions, ellipsoids in more.
Where do the ellipses point? Write the covariance in its eigendecomposition , with orthonormal eigenvectors in the columns of and eigenvalues on the diagonal of (Section 3.4). In the rotated coordinates the quadratic form becomes , with no cross terms. The axes of every contour therefore point along the eigenvectors, and the ellipse at Mahalanobis distance has semi-axes of length . The eigenvalues are the variances along the principal directions, and their product is . 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 and correlation , the covariance matrix and its determinant are
The figure below draws this case with mean zero.
Set 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 toward 0.95. The ellipses narrow into a needle along the diagonal. With both standard deviations at 1 the eigenvalues are and , so the first approaches 2 while the second and the determinant approach zero: the distribution concentrates near a line, and once is known, is nearly determined. At 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 negative. The ellipses tilt the other way: a large now goes with a small .
Watch the two strips while you move . 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 is : 39% inside , 86% inside , and 99% inside . Enclosing 95% takes , not 1.96. The gap widens with the dimension.
One more property is special to Gaussians. When 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 and 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 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 in dimensions, let be an matrix, and let be a vector in . Then
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 is positive definite only when no row of is a combination of the others. When it is not, as when has more rows than columns, 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 . The formulas for its mean and covariance hold in both cases.
- By linearity of expectation (Section 2.6), .
- Subtracting the mean, .
- By the definition of the covariance matrix, .
- is constant, so it moves outside the expectation: .
- That is Gaussian, and not merely some distribution with this mean and covariance, needs one more argument. When is square and invertible, substituting into Equation (4.5) leaves an exponent that is a quadratic function of , so is Gaussian by Equation (4.6).
- For a general , 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 is a linear combination of the coordinates of , so it is Gaussian, and so is .
4.3.1 Sampling with the Cholesky factor #
Sampling runs the map in the useful direction. Let be a vector of 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 with and set
By Equation (4.9), is Gaussian with mean and covariance . The Cholesky factor of Section 3.5, lower triangular with a positive diagonal, is the usual choice of : it exists for every positive definite , it costs 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 from the eigendecomposition. It would map a given 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 shows how each coordinate is built:
Multiplying out confirms . The formula also says what correlation is, mechanically. The coordinate is built partly from the same random number that drives and partly from fresh randomness ; a fraction of its variance comes from the shared part. At the two coordinates share nothing, and at they share everything.
Follow the arrows. Every gray point is moved by the same matrix. Because is lower triangular, depends on alone; with the map leaves the first coordinate unchanged and every arrow is vertical. With a positive , the map adds to the second coordinate, which pushes points on the left down and points on the right up, and it shrinks by the factor . The round cloud becomes a tilted ellipse.
Compare the sample correlation with . The readout computes the correlation of the blue points. It differs from by a few hundredths, and a fresh set of samples gives a different error: sampling noise, with a standard deviation of roughly for points.
Set to zero with unequal standard deviations. is then diagonal and only stretches the cloud along the axes.
For a Gaussian process, 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.
Let and be jointly Gaussian with means , variances , and covariance . The difference is the map with the single row , so by Equation (4.9) it is Gaussian with mean and variance
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
- Blitzstein and Hwang (2019) Introduction to Probability
- Box and Muller (1958) A Note on the Generation of Random Normal Deviates
- 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: , the coordinates we keep, and , the coordinates we drop. Partition the mean and the covariance to match:
The diagonal blocks and hold the covariances within each block, and holds the covariances between a coordinate of and a coordinate of . The marginal distribution of is
Marginalizing a Gaussian is reading off a sub-block. The proof is one line from the previous section: keeping and dropping is the linear map with matrix , an identity block beside a block of zeros, and Equation (4.9) gives mean and covariance . 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 does not depend on how many other coordinates 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 , 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 answers the question "what do I believe about if I ignore ?" The next section answers a different question: "what do I believe about once I know ?"
Sources cited in Section 4.4 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 given is
The numerator is the joint density along the vertical line : a slice through the bell. The denominator does not depend on ; 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 , 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 ,
Exercise 4.2 obtains this from the general formula below. Each part has a reading. The observation enters through its z-score . The mean of moves away from by times that many of 's own standard deviations: a value of one standard deviation above its mean predicts to lie standard deviations above its mean. The variance shrinks by the factor , the fraction of 's variance that does not explain, and it does not depend on at all.
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 toward . The conditional density collapses, and the readout shows the fraction of variance removed, , passing 90%. At nothing is removed and the conditional equals the marginal: an observation uncorrelated with 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 is times the observed deviation of , closer to the mean whenever . 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 and an unobserved block as in Equation (4.12). Then
Compare the two-dimensional case. The matrix plays the role of , and the subtracted term that of .
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, holds the 40 observed validation errors and the unknown errors at, say, 1,000 untried configurations, so is and is . 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 is
and the precision matrix has the blocks
Multiplying 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: and .
- By the product rule, . With held fixed, is a constant, so as a function of the conditional is proportional to the joint density Equation (4.5).
- Write and . The log of the joint density is plus a constant, where with the blocks of Equation (4.17).
- Expand block by block: . The two cross terms and are equal, because each is a number and the transpose of the other.
- Keep only the terms that involve ; the rest are constant given . Then .
- This is the form of Equation (4.6) in the variable , with precision and . ( is positive definite, as is every diagonal block of a positive definite matrix.) So given is Gaussian with covariance and mean , and has the same covariance and its mean shifted by .
- Substitute the bottom row of Equation (4.17). The covariance is , the Schur complement.
- The mean offset is .
- Together: is Gaussian with mean and covariance , 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 of the joint precision: conditioning reads off a block of the precision matrix, just as marginalizing reads off a block of the covariance matrix.
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.
Two inputs and lie close together. A prior says the objective values and are each with correlation 0.8, the kind of value a smooth kernel assigns to nearby inputs (Section 7.2). We evaluate . By Equation (4.14) with and ,
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 , the mean would have moved to , 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 and triangular solves, never with an explicit inverse (Section 3.5). With , set and . Since , the mean offset is and the subtracted covariance is .
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 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
- Galton (1886) Regression Towards Mediocrity in Hereditary Stature
- Snoek et al. (2012) Practical Bayesian Optimization of Machine Learning Algorithms
- Petersen and Pedersen (2012) The Matrix Cookbook
- 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 and are independent, the pair is jointly Gaussian with a diagonal covariance, and is the linear map with the single row . By Equation (4.9),
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 and are correlated, the same map gives the variance . Two uses recur in the book. An observation with independent noise has variance , the predictive variance of Section 8.3. And the average of independent measurements, each with variance , has variance , so its standard deviation falls like .
4.6.2 Products of Gaussian densities #
Now take two Gaussian densities over the same variable and multiply them pointwise. The result is not normalized, but its shape is Gaussian: the sum of two quadratic exponents is quadratic.
Take the densities and .
- Multiplying exponentials adds the exponents: .
- Collect powers of : the coefficient of is , and the coefficient of is .
- By Equation (4.2), the product is proportional to a Gaussian density with precision and mean .
- The terms that do not involve are . Over a common denominator the bracket simplifies to .
- The normalizing factors multiply to . Since , this equals .
- Collecting the factors: .
In dimensions the same steps, with Equation (4.6) in place of Equation (4.2), give
with the constant (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 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 is , and we observe with noise . As a function of , the likelihood is the density , since the formula is symmetric in and . The posterior is proportional to prior times likelihood, so it is Gaussian with precision and a mean between the prior mean and the observation. The constant 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 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.
Switch between the two operations with the same inputs. The sum is centered at and is wider than either input. The product lies between and and is narrower than either.
In the product, make one input very wide. With 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 with it. Two confident densities that disagree produce a confident compromise in a region where neither puts much mass. A small is the warning sign that the prior and the measurement are in conflict.
Equation (4.19) multiplies density functions. Multiplying two Gaussian random variables is a different operation with a different answer: if and are independent standard normals, their product 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
- 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 dimensions, even the density at the mean, , is about , below the smallest positive double-precision number. The log density is a sum of moderate numbers. Compute it from the Cholesky factor of : with the quadratic form is , and (Section 3.6).
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 . 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 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 . 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 #
The values and are jointly Gaussian with means 0.3 and 0.1, standard deviations 0.2 each, and correlation 0.75. Compute the probability that . Repeat with correlation 0 and explain the difference.
Solution
By Example 4.2, has mean and variance , so its standard deviation is and . With correlation 0 the variance is , the standard deviation , and the probability . 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.
Derive Equation (4.14) from Equation (4.15). Then show that, in general, observing never increases the variance of any linear combination .
Solution
Take and , so , , and . The mean is , and the variance is . In general, the variance of falls from to . With , the subtracted amount is , because the inverse of a positive definite matrix is positive definite. The decrease is zero exactly when , that is, when is uncorrelated with every observed coordinate.
Let , and let be independent of and equal to or with probability one half each. Set . Show that is standard normal and that and are uncorrelated, but that they are not independent and not jointly Gaussian.
Solution
Because is symmetric, has the same distribution as , so . The covariance is . They are dependent, because : knowing leaves only two possible values for . They are not jointly Gaussian, because the linear combination equals zero with probability one half and is otherwise ; a linear combination of jointly Gaussian variables would be Gaussian (Section 4.3). Uncorrelated implies independent only for jointly Gaussian variables.
A quantity has prior and is measured times, , with independent noise . Use Equation (4.19) to find the posterior of . What happens as ? What is the posterior variance for ?
Solution
Each measurement contributes a likelihood factor . Multiplying the prior by the factors one at a time, the precisions add: the posterior precision is , and the posterior mean is . As the prior's precision vanishes, the mean tends to the sample average , and the variance to , the familiar standard error of an average. For the variance is . The same number returns in Exercise 8.2, where a Gaussian process is evaluated 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
- (2006). Pattern Recognition and Machine Learning. Springer. Cited in §4.4 §4.5
- (2019). Introduction to Probability. Chapman and Hall/CRC. Cited in §4.1 §4.3
- (1958). A Note on the Generation of Random Normal Deviates. The Annals of Mathematical Statistics. Cited in §4.3
- (2006). Elements of Information Theory. Wiley. Cited in §4.1
- (1886). Regression Towards Mediocrity in Hereditary Stature. The Journal of the Anthropological Institute of Great Britain and Ireland. Cited in §4.5
- (2022). Probabilistic Machine Learning: An Introduction. MIT Press.
- (2012). The Matrix Cookbook. Technical University of Denmark. non-peer-reviewed Cited in §4.5
- (2006). Gaussian Processes for Machine Learning. MIT Press. Cited in §4.3 §4.6
- (2012). Practical Bayesian Optimization of Machine Learning Algorithms. Advances in Neural Information Processing Systems 25 (NeurIPS 2012). Cited in §4.5