10 / 22 · Several Random Variables
The multivariate Gaussian
The joint distribution described completely by a mean vector and a covariance matrix: the density and the Mahalanobis distance, the covariance matrix as an ellipse through its eigenvectors, affine maps, marginals and conditionals in closed form (the conditional mean is a linear regression), uncorrelated meaning independent only for jointly Gaussian vectors, and the thin shell where high-dimensional Gaussian samples live.
On this page 12
A joint distribution of variables is in general a function of arguments that no table can hold. One family is different. It is described completely by a mean vector and a covariance matrix, it stays in the family under linear maps, marginalization and conditioning, and all of these are a few lines of linear algebra. That family, the multivariate Gaussian, is the noise model of linear regression, the prior of Gaussian processes, the state of a Kalman filter and the latent space of most generative models. This note builds it from the one-dimensional normal and the covariance of the previous note.
Notation. is a random vector with mean and covariance matrix , , symmetric and positive definite. ; is the standard normal vector. is the determinant, the transpose. The note uses a little linear algebra: matrix products, inverses and determinants, the quadratic form , and the eigenvectors of a symmetric matrix.
The density#
has the density
For it is the normal density of the continuous distributions note, with . The quadratic form in the exponent, , is the squared Mahalanobis distance: the distance from the mean measured in standard deviations along each direction. The density is constant on the sets where is constant, which are ellipsoids.
If is diagonal, the quadratic form is a sum , the exponential of a sum is a product, and the density factorizes into one normal density per coordinate. The standard normal vector is simply independent coordinates.
Covariance as geometry#
A symmetric positive definite matrix has an orthonormal basis of eigenvectors with positive eigenvalues : . In the coordinates of that basis the covariance is diagonal, so the density factorizes there, with variance along . The contours are ellipses with axes along the eigenvectors and half-lengths at Mahalanobis distance . For
the long axis points along :
A covariance matrix as an ellipse
The long axis carries of the total variance , and projecting onto it gives the first principal component. The ellipses also correct a common intuition. In one dimension, one standard deviation around the mean holds 68% of the probability; in two dimensions the ellipse of Mahalanobis distance 1 holds only , and distance 2 holds , because is a sum of squared standard normals and has the chi-squared distribution with degrees of freedom.
Affine maps#
Linear maps keep Gaussians Gaussian. If , then for any matrix and vector
The mean follows from linearity of expectation and the covariance from bilinearity of covariance; that the result is again Gaussian follows, for an invertible square , from the change-of-variables formula of the functions of random variables note in dimensions, and for any from the characteristic function; when is singular, the result is a degenerate Gaussian concentrated on a subspace, without a density. Three consequences are used constantly:
- Sampling. with (a Cholesky factor) has distribution ; the Gaussian distributions note of the generative models course works through it in PyTorch.
- Whitening. Conversely, : any Gaussian is a standard one in suitable coordinates.
- Linear combinations. . For the example above, whose mean is 0, .
Marginals and conditionals#
Split into two blocks , , with the mean and covariance split accordingly:
The marginal of is read off: , a special case of an affine map that selects coordinates. The conditional of given is Gaussian as well, with
For two scalar coordinates the blocks are numbers, and the formulas read and . For the example, , so given the second coordinate is :
Conditioning a Gaussian vector
Two features of the formulas matter far beyond this example. The conditional mean is a linear function of the observed value, so for jointly Gaussian data linear regression is not an approximation but the exact best predictor, the subject of the conditional expectation note. And the conditional covariance, the Schur complement , does not depend on the observed value: observing shrinks the uncertainty about by the same amount wherever lands. Gaussian process regression and the Kalman filter are these two formulas applied to large covariance matrices.
Uncorrelated means independent, for Gaussian vectors#
For a jointly Gaussian vector, zero covariance between two blocks makes block-diagonal, and the density factorizes: uncorrelated implies independent. This is a property of the joint distribution, not of the marginals. Let and let , where is an independent fair sign. Then as well, and , but : the two are strongly dependent. The pair is not jointly Gaussian: every linear combination of a Gaussian vector is normal, and equals 0 with probability , which no normal variable does.
High dimensions: the shell#
Optional depth: why high-dimensional Gaussian samples avoid the centre. The rest of the note does not depend on it.
The density of is largest at the origin, and yet samples in high dimension are never near it. The squared length has mean and variance , so the length concentrates around with a spread that stays near :
The length of a standard normal vector in d dimensions
In 100 dimensions the length is , and a length below 5 has probability about . The density is high near the centre, but the centre has almost no volume; the volume, and with it the probability, is in a thin shell. Two practical consequences: interpolating linearly between two latent samples of a generative model passes through a region the model never saw during training, which is why spherical interpolation is often used instead; and in high dimensions, distances between independent Gaussian points are all about , so nearest neighbours become less informative.
What changed#
| A general joint distribution | The multivariate Gaussian | |
|---|---|---|
| Parameters | a function of arguments | and : numbers |
| Contours | anything | ellipsoids, axes from the eigenvectors of |
| Linear maps, marginals | new distributions to compute | ; read off blocks |
| Conditionals | renormalized slices | Gaussian, linear mean, Schur complement covariance |
| Uncorrelated | not enough for independence | equivalent to independence |
Limitations#
- Thin tails and one mode. Real data in high dimension are rarely Gaussian: images, text embeddings and returns have heavy tails, clusters and curved structure; mixtures, flows and diffusion models exist for that reason.
- The covariance matrix is expensive. It has free entries, 500,500 for ; estimating it needs many more samples than dimensions, and inverting it costs . Diagonal, low-rank or sparse-precision structures are used in practice.
- Marginal normality proves nothing about the joint. Each coordinate can be normal while the vector is not, as the sign example shows; formulas for conditionals and independence apply only when the vector is jointly Gaussian.
What you should remember#
- has density ; contours are ellipsoids of constant Mahalanobis distance.
- The eigenvectors of give the axes, the square roots of its eigenvalues the half-lengths; in 2D one Mahalanobis unit holds 39%, not 68%.
- ; with samples any Gaussian.
- Marginals are blocks of and ; conditionals are Gaussian with a mean linear in the observation and covariance .
- For jointly Gaussian vectors, uncorrelated means independent.
- A standard normal vector in dimensions has length about .
Code#
The example of the figures checked by sampling, with NumPy:
import numpy as np
from scipy import stats
S = np.array([[2.0, 1.2], [1.2, 1.0]])
w, V = np.linalg.eigh(S)
print(w.round(3), np.abs(V[:, 1]).round(3)) # [0.2 2.8] [0.832 0.555]: the long axis
print(round(1.2 / np.sqrt(2), 2), [round(float(stats.chi2(2).cdf(k * k)), 3) for k in (1, 2)]) # 0.85 [0.393, 0.865]
rng = np.random.default_rng(0)
L = np.linalg.cholesky(S) # sampling: X = L Z
X = rng.normal(size=(1_000_000, 2)) @ L.T
print(np.cov(X.T).round(2).tolist()) # [[2.0, 1.2], [1.2, 1.0]]
d2 = np.einsum('ij,jk,ik->i', X, np.linalg.inv(S), X) # squared Mahalanobis distances
print(round(float((d2 <= 1).mean()), 3), round(float((d2 <= 4).mean()), 3)) # 0.393 0.865
print(round(float(X.sum(axis=1).var()), 2)) # 5.39, against 2 + 1 + 2 * 1.2 = 5.4
# conditioning on X1 = 2: the samples with X1 close to 2
near = X[np.abs(X[:, 0] - 2) < 0.02, 1]
print(round(1.2 / 2 * 2, 2), round(1 - 1.2**2 / 2, 2), round(float(near.mean()), 2), round(float(near.var()), 2)) # 1.2 0.28 1.2 0.28
# normal marginals, zero correlation, and still dependent: Y = S X with a random sign S
x = rng.normal(size=1_000_000)
y = rng.choice([-1, 1], size=x.size) * x
print(round(float(np.corrcoef(x, y)[0, 1]), 3), round(float((x + y == 0).mean()), 3)) # -0.001 0.501
# the shell: the length of a standard normal vector in 100 dimensions
r = np.linalg.norm(rng.normal(size=(100_000, 100)), axis=1)
print(round(float(r.mean()), 2), round(float(r.std()), 2), f'{stats.chi(100).cdf(5):.1e}') # 9.97 0.71 1.1e-15
Next#
For Gaussians the best prediction of from turned out to be linear, with a known variance left over. The question makes sense for any pair of random variables: what function of predicts best, and how much error is left? The next note answers it with the conditional expectation , the regression function that a model trained with squared error approximates; other losses target other features of the conditional distribution, such as its median or a quantile.
References#
- C. M. Bishop. Pattern Recognition and Machine Learning. Springer, 2006. Section 2.3 (the Gaussian distribution, conditional and marginal Gaussians).
- M. P. Deisenroth, A. A. Faisal, C. S. Ong. Mathematics for Machine Learning. Cambridge University Press, 2020. Section 6.5 (Gaussian distribution).
- J. K. Blitzstein, J. Hwang. Introduction to Probability, 2nd ed. CRC Press, 2019. Section 7.5 (multivariate normal).
- T. White. Sampling Generative Networks. arXiv:1609.04468, 2016. Spherical interpolation in latent spaces.