Module contents
Lesson 14 of 24Core 105 min

The multivariate Gaussian I: definition, geometry and sampling

The multivariate Gaussian underlies Gaussian processes, the Kalman filter, VAEs, diffusion and the multivariate CLT. Define it through linear combinations; study its geometry, affine closure, and numerically stable sampling and evaluation with Cholesky.

After this lesson you can

  • Define the multivariate Gaussian using linear combinations and prove equivalence with the characteristic function and density.
  • Apply AX + b ~ N(Aμ + b, AΣAᵀ), including the degenerate case and the reparameterization μ + Lε.
  • Relate eigenvalues and eigenvectors of Σ to level ellipsoids, and Mahalanobis distance to chi-squared.
  • Implement stable sampling, log density and whitening with Cholesky.
  • Distinguish jointly Gaussian variables from variables with normal marginals.

Before you start

Motivation: one object, six disciplines

Previous lessons gave you the machinery: the covariance matrix, the characteristic function, and change of variables for densities. This lesson applies it to the most widely used object in applied probability, the multivariate Gaussian (or multivariate normal). It appears in the same form in seemingly unrelated fields:

  • Gaussian processes. An unknown function evaluated at nn points is an nn-dimensional vector N(m,K)\Normal(\vb{m}, \mat{K}); prediction conditions that vector, and the numerical difficulty is factorizing K\mat{K}.
  • Kalman filter. State and observation are Gaussian; each step is an affine transformation followed by conditioning.
  • Variational autoencoders. The encoder produces z=μϕ(x)+Lϕ(x) ε\vb{z} = \vb{\mu}_\phi(\vb{x}) + \mat{L}_\phi(\vb{x})\,\vb{\eps} with ε∼N(0,I)\vb{\eps} \sim \Normal(\vb{0}, \mat{I}): this reparameterization permits differentiation through sampling.
  • Diffusion. The noise process is xt=αˉt x0+1−αˉt ε\vb{x}_t = \sqrt{\bar\alpha_t}\,\vb{x}_0 + \sqrt{1 - \bar\alpha_t}\,\vb{\eps}, an affine transformation of a standard Gaussian.
  • Multivariate central limit theorem. Normalized sums of independent random vectors converge in law to a Gaussian, which therefore appears as a universal limit in the CLT lesson.
  • Quantitative finance. To simulate correlated returns of NN assets, factor the covariance matrix and write r=μ+Lε\vb{r} = \vb{\mu} + \mat{L}\vb{\eps}.

All six share one recipe, X=μ+Lε\vb{X} = \vb{\mu} + \mat{L}\vb{\eps}, and this lesson asks: why is this family so tractable? There are four reasons, which you will prove and see one by one. It is closed under affine transformations. It is determined by two objects, its mean and covariance. Its level sets are ellipsoids whose geometry is read from eigenvalues. And a single Cholesky factorization supports simulation, evaluation and whitening.

Definition: Gaussian means surviving linear combinations

A one-dimensional Gaussian is defined by its density, but the multivariate density requires invertible Σ\mat{\Sigma}, while real models (a Gaussian process at nearly identical points, a filter with noise in only some coordinates) have singular covariances. The correct definition avoids density and looks at all projections at once.

All projections being normal says more than it seems. In particular, each coordinate Xi=ei⊤XX_i = \vb{e}_i\T\vb{X} is normal and therefore has moments of all orders, so μ=E[X]\vb{\mu} = \E[\vb{X}] and Σ=Cov⁡(X)\mat{\Sigma} = \Cov(\vb{X}) exist (lesson 8). By linearity, E[a⊤X]=a⊤μ\E[\vb{a}\T\vb{X}] = \vb{a}\T\vb{\mu} and Var⁡(a⊤X)=a⊤Σa\Var(\vb{a}\T\vb{X}) = \vb{a}\T\mat{\Sigma}\vb{a}: every projection is N(a⊤μ,a⊤Σa)\Normal(\vb{a}\T\vb{\mu}, \vb{a}\T\mat{\Sigma}\vb{a}), and Σ\mat{\Sigma} is symmetric positive semidefinite because these variances are nonnegative.

Proof

(1)⇒(2)(1) \Rightarrow (2). Fix t\vb{t}. Since t⊤X∼N(t⊤μ,t⊤Σt)\vb{t}\T\vb{X} \sim \Normal(\vb{t}\T\vb{\mu}, \vb{t}\T\mat{\Sigma}\vb{t}) and the characteristic function of N(m,s2)\Normal(m, s^2) is u↦eium−s2u2/2u \mapsto e^{ium - s^2u^2/2} (also when s=0s = 0), evaluating at u=1u = 1:

φX(t)=E[ei t⊤X]=φt⊤X(1)=exp⁡ ⁣(i t⊤μ−12t⊤Σt).\varphi_{\vb{X}}(\vb{t}) = \E\big[e^{i\,\vb{t}\T\vb{X}}\big] = \varphi_{\vb{t}\T\vb{X}}(1) = \exp\!\big(i\,\vb{t}\T\vb{\mu} - \tfrac{1}{2}\vb{t}\T\mat{\Sigma}\vb{t}\big).

(2)⇒(1)(2) \Rightarrow (1). For a∈Rd\vb{a} \in \R^d and u∈Ru \in \R, φa⊤X(u)=φX(ua)=exp⁡(iu a⊤μ−12u2 a⊤Σa)\varphi_{\vb{a}\T\vb{X}}(u) = \varphi_{\vb{X}}(u\vb{a}) = \exp(iu\,\vb{a}\T\vb{\mu} - \tfrac{1}{2}u^2\,\vb{a}\T\mat{\Sigma}\vb{a}), the characteristic function of N(a⊤μ,a⊤Σa)\Normal(\vb{a}\T\vb{\mu}, \vb{a}\T\mat{\Sigma}\vb{a}). By uniqueness of the characteristic function, a⊤X\vb{a}\T\vb{X} is normal. This holds for every a\vb{a}: X\vb{X} is Gaussian, and its moments are those in the definition because they are read from each projection’s law.

∎

An existence question remains: given μ\vb{\mu} and any positive semidefinite Σ\mat{\Sigma}, is there really a Gaussian vector with those parameters? Yes, and the construction is the recipe for the whole lesson.

Proof

Let s=A⊤t\vb{s} = \mat{A}\T\vb{t}. Because the εj\eps_j are independent, the expectation of the product is the product of expectations:

E[eit⊤(μ+Aε)]=eit⊤μ E[∏j=1keisjεj]=eit⊤μ∏j=1ke−sj2/2=exp⁡ ⁣(it⊤μ−12t⊤AA⊤t).\E\big[e^{i\vb{t}\T(\vb{\mu} + \mat{A}\vb{\eps})}\big] = e^{i\vb{t}\T\vb{\mu}}\,\E\Big[\prod_{j=1}^{k} e^{i s_j \eps_j}\Big] = e^{i\vb{t}\T\vb{\mu}}\prod_{j=1}^{k} e^{-s_j^2/2} = \exp\!\big(i\vb{t}\T\vb{\mu} - \tfrac{1}{2}\vb{t}\T\mat{A}\mat{A}\T\vb{t}\big).

This is the form of point (2) of the previous theorem with Σ=AA⊤\mat{\Sigma} = \mat{A}\mat{A}\T: X\vb{X} is Gaussian with those parameters. The converse is uniqueness: vectors with the same characteristic function have the same law. Finally, the spectral theorem gives Σ=UΛU⊤\mat{\Sigma} = \mat{U}\mat{\Lambda}\mat{U}\T with Λ⪰0\mat{\Lambda} \succeq 0, and A=UΛ1/2\mat{A} = \mat{U}\mat{\Lambda}^{1/2} satisfies AA⊤=Σ\mat{A}\mat{A}\T = \mat{\Sigma}.

∎

Thus the three descriptions of a Gaussian are equivalent: by projections (the definition), by characteristic function, and as an affine image of white noise, X=μ+Aε\vb{X} = \vb{\mu} + \mat{A}\vb{\eps}. Each serves a purpose. Projections are best for proving closure properties; the characteristic function identifies laws; the affine image supports simulation and differentiation through sampling.

The density, and what happens when it does not exist

If Σ\mat{\Sigma} is positive definite, the Gaussian has a density with respect to Lebesgue measure on Rd\R^d, obtained by the change of variables from lesson 10.

Before reading the proof, try to anticipate each step: it is a linear change of variables, and you only need to track where each factor appears.

Σ=LL⊤,X=μ+Lε,ε∼N(0,I)\begin{gathered} \mat{\Sigma} = \mat{L}\mat{L}\T, \\ \vb{X} = \vb{\mu} + \mat{L}\vb{\eps}, \quad \vb{\eps} \sim \Normal(\vb{0}, \mat{I}) \end{gathered}
With Σ≻0\mat{\Sigma} \succ 0 an invertible L\mat{L} exists (Cholesky, for example), and the existence theorem gives the law of X\vb{X}. The density of ε\vb{\eps} is the product of dd standard normals: pε(z)=(2π)−d/2e−∥z∥2/2p_{\vb{\eps}}(\vb{z}) = (2\pi)^{-d/2} e^{-\norm{\vb{z}}^2/2}.
1/5

Notice that the only quantity depending on x\vb{x} is the exponent, and the normalization factor is det⁡(Σ)−1/2\det(\mat{\Sigma})^{-1/2}: a matrix stretching space by a factor det⁡L\det\mat{L} dilutes density by the same factor, keeping total mass one.

Proof

Let v∈null⁡(Σ)\vb{v} \in \nullsp(\mat{\Sigma}). Then Var⁡(v⊤X)=v⊤Σv=0\Var(\vb{v}\T\vb{X}) = \vb{v}\T\mat{\Sigma}\vb{v} = 0, so v⊤(X−μ)=0\vb{v}\T(\vb{X} - \vb{\mu}) = 0 almost surely. Taking a finite basis of null⁡(Σ)\nullsp(\mat{\Sigma}), X−μ\vb{X} - \vb{\mu} is almost surely orthogonal to the whole kernel, i.e. it lies in null⁡(Σ)⊥=col⁡(Σ)\nullsp(\mat{\Sigma})^\perp = \col(\mat{\Sigma}) (since Σ\mat{\Sigma} is symmetric). A proper affine subspace has Lebesgue measure zero but probability one under the law of X\vb{X}: that law is singular with respect to Lebesgue measure and, by Radon-Nikodym, cannot have a density.

∎

The degenerate Gaussian is not pathological: it includes X=(Y,Y)\vb{X} = (Y, Y) with normal YY, returns on two identical assets, a linear model with more variables than noise sources, and Gaussian-process distributions at repeated points. Within its subspace it does have a density relative to rr-dimensional Lebesgue measure, and the theory works the same way; one must simply avoid writing Σ−1\mat{\Sigma}\inv.

Affine transformations: closure that makes everything work

With the projection definition, the family’s most important property is proved in three lines.

Proof

For each c∈Rm\vb{c} \in \R^m, c⊤Y=(A⊤c)⊤X+c⊤b\vb{c}\T\vb{Y} = (\mat{A}\T\vb{c})\T\vb{X} + \vb{c}\T\vb{b} is an affine function of a linear combination of X\vb{X}, which is normal; an affine function of a normal (including zero slope) is normal. Hence Y\vb{Y} is Gaussian. Its mean is Aμ+b\mat{A}\vb{\mu} + \vb{b} by linearity, and its covariance E[A(X−μ)(X−μ)⊤A⊤]=AΣA⊤\E[\mat{A}(\vb{X} - \vb{\mu})(\vb{X} - \vb{\mu})\T\mat{A}\T] = \mat{A}\mat{\Sigma}\mat{A}\T. A Gaussian with those parameters has that law by the characteristic function theorem.

∎

Almost all Gaussian calculations apply this one line:

  • Marginals. If A\mat{A} selects coordinates, the subvector is Gaussian with the corresponding submatrix of Σ\mat{\Sigma}. Each coordinate XiX_i is N(μi,Σii)\Normal(\mu_i, \Sigma_{ii}).
  • Projections. a⊤X∼N(a⊤μ,a⊤Σa)\vb{a}\T\vb{X} \sim \Normal(\vb{a}\T\vb{\mu}, \vb{a}\T\mat{\Sigma}\vb{a}), which is the definition.
  • Sums. If X\vb{X} and Y\vb{Y} are independent Gaussians, (X,Y)(\vb{X}, \vb{Y}) is Gaussian (its characteristic function is the product of two Gaussians) and hence X+Y∼N(μX+μY,ΣX+ΣY)\vb{X} + \vb{Y} \sim \Normal(\vb{\mu}_X + \vb{\mu}_Y, \mat{\Sigma}_X + \mat{\Sigma}_Y).
  • Sampling. X=μ+Lε\vb{X} = \vb{\mu} + \mat{L}\vb{\eps} is the recipe for simulating N(μ,LL⊤)\Normal(\vb{\mu}, \mat{L}\mat{L}\T).
  • Whitening. If Σ≻0\mat{\Sigma} \succ 0, L−1(X−μ)∼N(0,L−1ΣL−T)=N(0,I)\mat{L}\inv(\vb{X} - \vb{\mu}) \sim \Normal(\vb{0}, \mat{L}\inv\mat{\Sigma}\mat{L}^{-\mathsf{T}}) = \Normal(\vb{0}, \mat{I}).

Now check the theorem hands-on. Drag the two columns of A\mat{A} and see what happens to the N(0,I)\Normal(\vb{0}, \mat{I}) cloud.

InteractiveTransforming a standard Gaussian
  • columns of A\mat{A}
  • radius-1 ellipse (image of the circle)
  • N(0,I)\mathcal{N}(\vb{0}, \mat{I}) and unit circle
0°
A=[1.000.900.000.60]\mat{A} = \begin{bmatrix} 1.00 & 0.90 \\ 0.00 & 0.60 \end{bmatrix}
AA⊤=[1.810.540.540.36]\mat{A}\mat{A}\T = \begin{bmatrix} 1.81 & 0.54 \\ 0.54 & 0.36 \end{bmatrix}
det⁡A\det\mat{A}0.600
Principal standard deviations σ1, σ2\sigma_1,\ \sigma_21.410, 0.425
Sample Σ^11, Σ^12, Σ^22\hat\Sigma_{11},\ \hat\Sigma_{12},\ \hat\Sigma_{22}1.84, 0.55, 0.37
The gray cloud is a sample from N(0,I)\Normal(\vb{0}, \mat{I}) and the dashed circle its Mahalanobis ellipse of radius 1. Drag the tips of columns a1\vb{a}_1 and a2\vb{a}_2 of A\mat{A}: the colored cloud is Aε\mat{A}\vb{\eps}, a sample from N(0,AA⊤)\Normal(\vb{0}, \mat{A}\mat{A}\T), and the blue ellipse is the image of the circle. Align the columns and the cloud falls on a line. Use the slider to rotate the input, X=AQε\vb{X} = \mat{A}\mat{Q}\vb{\eps}: the points move, the ellipse does not. Buttons rewrite A\mat{A} as the Cholesky factor, symmetric square root or scaled eigenvectors of the same Σ\mat{\Sigma}.

What you should have seen:

  • The ellipse and Σ=AA⊤\mat{\Sigma} = \mat{A}\mat{A}\T are all that matter. Rotating the input with Q\mat{Q} changes each point but preserves the cloud’s shape and statistics, because (AQ)(AQ)⊤=AQQ⊤A⊤=AA⊤(\mat{A}\mat{Q})(\mat{A}\mat{Q})\T = \mat{A}\mat{Q}\mat{Q}\T\mat{A}\T = \mat{A}\mat{A}\T. Equivalently, the square root A\mat{A} of Σ\mat{\Sigma} is not unique, and any two roots differ by an orthogonal matrix.
  • Cholesky, symmetric square root and eigenvectors are three roots of the same Σ\mat{\Sigma}. Each button completely changes A\mat{A} (triangular, symmetric, with orthogonal columns), yet the ellipse does not move a pixel.
  • With the “40° rotation” matrix, A=R\mat{A} = \mat{R} satisfies RR⊤=I\mat{R}\mat{R}\T = \mat{I}: the colored cloud rotates relative to the gray one, but its ellipse remains the unit circle and its law remains N(0,I)\Normal(\vb{0}, \mat{I}). This foreshadows rotational invariance in the last section.
  • With aligned columns, det⁡A=0\det\mat{A} = 0 and the Gaussian degenerates: all mass falls on a line and Σ\mat{\Sigma} is singular. The preceding proposition in action.

Geometry: ellipsoids and Mahalanobis distance

Let Σ≻0\mat{\Sigma} \succ 0 have spectral decomposition Σ=UΛU⊤\mat{\Sigma} = \mat{U}\mat{\Lambda}\mat{U}\T, Λ=diag⁡(λ1,…,λd)\mat{\Lambda} = \diag(\lambda_1, \dots, \lambda_d) and orthonormal columns ui\vb{u}_i. Then Σ−1=UΛ−1U⊤\mat{\Sigma}\inv = \mat{U}\mat{\Lambda}\inv\mat{U}\T and the density exponent is

(x−μ)⊤Σ−1(x−μ)=∑i=1d(ui⊤(x−μ))2λi.(\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}) = \sum_{i=1}^{d}\frac{\big(\vb{u}_i\T(\vb{x} - \vb{\mu})\big)^2}{\lambda_i}.

This is the sum of the squared coordinates of x−μ\vb{x} - \vb{\mu} in the eigenvector basis, each divided by its variance. Density p(x)p(\vb{x}) decreases with this quantity, so its level sets are the sets where it is constant.

The level sets {x:dM(x)=r}\{\vb{x} : d_M(\vb{x}) = r\} are ellipsoids centered at μ\vb{\mu}, with axes in directions ui\vb{u}_i and semiaxes rλir\sqrt{\lambda_i}: they are the image under μ+L ⋅\vb{\mu} + \mat{L}\,\cdot of the Euclidean sphere of radius rr. Eigenvalues are variances and their square roots are the semiaxis lengths of the radius-1 ellipsoid.

Proof

Let z=L−1(x−μ)\vb{z} = \mat{L}\inv(\vb{x} - \vb{\mu}) and b=L⊤a\vb{b} = \mat{L}\T\vb{a}. Then a⊤(x−μ)=b⊤z\vb{a}\T(\vb{x} - \vb{\mu}) = \vb{b}\T\vb{z} and a⊤Σa=∥b∥2\vb{a}\T\mat{\Sigma}\vb{a} = \norm{\vb{b}}^2. Since a↦b\vb{a} \mapsto \vb{b} is a bijection, the ratio is ∣b⊤z∣/∥b∥\abs{\vb{b}\T\vb{z}}/\norm{\vb{b}}, which by Cauchy-Schwarz is ≤∥z∥\le \norm{\vb{z}} with equality for b∥z\vb{b} \parallel \vb{z}.

∎

This is a useful interpretation: dM(x)≤rd_M(\vb{x}) \le r means no linear combination of coordinates sees x\vb{x} more than rr standard deviations from its mean. How much probability is inside those ellipsoids? It depends only on dd and rr, not Σ\mat{\Sigma}.

Proof

Let Z=L−1(X−μ)\vb{Z} = \mat{L}\inv(\vb{X} - \vb{\mu}). By affine closure, Z∼N(0,L−1ΣL−T)=N(0,I)\vb{Z} \sim \Normal(\vb{0}, \mat{L}\inv\mat{\Sigma}\mat{L}^{-\mathsf{T}}) = \Normal(\vb{0}, \mat{I}), and its characteristic function is exp⁡(−12∥t∥2)=∏ie−ti2/2\exp(-\tfrac{1}{2}\norm{\vb{t}}^2) = \prod_i e^{-t_i^2/2}: it factorizes, so coordinates Z1,…,ZdZ_1, \dots, Z_d are independent and N(0,1)\Normal(0, 1). Then dM(X)2=∥Z∥2=∑iZi2d_M(\vb{X})^2 = \norm{\vb{Z}}^2 = \sum_i Z_i^2 is a sum of dd independent variables with law χ12=Gamma(12,rate 12)\chi^2_1 = \mathrm{Gamma}(\tfrac{1}{2}, \text{rate } \tfrac{1}{2}) (change of variables with y=z2y = z^2). Independent gammas with the same rate add their shapes (exponential-gamma family), and the sum is Gamma(d2,12)=χd2\mathrm{Gamma}(\tfrac{d}{2}, \tfrac{1}{2}) = \chi^2_d.

∎

In two dimensions, χ22\chi^2_2 is an exponential with mean 2 and coverage has closed form: P(dM≤r)=1−e−r2/2\Pr(d_M \le r) = 1 - e^{-r^2/2}. This interactive shows it and challenges the habit of applying the 68-95-99.7 rule.

InteractiveCovariance sculptor
N(0,Σ)\mathcal{N}(\vb{0}, \mat{\Sigma}) cloud and Mahalanobis ellipses of radii 1, 2 and 3
123
  • within radius 1
  • between 1 and 2
  • between 2 and 3
  • outside radius 3
Coverage of radius-rr ellipse in dimension d=2d = 2
r=1r = 139.3 % (sample 37.9 %)
r=2r = 286.5 % (sample 86.0 %)
r=3r = 398.9 % (sample 98.3 %)
Bar: P(χd2≤r2)P(\chi^2_d \le r^2). Solid line: sample fraction. Dashed line: the 68.3 / 95.4 / 99.7 rule for d=1d = 1.
Coverage dimension dd
Σ=[1.650.880.880.96]\mat{\Sigma} = \begin{bmatrix} 1.65 & 0.88 \\ 0.88 & 0.96 \end{bmatrix}
λ1, λ2\lambda_1,\ \lambda_22.250, 0.360
ρ=Σ12/Σ11Σ22\rho = \Sigma_{12}/\sqrt{\Sigma_{11}\Sigma_{22}}0.699
det⁡Σ\det\mat{\Sigma}0.810
Mahalanobis radius covering 95 % (d = 2)2.448
Typical radius d\sqrt{d}1.414
Drag the axis endpoints: you change the eigenvectors and eigenvalues of Σ\mat{\Sigma}, and with them the cloud and Mahalanobis ellipses of radii 1, 2 and 3. Watch the right panel: the percentages of the cloud within each ellipse do not change as you sculpt Σ\mat{\Sigma}, because each point keeps its Mahalanobis distance. Dimension dd does change coverage: move from 1 to 10 and compare with the one-dimensional rule (dashed line). “Another sample” redraws the cloud.

What you should have seen:

  • In dimension 2, ellipses of radii 1, 2 and 3 cover 39.3 %, 86.5 % and 98.9 %, not the 68.3 %, 95.4 % and 99.7 % of one dimension. To reach 95 % in the plane take r=2.45r = 2.45, not 1.961.96.
  • Coverage does not depend on Σ\mat{\Sigma}. By the theorem it depends only on dd and rr. Sculpting covariance deforms the cloud, but each point travels with its ellipse and remains in the same ring: it is the image under L\mat{L} of a fixed point in the standard cloud, and its Mahalanobis distance is that point’s norm.
  • In high dimensions, the radius-1 ball is almost empty. For d=10d = 10 the radius-1 ellipsoid contains 0.017 % of the mass and the radius-3 one only 46.8 %. Mass lives around radius d\sqrt{d}, because E[dM2]=d\E[d_M^2] = d.

The table gives exact coverages P(χd2≤r2)\Pr(\chi^2_d \le r^2), which you will verify with SciPy below:

ddr=1r = 1r=2r = 2r=3r = 395 % radius
168.27 %95.45 %99.73 %1.960
239.35 %86.47 %98.89 %2.448
319.87 %73.85 %97.07 %2.795
53.74 %45.06 %89.09 %3.327
100.017 %5.27 %46.79 %4.279

The observation on mass deserves one more sentence. Since E[∥Z∥2]=d\E[\norm{\vb{Z}}^2] = d and Var⁡(∥Z∥2)=2d\Var(\norm{\vb{Z}}^2) = 2d, the norm ∥Z∥\norm{\vb{Z}} concentrates around d\sqrt{d}, in a shell of nearly constant thickness (its standard deviation approaches 1/21/\sqrt{2}, as the final section’s cell shows). In dimension 100, mass is at distance 10±0.710 \pm 0.7 from the origin, and the origin, although the density maximum, is a place no sample visits. We will prove it in norm concentration.

Stable sampling and log density with Cholesky

The recipe X=μ+Lε\vb{X} = \vb{\mu} + \mat{L}\vb{\eps} is an algorithm. Cholesky sampling factorizes Σ=LL⊤\mat{\Sigma} = \mat{L}\mat{L}\T once (Cholesky factorization, with lower-triangular L\mat{L} and positive diagonal, unique if Σ≻0\mat{\Sigma} \succ 0), then for each sample generates dd standard normals and computes a matrix-vector product. Factorization costs about d3/3d^3/3 operations and each sample d2d^2. Correctness follows from the existence theorem: LL⊤=Σ\mat{L}\mat{L}\T = \mat{\Sigma} gives the right covariance.

The same L\mat{L} evaluates the log density. For Σ≻0\mat{\Sigma} \succ 0, the logarithm of the density is

log⁡p(x)=−12(dlog⁡2π+2∑i=1dlog⁡Lii⏟log⁡det⁡Σ+∥z∥2⏟dM2),Lz=x−μ.\log p(\vb{x}) = -\tfrac{1}{2}\Big(d\log 2\pi + \underbrace{2\sum_{i=1}^{d}\log L_{ii}}_{\log\det\mat{\Sigma}} + \underbrace{\norm{\vb{z}}^2}_{d_M^2}\Big), \qquad \mat{L}\vb{z} = \vb{x} - \vb{\mu}.

The vector z\vb{z} is obtained by solving a triangular system by forward substitution, at cost d2d^2, and the log determinant comes from the diagonal: det⁡Σ=det⁡(L)2=∏iLii2\det\mat{\Sigma} = \det(\mat{L})^2 = \prod_i L_{ii}^2. Neither Σ−1\mat{\Sigma}\inv nor det⁡Σ\det\mat{\Sigma} is ever formed. The reasons, in order of importance:

  1. The determinant overflows or underflows. With d=300d = 300 and variances of order 10−310^{-3}, det⁡Σ≈10−900\det\mat{\Sigma} \approx 10^{-900}, below the smallest float64 (≈10−308\approx 10^{-308}): np.linalg.det returns 0.0 and its logarithm gives −∞-\infty. Summing logarithms avoids that problem.
  2. Cholesky fails loudly; the inverse lies silently. If Σ\mat{\Sigma} is not positive definite (because of rounding or a modeling error), Cholesky raises an exception. np.linalg.inv returns a matrix of numbers, and the quadratic form x⊤Σ−1x\vb{x}\T\mat{\Sigma}\inv\vb{x} can be negative, impossible for a squared distance. With ∥z∥2\norm{\vb{z}}^2, it is a sum of squares.
  3. Cost. Factorization costs d3/3d^3/3; forming the inverse, about 2d32d^3, six times more.
  4. Reuse. The same L\mat{L} supports sampling, evaluation and whitening.

An honest caveat: Cholesky’s numerical stability is not magic. For Σ\mat{\Sigma} with very large condition number κ(Σ)=λmax⁡/λmin⁡\kappa(\mat{\Sigma}) = \lambda_{\max}/\lambda_{\min}, relative error in dM2d_M^2 is of order κ εmach\kappa\,\varepsilon_{\text{mach}} with either method; the advantages above are structural. When κ\kappa reaches εmach−1≈1016\varepsilon_{\text{mach}}^{-1} \approx 10^{16}, nothing remains to save: the matrix is numerically singular and the model must change.

The usual remedy is jitter (or nugget): factorize Σ+δI\mat{\Sigma} + \delta\mat{I} with small δ\delta, around 10−810^{-8} times the mean diagonal. This is not meaningless: Σ+δI\mat{\Sigma} + \delta\mat{I} is the covariance of X+δ ε′\vb{X} + \sqrt{\delta}\,\vb{\eps}', the same variable with a little independent noise added, and is positive definite by construction. Gaussian processes use it constantly.

Implementation from scratch

We will build a complete MultivariateNormal class: our own Cholesky factorization (Cholesky-Banachiewicz algorithm), sampling, whitening, Mahalanobis distance and log density. Then we will compare it with SciPy.

[ ]MultivariateNormal desde cero: Cholesky, muestreo, blanqueado y log-densidadBrowser
import numpy as np
from scipy.linalg import solve_triangular

def cholesky(S):
    """Cholesky-Banachiewicz: L inferior con L @ L.T = S, para S simétrica definida positiva."""
    n = len(S)
    L = np.zeros((n, n))
    for i in range(n):
        for j in range(i + 1):
            s = S[i, j] - L[i, :j] @ L[j, :j]
            if i == j:
                if s <= 0:
                    raise np.linalg.LinAlgError(f"pivote no positivo ({s:.2e}) en la fila {i}: Σ no es definida positiva")
                L[i, i] = np.sqrt(s)
            else:
                L[i, j] = s / L[j, j]
    return L

class MultivariateNormal:
    def __init__(self, mu, Sigma, jitter=0.0, chol=cholesky):
        self.mu = np.asarray(mu, dtype=float)
        self.d = len(self.mu)
        S = np.asarray(Sigma, dtype=float)
        self.L = chol(S + jitter * np.eye(self.d))
        self.logdet = 2.0 * np.log(np.diag(self.L)).sum()        # log det Σ = 2 Σ log L_ii

    def sample(self, n, rng):
        eps = rng.standard_normal((n, self.d))
        return self.mu + eps @ self.L.T                          # filas: (L ε)ᵀ = εᵀ Lᵀ

    def whiten(self, x):
        r = np.atleast_2d(x) - self.mu
        return solve_triangular(self.L, r.T, lower=True).T       # z = L⁻¹ (x − μ), sin formar L⁻¹

    def mahalanobis2(self, x):
        return (self.whiten(x) ** 2).sum(axis=1)

    def logpdf(self, x):
        return -0.5 * (self.d * np.log(2 * np.pi) + self.logdet + self.mahalanobis2(x))

rng = np.random.default_rng(0)
d = 4
A = rng.standard_normal((d, d))
Sigma = A @ A.T + 0.5 * np.eye(d)
mu = np.array([1.0, -2.0, 0.5, 3.0])

mvn = MultivariateNormal(mu, Sigma)
print("máx |L propia − np.linalg.cholesky| =", np.abs(mvn.L - np.linalg.cholesky(Sigma)).max())
print("máx |L Lᵀ − Σ|                     =", np.abs(mvn.L @ mvn.L.T - Sigma).max())

X = mvn.sample(50_000, rng)
print("error relativo de la media muestral :", np.abs(X.mean(axis=0) - mu).max() / np.abs(mu).max())
print("error relativo de la covarianza     :", np.abs(np.cov(X.T) - Sigma).max() / np.abs(Sigma).max())

Z = mvn.whiten(X)
print("covarianza de los datos blanqueados (primera fila):", np.cov(Z.T).round(2)[0])

The three one-line checks (our L\mat{L} agrees with NumPy, sampling reproduces mean and covariance, and whitening returns the identity) are worth writing whenever you implement a sampler. Now validate against SciPy and the geometry section’s theory, and check the incorrect sampler’s error:

[ ]Validación frente a SciPy, ley chi-cuadrado y el muestreador equivocadoBrowser
from scipy import stats

ref = stats.multivariate_normal(mu, Sigma)
print("máx |logpdf propia − scipy| =", np.abs(mvn.logpdf(X[:2000]) - ref.logpdf(X[:2000])).max())

m2 = mvn.mahalanobis2(X)
print(f"E[d_M²] = {m2.mean():.3f} (teoría: d = {d});  Var[d_M²] = {m2.var():.2f} (teoría: 2d = {2 * d})")
print("p-valor de Kolmogorov-Smirnov frente a chi²_4:", round(stats.kstest(m2, stats.chi2(d).cdf).pvalue, 3))
for r in (1, 2, 3):
    print(f"  cobertura del radio {r}: muestra {np.mean(m2 <= r * r):.4f}   exacta {stats.chi2.cdf(r * r, d):.4f}")

# el error clásico: μ + Σε en lugar de μ + Lε
eps = rng.standard_normal((50_000, d))
mala = mu + eps @ Sigma.T
print("covarianza de μ + Σε:  error frente a Σ² =", round(np.abs(np.cov(mala.T) - Sigma @ Sigma).max() / np.abs(Sigma @ Sigma).max(), 4),
      "  error frente a Σ =", round(np.abs(np.cov(mala.T) - Sigma).max() / np.abs(Sigma).max(), 2))

Now the part where the calculation method matters. First underflow: d=300d = 300 with variances of order 10−310^{-3}. Then the covariance matrix of a Gaussian process with Gaussian kernel on 40 points in [0,1][0, 1], a textbook case: mathematically positive definite, numerically singular.

[ ]Cuando la inversa y el determinante fallan, y Cholesky avisaBrowser
# 1) Desbordamiento: det(Σ) ≈ 1e-900 no cabe en un float64
d = 300
S = 1e-3 * (0.3 * np.ones((d, d)) + 0.7 * np.eye(d))
x = 0.01 * np.random.default_rng(1).standard_normal((1, d))
mvn_g = MultivariateNormal(np.zeros(d), S, chol=np.linalg.cholesky)
det, inv = np.linalg.det(S), np.linalg.inv(S)
with np.errstate(all="ignore"):
    ingenua = -0.5 * (d * np.log(2 * np.pi) + np.log(det) + (x @ inv @ x.T)[0, 0])
print(f"det Σ = {det},  log-densidad ingenua = {ingenua},  con Cholesky = {mvn_g.logpdf(x)[0]:.4f}")
print(f"SciPy = {stats.multivariate_normal(np.zeros(d), S).logpdf(x):.4f}   y  log det Σ = {mvn_g.logdet:.2f}")

# 2) Un proceso gaussiano con kernel gaussiano: Σ casi singular
t = np.linspace(0, 1, 40)
K = np.exp(-0.5 * ((t[:, None] - t[None, :]) / 0.3) ** 2)
print(f"\nnúmero de condición de K = {np.linalg.cond(K):.1e};  autovalor mínimo calculado = {np.linalg.eigvalsh(K).min():.1e}")
try:
    np.linalg.cholesky(K)
except np.linalg.LinAlgError as e:
    print("Cholesky de K avisa:", e)
xs = np.random.default_rng(2).standard_normal((2000, 40))
q = np.einsum("ni,ij,nj->n", xs, np.linalg.inv(K), xs)
print(f"x' K⁻¹ x con la inversa: mínimo = {q.min():.1e},  fracción de valores negativos = {np.mean(q < 0):.2f}")

# 3) El remedio: jitter δ I, que equivale a añadir ruido independiente de varianza δ
gp = MultivariateNormal(np.zeros(40), K, jitter=1e-8, chol=np.linalg.cholesky)
Y = gp.sample(2000, np.random.default_rng(3))
print(f"con jitter 1e-8: E[d_M²] = {gp.mahalanobis2(Y).mean():.1f} (teoría: d = 40),  mínimo = {gp.mahalanobis2(Y).min():.1f} (siempre ≥ 0)")

Notice the three stories. In the first, the determinant underflows and the naive log density is +∞+\infty, while Cholesky’s (SciPy uses a spectral decomposition with the same idea) is finite and agrees. In the second, the inverse returns negative “squared distances” for 41 % of samples without warning, while Cholesky refuses to proceed. In the third, jitter restores a well-defined model, and samples satisfy theory: E[dM2]=d\E[d_M^2] = d.

Whitening: three ways to undo a covariance

We used L−1(X−μ)\mat{L}\inv(\vb{X} - \vb{\mu}) to turn a Gaussian into a standard one. This operation, widely used outside probability, has a name and many variants.

Proof

WΣW⊤=I\mat{W}\mat{\Sigma}\mat{W}\T = \mat{I} is equivalent to (WΣ1/2)(WΣ1/2)⊤=I(\mat{W}\mat{\Sigma}^{1/2})(\mat{W}\mat{\Sigma}^{1/2})\T = \mat{I}, meaning Q:=WΣ1/2\mat{Q} := \mat{W}\mat{\Sigma}^{1/2} is orthogonal. Solving gives W=QΣ−1/2\mat{W} = \mat{Q}\mat{\Sigma}^{-1/2}.

∎

There is rotational freedom, with three canonical choices of Q\mat{Q}:

MethodMatrixQ\mat{Q}Property
PCAW=Λ−1/2U⊤\mat{W} = \mat{\Lambda}^{-1/2}\mat{U}\TU⊤\mat{U}\Trotates to principal axes and scales them; allows ordering by variance and discarding
ZCAW=Σ−1/2\mat{W} = \mat{\Sigma}^{-1/2}I\mat{I}symmetric; moves the data least
CholeskyW=L−1\mat{W} = \mat{L}\invL−1Σ1/2\mat{L}\inv\mat{\Sigma}^{1/2}triangular: coordinate ii depends only on the first ii
Proof

With W=QΣ−1/2\mat{W} = \mat{Q}\mat{\Sigma}^{-1/2}, E∥WX−X∥2=tr⁡(WΣW⊤)−2tr⁡(WΣ)+tr⁡Σ=d−2tr⁡(QΣ1/2)+tr⁡Σ\E\norm{\mat{W}\vb{X} - \vb{X}}^2 = \tr(\mat{W}\mat{\Sigma}\mat{W}\T) - 2\tr(\mat{W}\mat{\Sigma}) + \tr\mat{\Sigma} = d - 2\tr(\mat{Q}\mat{\Sigma}^{1/2}) + \tr\mat{\Sigma}. Maximize tr⁡(QΣ1/2)=tr⁡(RΛ1/2)=∑iRiiλi\tr(\mat{Q}\mat{\Sigma}^{1/2}) = \tr(\mat{R}\mat{\Lambda}^{1/2}) = \sum_i R_{ii}\sqrt{\lambda_i} with orthogonal R=U⊤QU\mat{R} = \mat{U}\T\mat{Q}\mat{U}. Orthogonal matrix entries satisfy ∣Rii∣≤1\abs{R_{ii}} \le 1 and λi>0\lambda_i > 0, so the sum is ≤∑iλi\le \sum_i \sqrt{\lambda_i}, with equality if and only if every Rii=1R_{ii} = 1. An orthogonal matrix with ones on the diagonal is the identity, i.e. Q=I\mat{Q} = \mat{I}.

∎

Cholesky has a distinctive interpretation: sequential whitening. Since L−1\mat{L}\inv is lower triangular, ziz_i is a combination of x1,…,xix_1, \dots, x_i; and since x<i\vb{x}_{<i} is itself a combination of z1,…,zi−1z_1, \dots, z_{i-1}, which are uncorrelated with ziz_i, it follows that Lii zi=xi−proj⁡span⁡(x1,…,xi−1)xiL_{ii}\,z_i = x_i - \proj_{\spn(x_1, \dots, x_{i-1})} x_i: the residual from predicting xix_i using its predecessors (L2L^2 projection). Thus Lii2L_{ii}^2 is the variance of that residual, which for a Gaussian is the conditional variance of xix_i given the past (Gaussian conditional expectation is linear, as the next lesson shows), and log⁡det⁡Σ=∑ilog⁡(Lii2)\log\det\mat{\Sigma} = \sum_i\log(L_{ii}^2) is the probability chain rule in matrix form. This is why Cholesky depends on variable ordering and is central to autoregressive models and normalizing flows.

InteractiveThree ways to whiten
Original data
PCA: Λ−1/2U⊤\mat{\Lambda}^{-1/2}\mat{U}\T
ZCA: Σ−1/2\mat{\Sigma}^{-1/2}
Cholesky: L−1\mat{L}\inv
  • grid: one color per angular sector of original data
  • circles of radii 1, 2 and 3
0.80
0.50
1.00
Cholesky order
Error of Cov⁡(WX)\operatorname{Cov}(\mat{W}\vb{X}) versus I\mat{I} (all three, t=1t = 1)0.0000
Distortion E∥WX−X∥2\mathbb{E}\norm{\mat{W}\vb{X} - \vb{X}}^2: PCA, ZCA, Cholesky0.90, 0.57, 0.74
Mean angular rotation per point: PCA, ZCA, Cholesky29°, 22°, 25°
Least distortion: ZCA. All three whiten and differ by a rotation: W=QΣ−1/2\mat{W} = \mat{Q}\mat{\Sigma}^{-1/2} with Q\mat{Q} orthogonal.
The data (upper left) contain an embedded grid whose vertices are colored by angular sector. The other three panels show the result of applying W\mat{W} (PCA, ZCA and Cholesky) estimated from sample covariance. All three have sample covariance I\mat{I} (fitting the radius-1 circle, with error in the readouts), but their grids are rotated, symmetric or sheared differently. Move tt from 0 to 1 to watch the process and change the Cholesky order.

What you should have seen:

  • All three whiten. Readouts confirm Cov⁡(WX)=I\Cov(\mat{W}\vb{X}) = \mat{I} for each up to rounding, and all three clouds fill the radius-1 circle.
  • ZCA most resembles the data. Its grid does not rotate as a whole: it compresses along the data’s principal axis and stretches along the secondary one, with both axes fixed, and has the lowest distortion in the readouts. PCA rotates to align principal and coordinate axes, while Cholesky shears: the first coordinate is unchanged except for scale and the second absorbs everything.
  • Cholesky depends on order. Switching from “x1x_1 first” to “x2x_2 first” changes the output, and both are valid whitenings.
  • Whitening is affine, so it preserves Gaussianity. If data are Gaussian, the output is N(0,I)\Normal(\vb{0}, \mat{I}): independent components. Otherwise, uncorrelated does not imply independent, as we see next.

The same experiment in three dimensions, checking that the three matrices are QΣ−1/2\mat{Q}\mat{\Sigma}^{-1/2} for an orthogonal Q\mat{Q}, ZCA distorts less and Cholesky is triangular:

[ ]Blanqueado PCA, ZCA y Cholesky en R³Browser
from scipy.linalg import eigh, cholesky as chol_lower

rng = np.random.default_rng(1)
d = 3
A = np.array([[2.0, 0.0, 0.0], [1.2, 1.0, 0.0], [0.8, -0.9, 0.4]])
X = np.array([1.0, 2.0, -1.0]) + rng.standard_normal((20_000, d)) @ A.T
Xc = X - X.mean(axis=0)
S = np.cov(Xc.T)
lam, U = eigh(S)
S_half = U @ np.diag(lam ** 0.5) @ U.T

W = {
    "PCA": np.diag(lam ** -0.5) @ U.T,
    "ZCA": U @ np.diag(lam ** -0.5) @ U.T,
    "Cholesky": np.linalg.inv(chol_lower(S, lower=True)),
}
for nombre, Wk in W.items():
    Zk = Xc @ Wk.T
    Q = Wk @ S_half
    print(f"{nombre:9s} error de Cov(WX) − I = {np.abs(np.cov(Zk.T) - np.eye(d)).max():.0e}   "
          f"Q ortogonal: {np.allclose(Q @ Q.T, np.eye(d))}   E‖WX − X‖² = {((Zk - Xc) ** 2).sum(axis=1).mean():.3f}   "
          f"simétrica: {np.allclose(Wk, Wk.T)}   triangular: {np.allclose(Wk, np.tril(Wk))}")

Uncorrelated and independent: the jointly Gaussian case

In general, independence implies lack of correlation but not conversely (lesson 8). For jointly Gaussian vectors, the converse holds.

Proof

The joint covariance is block diagonal, Σ=diag⁡(ΣX,ΣY)\mat{\Sigma} = \diag(\mat{\Sigma}_X, \mat{\Sigma}_Y), so the quadratic form separates: (s,t)Σ(s,t)⊤=s⊤ΣXs+t⊤ΣYt(\vb{s}, \vb{t})\mat{\Sigma}(\vb{s}, \vb{t})\T = \vb{s}\T\mat{\Sigma}_X\vb{s} + \vb{t}\T\mat{\Sigma}_Y\vb{t}. Therefore

φ(X,Y)(s,t)=eis⊤μX−12s⊤ΣXs  eit⊤μY−12t⊤ΣYt=φX(s) φY(t).\varphi_{(\vb{X}, \vb{Y})}(\vb{s}, \vb{t}) = e^{i\vb{s}\T\vb{\mu}_X - \frac{1}{2}\vb{s}\T\mat{\Sigma}_X\vb{s}}\;e^{i\vb{t}\T\vb{\mu}_Y - \frac{1}{2}\vb{t}\T\mat{\Sigma}_Y\vb{t}} = \varphi_{\vb{X}}(\vb{s})\,\varphi_{\vb{Y}}(\vb{t}).

The right side is the characteristic function of the product law PX⊗PYP_{\vb{X}} \otimes P_{\vb{Y}}. By uniqueness the joint law is the product law, the definition of independence.

∎

The assumption that the joint vector is Gaussian is essential and cannot be replaced by normality of each marginal. The counterexample is short and completely visible.

InteractiveNormal marginals, non-Gaussian joint law
Sample of (X,Y)(X, Y): lies on two lines
c
  • ∣X∣<c\abs{X} < c: Y=XY = X
  • ∣X∣≥c\abs{X} \ge c: Y=−XY = -X
Histogram of X+YX + Y (red: atom at 0) and a normal with the same variance
−404
Corr⁡(X,Y)=ρ(c)\operatorname{Corr}(X, Y) = \rho(c) as a function of cc
c* = 1.538ρ = 1
1.54
Histogram of
Exact Corr⁡(X,Y)\operatorname{Corr}(X, Y)0.002
Sample Corr⁡(X,Y)\operatorname{Corr}(X, Y)0.000
Variance of XX and YY (sample)1.00, 1.00
Corr⁡(X2,Y2)\operatorname{Corr}(X^2, Y^2)1.000
P(X+Y=0)\Pr(X + Y = 0)0.124
Uncorrelated, with normal marginals but dependent: YY is a function of XX. (X,Y)(X, Y) is not jointly Gaussian.
Move cc and observe the sample of (X,Y)(X, Y): it always falls on the two lines y=xy = x (blue) and y=−xy = -x (red), an X shape. The marginals are N(0,1)\mathcal{N}(0, 1) for every cc, but correlation spans [−1,1][-1, 1] and is zero at c∗≈1.538c^* \approx 1.538, where XX and YY remain completely dependent. Switch the histogram to X+YX + Y to see the atom at 0 (red) ruling out joint normality.

What you should have seen:

  • The scatter plot is an X, not an ellipse. A joint Gaussian with N(0,1)\Normal(0, 1) marginals and correlation ρ\rho would be elliptical; here all mass lies on two lines.
  • Two identical histograms for XX and YY, for each cc: no inspection of marginals reveals the problem.
  • The clearest witness is X+YX + Y, with a peak at 0 ranging from almost all mass (small cc) to none (large cc).
  • Correlation crosses zero at c∗c^* despite total dependence. Lack of correlation measures only linear dependence.

Rotational invariance and uniform directions

With Σ=I\mat{\Sigma} = \mat{I}, the Gaussian is as symmetric as possible, and that symmetry has far-reaching consequences.

Proof

The first statement is affine closure: QIQ⊤=I\mat{Q}\mat{I}\mat{Q}\T = \mat{I}. For the second, the density of ε\vb{\eps} is (2π)−d/2e−r2/2(2\pi)^{-d/2}e^{-r^2/2} with r=∥z∥r = \norm{\vb{z}}, a function of radius alone. In polar coordinates z=rθ\vb{z} = r\vb{\theta}, Lebesgue measure is rd−1 ⁣dr  ⁣dσ(θ)r^{d-1}\dd r\,\dd\sigma(\vb{\theta}), with σ\sigma sphere surface measure, so the joint density of (r,θ)(r, \vb{\theta}) is proportional to rd−1e−r2/2⋅1r^{d-1}e^{-r^2/2}\cdot 1. It factorizes: rr and θ\vb{\theta} are independent, θ\vb{\theta} has constant density relative to σ\sigma (uniform), and rr has density ∝rd−1e−r2/2\propto r^{d-1}e^{-r^2/2}, that of the square root of a χd2\chi^2_d.

∎

This is the cheapest way to sample points uniformly on the sphere: generate dd normals and normalize (Muller, 1959). With uniform coordinates rejection would be needed (keep cube points inside the ball), and acceptance collapses with dimension: 52 % in d=3d = 3 and 0.25 % in d=10d = 10. Angles are the classic trap: choosing two uniform angles concentrates points at the poles. There is also a historically important converse characterization:

One consequence is Archimedes’ theorem: the zz coordinate of a point uniform on sphere S2S^2 is uniform on [−1,1][-1, 1] (projection of the sphere onto an axis preserves area). A cell checks this alongside independence of norm and direction and the high-dimensional norm concentration previewed above:

[ ]Direcciones uniformes, independencia de la norma y concentraciónBrowser
rng = np.random.default_rng(7)

Z = rng.standard_normal((50_000, 3))
n = np.linalg.norm(Z, axis=1)
U3 = Z / n[:, None]                                    # dirección uniforme en S²
print("Arquímedes: p-valor de KS de la coordenada z frente a U[-1, 1] =", round(stats.kstest(U3[:, 2], stats.uniform(-1, 2).cdf).pvalue, 3))
print("corr(‖Z‖², u_z²) =", round(np.corrcoef(n ** 2, U3[:, 2] ** 2)[0, 1], 4), "(≈ 0: norma y dirección son independientes)")

Q, _ = np.linalg.qr(rng.standard_normal((3, 3)))
print("covarianza de QZ para una Q ortogonal cualquiera:", np.cov((Z @ Q.T).T).round(2).tolist()[0])

print("\n  d   media ‖Z‖   √d     desv. ‖Z‖   P(‖Z‖ ≤ 1)")
for d in (1, 2, 10, 50, 100):
    nz = np.linalg.norm(rng.standard_normal((20_000, d)), axis=1)
    print(f"{d:4d}   {nz.mean():8.3f}  {np.sqrt(d):6.3f}   {nz.std():8.3f}   {np.mean(nz <= 1):.4f}")

The final column condenses the lesson’s warning: in dimension 50 none of the 20 000 samples fall inside the radius-1 ball, and the norm is d±0.7\sqrt{d} \pm 0.7.

Using libraries

In practice use scipy.stats.multivariate_normal for evaluation and numpy.random.Generator.multivariate_normal for simulation. NumPy lets you choose a factorization method; its default, SVD, also works with singular Σ\mat{\Sigma}, unlike Cholesky. SciPy supports singular covariances with allow_singular=True, evaluating density in the subspace where the law lives:

[ ]SciPy y NumPy: evaluar, simular y el caso degeneradoBrowser
rng = np.random.default_rng(5)
mu2 = np.array([1.0, -1.0])
S2 = np.array([[2.0, 0.8], [0.8, 1.0]])

pts = rng.multivariate_normal(mu2, S2, size=100_000, method="cholesky")
print("method='cholesky': covarianza muestral =", np.cov(pts.T).round(2).tolist())
pts_svd = rng.multivariate_normal(mu2, S2, size=100_000)
print("method='svd' (por defecto):          =", np.cov(pts_svd.T).round(2).tolist())

# el caso degenerado: (Y, 2Y + 1), toda la masa sobre una recta
S_sing = np.array([[1.0, 2.0], [2.0, 4.0]])
mu_s = np.array([0.0, 1.0])
try:
    np.linalg.cholesky(S_sing)
except np.linalg.LinAlgError:
    print("\nΣ singular: Cholesky falla, como debe")
deg = rng.multivariate_normal(mu_s, S_sing, size=10_000)
print("¿están todas las muestras sobre la recta y = 2x + 1?", np.allclose(deg[:, 1], 2 * deg[:, 0] + 1, atol=1e-6))
g = stats.multivariate_normal(mu_s, S_sing, allow_singular=True)
print("logpdf sobre la recta (densidad dentro del subespacio):", round(float(g.logpdf([0.0, 1.0])), 4),
      "  fuera de ella:", g.logpdf([0.0, 5.0]))

In PyTorch, reparameterization comes into its own: rsample computes μ+Lε\vb{\mu} + \mat{L}\vb{\eps} with ε\vb{\eps} fixed as external noise, making the sample a differentiable function of μ\vb{\mu} and L\mat{L}. The cell checks gradients of J(μ,L)=E∥X∥2=∥μ∥2+∥L∥F2J(\vb{\mu}, \mat{L}) = \E\norm{\vb{X}}^2 = \norm{\vb{\mu}}^2 + \norm{\mat{L}}_F^2, equal to 2μ2\vb{\mu} and 2L2\mat{L} (with lower-triangular L\mat{L}), using the reparameterized estimator and the alternative score-function estimator, whose variance is much greater. This motivates reparameterization in VAEs and diffusion; the cell runs on CPU with minimal sizes.

[ ]Reparametrización en PyTorch: gradientes a través del muestreo (CPU)Local GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = ""                 # solo CPU
import torch
from torch.distributions import MultivariateNormal

torch.manual_seed(0)
n = 200_000
mu = torch.tensor([1.0, -0.5, 2.0], requires_grad=True)
raw = torch.tensor([[1.0, 0.0, 0.0], [0.6, 0.8, 0.0], [-0.3, 0.2, 0.5]], requires_grad=True)

def objetivo(mu, raw, reparametrizar=True):
    L = torch.tril(raw)                                  # la triangular inferior es el parámetro
    dist = MultivariateNormal(mu, scale_tril=L)
    x = dist.rsample((n,)) if reparametrizar else dist.sample((n,))
    return (x ** 2).sum(dim=1).mean()                    # J = E‖X‖² = ‖μ‖² + ‖L‖_F²

J = objetivo(mu, raw)
J.backward()
L = torch.tril(raw.detach())
print("J estimado:", round(J.item(), 3), "  exacto ‖μ‖² + ‖L‖_F²:", round(((mu ** 2).sum() + (L ** 2).sum()).item(), 3))
print("∇μ  estimado:", mu.grad.numpy().round(3), "  exacto 2μ:", (2 * mu.detach()).numpy().round(3))
print("máx |∇L estimado − 2L| =", round((torch.tril(raw.grad) - 2 * L).abs().max().item(), 4))
print("con .sample() el resultado tiene grafo de cálculo:", objetivo(mu.detach().requires_grad_(), raw.detach().requires_grad_(), reparametrizar=False).requires_grad)

# varianza por muestra del gradiente respecto de μ: reparametrización frente a función de puntuación
dist = MultivariateNormal(mu.detach(), scale_tril=L)
x = dist.sample((n,))
g_rep = 2 * x                                                         # ∂/∂μ de ‖μ + Lε‖²
score = torch.cholesky_solve((x - mu.detach()).T, L).T                # Σ⁻¹(x − μ) = ∇μ log p(x)
g_score = (x ** 2).sum(dim=1, keepdim=True) * score
print("desviación por muestra, reparametrización:", g_rep.std(dim=0).numpy().round(2))
print("desviación por muestra, función de puntuación:", g_score.std(dim=0).numpy().round(2))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Both estimators are unbiased and give 2μ2\vb{\mu}, but the reparameterized one has per-sample deviation between 6 and 15 times smaller in this example. This is why VAEs train with reparameterization: the score-function estimator (REINFORCE) would require many more samples or variance-reduction techniques for the same error.

Common mistakes

Exercises

ProofAffine closure via the characteristic function
Prove: Let X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) in Rd\R^d, A∈Rm×d\mat{A} \in \R^{m \times d} and b∈Rm\vb{b} \in \R^m. Then AX+b∼N(Aμ+b,AΣA⊤)\mat{A}\vb{X} + \vb{b} \sim \Normal(\mat{A}\vb{\mu} + \vb{b}, \mat{A}\mat{\Sigma}\mat{A}\T).
0
Without using the projection definition, calculate the characteristic function of Y=AX+b\vb{Y} = \mat{A}\vb{X} + \vb{b} at s∈Rm\vb{s} \in \R^m from that of X\vb{X}.

Step 1 of 4. Which function do you calculate?

ProofMahalanobis distance is chi-squared
Prove: Let X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) in Rd\R^d with Σ≻0\mat{\Sigma} \succ 0. Then (X−μ)⊤Σ−1(X−μ)∼χd2(\vb{X} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{X} - \vb{\mu}) \sim \chi^2_d.
0
Reduce the problem to a standard Gaussian. You may use that a sum of independent gammas with the same rate is a gamma with summed shape, and that χ12=Gamma(12,rate 12)\chi^2_1 = \mathrm{Gamma}(\tfrac{1}{2}, \text{rate } \tfrac{1}{2}).

Step 1 of 5. What is the first step?

NumericCoverage of the radius-2 ellipsoid
Let X∼N(μ,Σ)\vb{X} \sim \Normal(\vb{\mu}, \mat{\Sigma}) in R2\R^2 with Σ=[3112]\mat{\Sigma} = \begin{bmatrix} 3 & 1 \\ 1 & 2 \end{bmatrix}. Calculate the probability that X\vb{X} falls in the ellipsoid {x:(x−μ)⊤Σ−1(x−μ)≤4}\{\vb{x} : (\vb{x} - \vb{\mu})\T\mat{\Sigma}\inv(\vb{x} - \vb{\mu}) \le 4\} (Mahalanobis radius 2).
NumericTail of a linear combination
Let X=(X1,X2)∼N(0,Σ)\vb{X} = (X_1, X_2) \sim \Normal(\vb{0}, \mat{\Sigma}) with Σ=[4223]\mat{\Sigma} = \begin{bmatrix} 4 & 2 \\ 2 & 3 \end{bmatrix}. Calculate P(X1+2X2>6)\Pr(X_1 + 2X_2 > 6).
NumericThe incorrect sampler
With Σ=[2112]\mat{\Sigma} = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}, simulate (incorrectly) X=μ+Σε\vb{X} = \vb{\mu} + \mat{\Sigma}\vb{\eps} with ε∼N(0,I)\vb{\eps} \sim \Normal(\vb{0}, \mat{I}). What is entry (1,2)(1, 2) of the covariance of X\vb{X}?
QuizDoes uncorrelated imply independent?
XX and YY each have marginal law N(0,1)\Normal(0, 1) and Cov⁡(X,Y)=0\Cov(X, Y) = 0. What can you assert?
QuizStandard Gaussian in high dimensions
Let Z∼N(0,I10)\vb{Z} \sim \Normal(\vb{0}, \mat{I}_{10}). Which statements are true?

More than one answer may be correct.

QuizProperties of whitening
Let Σ≻0\mat{\Sigma} \succ 0 and W\mat{W} satisfy WΣW⊤=I\mat{W}\mat{\Sigma}\mat{W}\T = \mat{I}. Which statements are true?

More than one answer may be correct.

QuizCholesky raises LinAlgError
You construct a Gaussian-process covariance matrix with a Gaussian kernel on 200 points in [0,1][0, 1] and np.linalg.cholesky raises LinAlgError: Matrix is not positive definite. What do you do?
CodeStable Gaussian log density
Implement mvn_logpdf(x, mu, L), where L is the lower Cholesky factor of Σ\mat{\Sigma} (L @ L.T == Sigma). x may be a vector of shape (d,), returning a scalar, or a matrix of shape (n, d) with one point per row, returning an array of shape (n,). Do not use np.linalg.inv or np.linalg.det: solve a triangular system and sum the diagonal logarithms. Tests compare with SciPy and include one case where the determinant underflows and another that is ill-conditioned.
import numpy as np
from scipy.linalg import solve_triangular

def mvn_logpdf(x, mu, L):
  # x: (d,) o (n, d); mu: (d,); L: triangular inferior con L @ L.T = Sigma
  pass
Shift+Enter to run

Summary

Key idea
A multivariate Gaussian is a standard sphere seen through a matrix: X=μ+Lε\vb{X} = \vb{\mu} + \mat{L}\vb{\eps} with LL⊤=Σ\mat{L}\mat{L}\T = \mat{\Sigma}, and everything else follows. It is defined by projections, determined by (μ,Σ)(\vb{\mu}, \mat{\Sigma}), closed under affine transformations, has Mahalanobis ellipsoid geometry (with χd2\chi^2_d coverage independent of Σ\mat{\Sigma}), and is sampled, evaluated and whitened with a single Cholesky factorization.
  • Definition. X\vb{X} is Gaussian if every a⊤X\vb{a}\T\vb{X} is normal (including degenerate). Equivalently φX(t)=exp⁡(it⊤μ−12t⊤Σt)\varphi_{\vb{X}}(\vb{t}) = \exp(i\vb{t}\T\vb{\mu} - \tfrac{1}{2}\vb{t}\T\mat{\Sigma}\vb{t}) and X=dμ+Aε\vb{X} \overset{d}{=} \vb{\mu} + \mat{A}\vb{\eps}. It has a density if and only if Σ≻0\mat{\Sigma} \succ 0; otherwise it lives in an affine subspace.
  • Affine closure. AX+b∼N(Aμ+b,AΣA⊤)\mat{A}\vb{X} + \vb{b} \sim \Normal(\mat{A}\vb{\mu} + \vb{b}, \mat{A}\mat{\Sigma}\mat{A}\T). Marginals, projections and independent sums are corollaries. The root A\mat{A} of Σ\mat{\Sigma} is not unique: two roots differ by an orthogonal matrix.
  • Geometry. Level sets are ellipsoids with semiaxes rλir\sqrt{\lambda_i} in directions ui\vb{u}_i. dM2∼χd2d_M^2 \sim \chi^2_d: coverage of radii 1, 2, 3 is 39 %, 86 %, 99 % in d=2d = 2 and 0.017 %, 5 %, 47 % in d=10d = 10. Mass lives in the shell of radius d\sqrt{d}.
  • Numerics. Cholesky for sampling (μ+Lε\vb{\mu} + \mat{L}\vb{\eps}, never Σε\mat{\Sigma}\vb{\eps}), forward substitution for dM2d_M^2, diagonal log sums for log⁡det⁡\log\det. Cholesky fails loudly where inversion lies; if it fails, apply and document jitter.
  • Whitening. W=QΣ−1/2\mat{W} = \mat{Q}\mat{\Sigma}^{-1/2} with orthogonal Q\mat{Q}: PCA, ZCA (moves data least) and Cholesky (sequential: Lii2L_{ii}^2 is conditional variance given the past).
  • Independence. Uncorrelated implies independent only within a joint Gaussian; normal marginals do not suffice (Y=±XY = \pm X has Corr⁡=2Fχ32(c2)−1\operatorname{Corr} = 2F_{\chi^2_3}(c^2) - 1, zero at c∗≈1.538c^* \approx 1.538).
  • Rotational invariance. Qε∼N(0,I)\mat{Q}\vb{\eps} \sim \Normal(\vb{0}, \mat{I}); ∥ε∥\norm{\vb{\eps}} and ε/∥ε∥\vb{\eps}/\norm{\vb{\eps}} are independent and direction is uniform on the sphere.

The next lesson uses all this to marginalize and condition: Kalman filter and Gaussian-process prediction formulas come from completing squares on the same object (Gaussian II).