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
- 04Covariance matrixCharacteristic functionUniqueness and Fourier inversionChange of variables for densitiesUnivariate normal distributionExponential, gamma and chi-squared distributionsIndependent random variablesPearson correlation
- 02Spectral theoremPositive definite matrixCholesky decompositionTrace and determinant via eigenvalues
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 points is an -dimensional vector ; prediction conditions that vector, and the numerical difficulty is factorizing .
- Kalman filter. State and observation are Gaussian; each step is an affine transformation followed by conditioning.
- Variational autoencoders. The encoder produces with : this reparameterization permits differentiation through sampling.
- Diffusion. The noise process is , 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 assets, factor the covariance matrix and write .
All six share one recipe, , 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 , 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 is normal and therefore has moments of all orders, so and exist (lesson 8). By linearity, and : every projection is , and is symmetric positive semidefinite because these variances are nonnegative.
Proof
. Fix . Since and the characteristic function of is (also when ), evaluating at :
. For and , , the characteristic function of . By uniqueness of the characteristic function, is normal. This holds for every : is Gaussian, and its moments are those in the definition because they are read from each projection’s law.
∎An existence question remains: given and any positive semidefinite , is there really a Gaussian vector with those parameters? Yes, and the construction is the recipe for the whole lesson.
Proof
Let . Because the are independent, the expectation of the product is the product of expectations:
This is the form of point (2) of the previous theorem with : is Gaussian with those parameters. The converse is uniqueness: vectors with the same characteristic function have the same law. Finally, the spectral theorem gives with , and satisfies .
∎Thus the three descriptions of a Gaussian are equivalent: by projections (the definition), by characteristic function, and as an affine image of white noise, . 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 is positive definite, the Gaussian has a density with respect to Lebesgue measure on , 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.
Notice that the only quantity depending on is the exponent, and the normalization factor is : a matrix stretching space by a factor dilutes density by the same factor, keeping total mass one.
Proof
Let . Then , so almost surely. Taking a finite basis of , is almost surely orthogonal to the whole kernel, i.e. it lies in (since is symmetric). A proper affine subspace has Lebesgue measure zero but probability one under the law of : 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 with normal , 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 -dimensional Lebesgue measure, and the theory works the same way; one must simply avoid writing .
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 , is an affine function of a linear combination of , which is normal; an affine function of a normal (including zero slope) is normal. Hence is Gaussian. Its mean is by linearity, and its covariance . A Gaussian with those parameters has that law by the characteristic function theorem.
∎Almost all Gaussian calculations apply this one line:
- Marginals. If selects coordinates, the subvector is Gaussian with the corresponding submatrix of . Each coordinate is .
- Projections. , which is the definition.
- Sums. If and are independent Gaussians, is Gaussian (its characteristic function is the product of two Gaussians) and hence .
- Sampling. is the recipe for simulating .
- Whitening. If , .
Now check the theorem hands-on. Drag the two columns of and see what happens to the cloud.
What you should have seen:
- The ellipse and are all that matter. Rotating the input with changes each point but preserves the cloud’s shape and statistics, because . Equivalently, the square root of is not unique, and any two roots differ by an orthogonal matrix.
- Cholesky, symmetric square root and eigenvectors are three roots of the same . Each button completely changes (triangular, symmetric, with orthogonal columns), yet the ellipse does not move a pixel.
- With the “40° rotation” matrix, satisfies : the colored cloud rotates relative to the gray one, but its ellipse remains the unit circle and its law remains . This foreshadows rotational invariance in the last section.
- With aligned columns, and the Gaussian degenerates: all mass falls on a line and is singular. The preceding proposition in action.
Geometry: ellipsoids and Mahalanobis distance
Let have spectral decomposition , and orthonormal columns . Then and the density exponent is
This is the sum of the squared coordinates of in the eigenvector basis, each divided by its variance. Density decreases with this quantity, so its level sets are the sets where it is constant.
The level sets are ellipsoids centered at , with axes in directions and semiaxes : they are the image under of the Euclidean sphere of radius . Eigenvalues are variances and their square roots are the semiaxis lengths of the radius-1 ellipsoid.
Proof
Let and . Then and . Since is a bijection, the ratio is , which by Cauchy-Schwarz is with equality for .
∎This is a useful interpretation: means no linear combination of coordinates sees more than standard deviations from its mean. How much probability is inside those ellipsoids? It depends only on and , not .
Proof
Let . By affine closure, , and its characteristic function is : it factorizes, so coordinates are independent and . Then is a sum of independent variables with law (change of variables with ). Independent gammas with the same rate add their shapes (exponential-gamma family), and the sum is .
∎In two dimensions, is an exponential with mean 2 and coverage has closed form: . This interactive shows it and challenges the habit of applying the 68-95-99.7 rule.
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 , not .
- Coverage does not depend on . By the theorem it depends only on and . Sculpting covariance deforms the cloud, but each point travels with its ellipse and remains in the same ring: it is the image under 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 the radius-1 ellipsoid contains 0.017 % of the mass and the radius-3 one only 46.8 %. Mass lives around radius , because .
The table gives exact coverages , which you will verify with SciPy below:
| 95 % radius | ||||
|---|---|---|---|---|
| 1 | 68.27 % | 95.45 % | 99.73 % | 1.960 |
| 2 | 39.35 % | 86.47 % | 98.89 % | 2.448 |
| 3 | 19.87 % | 73.85 % | 97.07 % | 2.795 |
| 5 | 3.74 % | 45.06 % | 89.09 % | 3.327 |
| 10 | 0.017 % | 5.27 % | 46.79 % | 4.279 |
The observation on mass deserves one more sentence. Since and , the norm concentrates around , in a shell of nearly constant thickness (its standard deviation approaches , as the final section’s cell shows). In dimension 100, mass is at distance 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 is an algorithm. Cholesky sampling factorizes once (Cholesky factorization, with lower-triangular and positive diagonal, unique if ), then for each sample generates standard normals and computes a matrix-vector product. Factorization costs about operations and each sample . Correctness follows from the existence theorem: gives the right covariance.
The same evaluates the log density. For , the logarithm of the density is
The vector is obtained by solving a triangular system by forward substitution, at cost , and the log determinant comes from the diagonal: . Neither nor is ever formed. The reasons, in order of importance:
- The determinant overflows or underflows. With and variances of order , , below the smallest
float64():np.linalg.detreturns0.0and its logarithm gives . Summing logarithms avoids that problem. - Cholesky fails loudly; the inverse lies silently. If is not positive definite (because of rounding or a modeling error), Cholesky raises an exception.
np.linalg.invreturns a matrix of numbers, and the quadratic form can be negative, impossible for a squared distance. With , it is a sum of squares. - Cost. Factorization costs ; forming the inverse, about , six times more.
- Reuse. The same supports sampling, evaluation and whitening.
An honest caveat: Cholesky’s numerical stability is not magic. For with very large condition number , relative error in is of order with either method; the advantages above are structural. When reaches , nothing remains to save: the matrix is numerically singular and the model must change.
The usual remedy is jitter (or nugget): factorize with small , around times the mean diagonal. This is not meaningless: is the covariance of , 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.
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 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:
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: with variances of order . Then the covariance matrix of a Gaussian process with Gaussian kernel on 40 points in , a textbook case: mathematically positive definite, numerically singular.
# 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 , 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: .
Whitening: three ways to undo a covariance
We used to turn a Gaussian into a standard one. This operation, widely used outside probability, has a name and many variants.
Proof
is equivalent to , meaning is orthogonal. Solving gives .
∎There is rotational freedom, with three canonical choices of :
| Method | Matrix | Property | |
|---|---|---|---|
| PCA | rotates to principal axes and scales them; allows ordering by variance and discarding | ||
| ZCA | symmetric; moves the data least | ||
| Cholesky | triangular: coordinate depends only on the first |
Proof
With , . Maximize with orthogonal . Orthogonal matrix entries satisfy and , so the sum is , with equality if and only if every . An orthogonal matrix with ones on the diagonal is the identity, i.e. .
∎Cholesky has a distinctive interpretation: sequential whitening. Since is lower triangular, is a combination of ; and since is itself a combination of , which are uncorrelated with , it follows that : the residual from predicting using its predecessors ( projection). Thus is the variance of that residual, which for a Gaussian is the conditional variance of given the past (Gaussian conditional expectation is linear, as the next lesson shows), and 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.
What you should have seen:
- All three whiten. Readouts confirm 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 “ first” to “ first” changes the output, and both are valid whitenings.
- Whitening is affine, so it preserves Gaussianity. If data are Gaussian, the output is : independent components. Otherwise, uncorrelated does not imply independent, as we see next.
The same experiment in three dimensions, checking that the three matrices are for an orthogonal , ZCA distorts less and Cholesky is triangular:
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, , so the quadratic form separates: . Therefore
The right side is the characteristic function of the product law . 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.
What you should have seen:
- The scatter plot is an X, not an ellipse. A joint Gaussian with marginals and correlation would be elliptical; here all mass lies on two lines.
- Two identical histograms for and , for each : no inspection of marginals reveals the problem.
- The clearest witness is , with a peak at 0 ranging from almost all mass (small ) to none (large ).
- Correlation crosses zero at despite total dependence. Lack of correlation measures only linear dependence.
Rotational invariance and uniform directions
With , the Gaussian is as symmetric as possible, and that symmetry has far-reaching consequences.
Proof
The first statement is affine closure: . For the second, the density of is with , a function of radius alone. In polar coordinates , Lebesgue measure is , with sphere surface measure, so the joint density of is proportional to . It factorizes: and are independent, has constant density relative to (uniform), and has density , that of the square root of a .
∎This is the cheapest way to sample points uniformly on the sphere: generate 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 and 0.25 % in . 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 coordinate of a point uniform on sphere is uniform on (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:
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 .
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 , unlike Cholesky. SciPy supports singular covariances with allow_singular=True, evaluating density in the subspace where the law lives:
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 with fixed as external noise, making the sample a differentiable function of and . The cell checks gradients of , equal to and (with lower-triangular ), 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.
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))npm run lab and open the connection link.Both estimators are unbiased and give , 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
Step 1 of 4. Which function do you calculate?
Step 1 of 5. What is the first step?
More than one answer may be correct.
More than one answer may be correct.
np.linalg.cholesky raises LinAlgError: Matrix is not positive definite. What do you do?mvn_logpdf(x, mu, L), where L is the lower Cholesky factor of (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
passSummary
- Definition. is Gaussian if every is normal (including degenerate). Equivalently and . It has a density if and only if ; otherwise it lives in an affine subspace.
- Affine closure. . Marginals, projections and independent sums are corollaries. The root of is not unique: two roots differ by an orthogonal matrix.
- Geometry. Level sets are ellipsoids with semiaxes in directions . : coverage of radii 1, 2, 3 is 39 %, 86 %, 99 % in and 0.017 %, 5 %, 47 % in . Mass lives in the shell of radius .
- Numerics. Cholesky for sampling (, never ), forward substitution for , diagonal log sums for . Cholesky fails loudly where inversion lies; if it fails, apply and document jitter.
- Whitening. with orthogonal : PCA, ZCA (moves data least) and Cholesky (sequential: is conditional variance given the past).
- Independence. Uncorrelated implies independent only within a joint Gaussian; normal marginals do not suffice ( has , zero at ).
- Rotational invariance. ; and 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).