Course contents 02 / 34

02 / 34 · Foundations

Multivariate Gaussian distributions

Sampling any Gaussian from standard noise with a Cholesky factor, why the same map makes samples differentiable, and how to store and evaluate a Gaussian whose parameters an optimizer can change freely.

Prerequisites

Linear algebra · Probability

On this page 6

Suppose an optimizer trains the covariance matrix of a 2-D Gaussian directly. It starts at (10.50.51)\begin{pmatrix} 1 & 0.5 \\ 0.5 & 1 \end{pmatrix}, and one gradient step moves the off-diagonal entries to 1.21.2. The new matrix has eigenvalues 2.22.2 and −0.2-0.2: it would give one direction a negative variance, so it is no covariance at all, and the model breaks.

The fitting experiments of the next notes need a Gaussian that survives any gradient step, that we can sample from, and whose samples move smoothly when its parameters move. A triangular square root of the covariance gives the second and third. Storing its diagonal through an exponential gives the first: then every value of the trained numbers is a valid covariance. The density, the ellipses and the affine maps of the Gaussian are in the Probability course’s multivariate Gaussian note; here we use them.

The covariance matrix#

For a random vector X=(X1,X2)⊤X = (X_1, X_2)^\top with mean μ=E[X]\boldsymbol\mu = \mathbb E[X], the covariance matrix is

Σ=E[(X−μ)(X−μ)⊤]=(σ12ρ σ1σ2ρ σ1σ2σ22),\begin{aligned} \boldsymbol\Sigma &= \mathbb E\big[(X-\boldsymbol\mu)(X-\boldsymbol\mu)^{\top}\big] \\ &= \begin{pmatrix} \sigma_1^2 & \rho\,\sigma_1\sigma_2 \\ \rho\,\sigma_1\sigma_2 & \sigma_2^2 \end{pmatrix}, \end{aligned}

where ρ\rho is the correlation of X1X_1 and X2X_2. It is symmetric, and positive semidefinite because Var⁡(a⊤X)=a⊤Σ a≥0\operatorname{Var}(\mathbf a^{\top}X) = \mathbf a^{\top}\boldsymbol\Sigma\,\mathbf a \ge 0 for every vector a\mathbf a. We write X∼N(μ,Σ)X \sim \mathcal N(\boldsymbol\mu, \boldsymbol\Sigma), with the covariance, never the standard deviation, as the second argument. The running example has μ=0\boldsymbol\mu = \mathbf 0, unit variances and ρ=0.5\rho = 0.5.

Two variances alone cannot describe this cloud. Its axis variances are both 1, exactly those of the round N(0,I)\mathcal N(\mathbf 0, \mathbf I); only the off-diagonal entry records that the cloud leans along the diagonal x1=x2x_1 = x_2.

Figure

A diagonal matrix only stretches along the axes; covariance tilts the cloud

Axis-aligned Gaussian cloud next to a tilted, correlated cloudTwo scatter plots of 2-D Gaussian samples with their 1-sigma and 2-sigma ellipses. The left cloud has covariance diag(1.5, 0.5): it is wider than tall and aligned with the axes. Braces under the horizontal axis and beside the vertical axis mark the spreads, each spanning plus and minus one standard deviation and labelled plus or minus the square root of Var(X1) = 1.5 and of Var(X2) = 0.5. The right cloud has covariance with unit variances and covariance 0.5. It leans along the diagonal x1 = x2. Its braces span plus and minus 1 along both axes, because Var(X1) = Var(X2) = 1, the same as for an untilted circle. Arrows along the eigenvectors show the semi-axes of the 1-sigma ellipse, of lengths square root of 1.5 along the diagonal and square root of 0.5 across it.Variances onlyCov(X₁, X₂) = 0x₁x₂1σ2σ±√Var(X₁) = ±√1.5±√Var(X₂)= ±√0.5With covarianceCov(X₁, X₂) = 0.5x₁x₂1σ2σ±√Var(X₁) = ±1±√Var(X₂)= ±1x₁ = x₂√1.5√0.5Axis-aligned Gaussian cloud next to a tilted, correlated cloudTwo scatter plots of 2-D Gaussian samples with their 1-sigma and 2-sigma ellipses. The left cloud has covariance diag(1.5, 0.5): it is wider than tall and aligned with the axes. Braces under the horizontal axis and beside the vertical axis mark the spreads, each spanning plus and minus one standard deviation and labelled plus or minus the square root of Var(X1) = 1.5 and of Var(X2) = 0.5. The right cloud has covariance with unit variances and covariance 0.5. It leans along the diagonal x1 = x2. Its braces span plus and minus 1 along both axes, because Var(X1) = Var(X2) = 1, the same as for an untilted circle. Arrows along the eigenvectors show the semi-axes of the 1-sigma ellipse, of lengths square root of 1.5 along the diagonal and square root of 0.5 across it.Variances onlyCov(X₁, X₂) = 0x₁x₂1σ2σ±√Var(X₁) = ±√1.5±√Var(X₂)= ±√0.5With covarianceCov(X₁, X₂) = 0.5x₁x₂1σ2σ±√Var(X₁) = ±1±√Var(X₂)= ±1x₁ = x₂√1.5√0.5
Both clouds are drawn from the same 260 standard-normal pairs. Left: Σ = diag(1.5, 0.5), independent coordinates. Right: Σ = [[1, 0.5], [0.5, 1]], the same cloud rotated by 45°: both axis variances are 1, and only the off-diagonal entry records the tilt. Braces span ±1 standard deviation; curves are the 1σ and 2σ ellipses.

Sampling: from standard noise to any Gaussian#

In one dimension, X=μ+σZX = \mu + \sigma Z with Z∼N(0,1)Z \sim \mathcal N(0, 1) and σ>0\sigma > 0 has distribution N(μ,σ2)\mathcal N(\mu, \sigma^2): stretch standard noise by σ\sigma, then shift it by μ\mu. The change-of-variables formula with g(z)=μ+σzg(z) = \mu + \sigma z and g′=σg' = \sigma gives the density φ((x−μ)/σ)/σ\varphi\big((x - \mu)/\sigma\big)/\sigma, where φ\varphi is the standard normal density; this is the N(μ,σ2)\mathcal N(\mu, \sigma^2) density.

Figure

Standardization and its inverse in one dimension

Standard normal density and a shifted, stretched normal densityTwo bell curves on one axis. The taller grey curve is the standard normal Z ~ N(0, 1), centred at 0. The lower, wider red curve is X ~ N(2, 1.5²), centred at mu = 2 with a horizontal arrow of length sigma = 1.5 drawn at the inflection height. The point z = 1 on the axis is connected by a curved arrow labelled X = mu + sigma Z to the point x = 3.5, and a second arrow below the axis labelled Z = (X − mu) / sigma goes back.−3−2−101234567Z ~ N(0, 1)X ~ N(μ, σ²)μ = 2, σ = 1.5μσX = μ + σZZ = (X − μ) / σStandard normal density and a shifted, stretched normal densityTwo bell curves on one axis. The taller grey curve is the standard normal Z ~ N(0, 1), centred at 0. The lower, wider red curve is X ~ N(2, 1.5²), centred at mu = 2 with a horizontal arrow of length sigma = 1.5 drawn at the inflection height. The point z = 1 on the axis is connected by a curved arrow labelled X = mu + sigma Z to the point x = 3.5, and a second arrow below the axis labelled Z = (X − mu) / sigma goes back.−20246Z ~ N(0, 1)X ~ N(μ, σ²)μ = 2, σ = 1.5μσX = μ + σZZ = (X − μ) / σ
The point z = 1 of the standard normal maps to x = μ + σz = 3.5 for μ = 2, σ = 1.5; dividing (x − μ) by σ maps it back. Both points sit one standard deviation above their own mean.

In dd dimensions a matrix plays the role of σ\sigma. For any A\mathbf A with AA⊤=Σ\mathbf A\mathbf A^{\top} = \boldsymbol\Sigma and Z∼N(0,I)Z \sim \mathcal N(\mathbf 0, \mathbf I),

 X=μ+AZ∼N(μ,Σ) \boxed{\,X = \boldsymbol\mu + \mathbf A Z \sim \mathcal N(\boldsymbol\mu, \boldsymbol\Sigma)\,}

The mean is μ+A E[Z]=μ\boldsymbol\mu + \mathbf A\,\mathbb E[Z] = \boldsymbol\mu by linearity of expectation. The covariance follows from the definition, with X−μ=AZX - \boldsymbol\mu = \mathbf A Z:

Cov⁡(X)=E[AZ(AZ)⊤]=A E[ZZ⊤] A⊤(linearity)=A I A⊤=Σ.\begin{aligned} \operatorname{Cov}(X) &= \mathbb E\big[\mathbf A Z (\mathbf A Z)^{\top}\big] \\ &= \mathbf A\, \mathbb E\big[Z Z^{\top}\big]\, \mathbf A^{\top} && \text{(linearity)} \\ &= \mathbf A\,\mathbf I\,\mathbf A^{\top} = \boldsymbol\Sigma . \end{aligned}

That the result is Gaussian at all is shown in the affine maps section of the Probability course: by the change of variables for an invertible A\mathbf A, and by the characteristic function for any A\mathbf A.

Many matrices satisfy AA⊤=Σ\mathbf A\mathbf A^{\top} = \boldsymbol\Sigma. Two are standard. The symmetric square root Σ1/2=UΛ1/2U⊤\boldsymbol\Sigma^{1/2} = \mathbf U\boldsymbol\Lambda^{1/2}\mathbf U^{\top} comes from the eigendecomposition Σ=UΛU⊤\boldsymbol\Sigma = \mathbf U\boldsymbol\Lambda\mathbf U^{\top}, with U\mathbf U orthogonal by the spectral theorem. It exists for every covariance, singular ones included: the eigenvalues of a positive semidefinite matrix are ≥0\ge 0, so their roots are real, and U⊤U=I\mathbf U^{\top}\mathbf U = \mathbf I gives Σ1/2Σ1/2=UΛU⊤\boldsymbol\Sigma^{1/2}\boldsymbol\Sigma^{1/2} = \mathbf U\boldsymbol\Lambda\mathbf U^{\top}. The Cholesky factor L\mathbf L is the unique lower-triangular matrix with positive diagonal and LL⊤=Σ\mathbf L\mathbf L^{\top} = \boldsymbol\Sigma; it exists when Σ\boldsymbol\Sigma is positive definite (Golub and Van Loan, 2013, §4.2; derived in the Cholesky factorization).

For the running example the eigenvalues are 1.51.5 and 0.50.5, with eigenvectors along (1,1)(1, 1) and (1,−1)(1, -1), and the two roots are

Σ1/2≈(0.9660.2590.2590.966),L=(100.50.75)≈(100.50.866).\begin{aligned} \boldsymbol\Sigma^{1/2} &\approx \begin{pmatrix} 0.966 & 0.259 \\ 0.259 & 0.966 \end{pmatrix}, \\ \mathbf L &= \begin{pmatrix} 1 & 0 \\ 0.5 & \sqrt{0.75} \end{pmatrix} \approx \begin{pmatrix} 1 & 0 \\ 0.5 & 0.866 \end{pmatrix}. \end{aligned}

Both turn independent noise into the same correlated cloud. Code uses L\mathbf L: a finite algorithm computes it in about d3/3d^3/3 operations (the Cholesky factorization). An eigendecomposition needs an iterative method, because eigenvalues are roots of a polynomial of degree dd, and for d≥5d \ge 5 such roots have no general formula in radicals (the Abel–Ruffini theorem). In PyTorch, MultivariateNormal stores the Cholesky factor of the covariance it receives and samples μ+LZ\boldsymbol\mu + \mathbf L Z (PyTorch source).

Figure

Sampling any Gaussian from standard noise

Three-step sampling pipeline: Z, then A Z, then μ + A ZThree scatter plots in the same window. First, a round cloud of standard normal noise Z centred at the origin with circular 1-sigma and 2-sigma contours. An arrow labelled times A, stretch and shear, leads to the second panel, where the cloud A Z leans along the diagonal with elliptical contours; A is the Cholesky factor L with rows (1, 0) and (0.5, 0.866). An arrow labelled plus mu, shift, leads to the third panel, where the same tilted cloud is centred at mu = (1.5, 1), marked with a cross and an arrow from the origin. One highlighted example point moves from z = (2, 1) to A z = (2, 1.87) and then to μ + A z = (3.5, 2.87).standard noisezZ ~ N(0, I)stretch and shearAzAZ ~ N(0, AAᵀ)shiftμμ + Azμ + AZ ~ N(μ, Σ)× A+ μA = L =100.50.866μ = (1.5, 1)LLᵀ = Σ = [[1, 0.5], [0.5, 1]]Three-step sampling pipeline: Z, then A Z, then μ + A ZThree scatter plots in the same window. First, a round cloud of standard normal noise Z centred at the origin with circular 1-sigma and 2-sigma contours. An arrow labelled times A, stretch and shear, leads to the second panel, where the cloud A Z leans along the diagonal with elliptical contours; A is the Cholesky factor L with rows (1, 0) and (0.5, 0.866). An arrow labelled plus mu, shift, leads to the third panel, where the same tilted cloud is centred at mu = (1.5, 1), marked with a cross and an arrow from the origin. One highlighted example point moves from z = (2, 1) to A z = (2, 1.87) and then to μ + A z = (3.5, 2.87).standard noisezZ ~ N(0, I)stretch and shearAzAZ ~ N(0, AAᵀ)shiftμμ + Azμ + AZ ~ N(μ, Σ)× A+ μA = L =100.50.866μ = (1.5, 1)LLᵀ = Σ = [[1, 0.5], [0.5, 1]]
Standard normal pairs Z are multiplied by the Cholesky factor L of Σ = [[1, 0.5], [0.5, 1]] and shifted by μ = (1.5, 1). The amber point z = (2, 1) moves to Lz = (2, 1.87) and then to μ + Lz = (3.5, 2.87). Curves are the 1σ and 2σ contours; all panels share one window.

The reparameterization view#

The map x=μ+Lεx = \boldsymbol\mu + \mathbf L\varepsilon does more than sample. It moves all randomness into ε∼N(0,I)\varepsilon \sim \mathcal N(\mathbf 0, \mathbf I), which does not depend on the parameters, and leaves a deterministic, differentiable function of μ\boldsymbol\mu and L\mathbf L. So the gradient of an expectation under the Gaussian becomes an expectation of a gradient:

∇μ,L Ex∼N(μ,LL⊤)[f(x)]=∇μ,L Eε[f(μ+Lε)]=Eε[∇μ,L f(μ+Lε)].\begin{aligned} &\nabla_{\boldsymbol\mu, \mathbf L}\, \mathbb E_{x \sim \mathcal N(\boldsymbol\mu, \mathbf L\mathbf L^\top)}\big[f(x)\big] \\ &\quad= \nabla_{\boldsymbol\mu, \mathbf L}\, \mathbb E_{\varepsilon}\big[f(\boldsymbol\mu + \mathbf L\varepsilon)\big] \\ &\quad= \mathbb E_{\varepsilon}\big[\nabla_{\boldsymbol\mu, \mathbf L}\, f(\boldsymbol\mu + \mathbf L\varepsilon)\big] . \end{aligned}

The first step uses only that μ+Lε\boldsymbol\mu + \mathbf L\varepsilon has the distribution N(μ,LL⊤)\mathcal N(\boldsymbol\mu, \mathbf L\mathbf L^\top), so both expectations are the same number. The second moves the gradient inside an expectation over a distribution that no longer depends on the parameters. This differentiation under the integral sign holds when ff is differentiable and its gradient is bounded by a function integrable against the noise density, as for any ff whose gradient grows at most polynomially.

The right side is estimated by averaging over a few draws of ε\varepsilon, and backpropagation handles it like any other layer. A sampler called as a black box would give no gradient at all (Kingma and Welling, 2014; Isachenko, lecture 4).

A one-dimensional check: for x=m+sεx = m + s\varepsilon and f(x)=x2f(x) = x^2, the expectation is E[x]2+Var⁡(x)=m2+s2\mathbb E[x]^2 + \operatorname{Var}(x) = m^2 + s^2, so its derivative in ss is 2s2s. The pathwise estimate averages f′(x) ∂x/∂sf'(x)\,\partial x/\partial s, and Eε=0\mathbb E\varepsilon = 0, Eε2=1\mathbb E\varepsilon^2 = 1 give

Eε[2(m+sε) ε]=2m Eε+2s Eε2=2s.\begin{aligned} \mathbb E_\varepsilon\big[2(m + s\varepsilon)\,\varepsilon\big] &= 2m\,\mathbb E\varepsilon + 2s\,\mathbb E\varepsilon^2 \\ &= 2s . \end{aligned}

With m=1m = 1, s=0.5s = 0.5 and 100,000 draws the average is 1.0031.003 against the exact 11. The same move is the reparameterization trick of the VAE and the one-step noising formula of diffusion models.

Gaussians in PyTorch#

To let an optimizer change the covariance freely, we train the Cholesky factor through three unconstrained numbers a,b,ca, b, c:

L=(ea0bec),Σ=LL⊤=(e2ab eab eab2+e2c).\begin{aligned} \mathbf L &= \begin{pmatrix} e^{a} & 0 \\ b & e^{c} \end{pmatrix}, \\ \boldsymbol\Sigma = \mathbf L\mathbf L^{\top} &= \begin{pmatrix} e^{2a} & b\,e^{a} \\ b\,e^{a} & b^2 + e^{2c} \end{pmatrix}. \end{aligned}

The exponential keeps the diagonal positive, so L\mathbf L is invertible and v⊤Σv=∥L⊤v∥2>0\mathbf v^{\top}\boldsymbol\Sigma\mathbf v = \|\mathbf L^{\top}\mathbf v\|^2 > 0 for every v≠0\mathbf v \ne \mathbf 0. Every gradient step on a,b,ca, b, c lands on a valid covariance, which repairs the opening example. The running example is a=0a = 0, b=0.5b = 0.5, c=ln⁡0.75≈−0.144c = \ln\sqrt{0.75} \approx -0.144, and a=b=c=0a = b = c = 0 gives Σ=I\boldsymbol\Sigma = \mathbf I.

The same factor gives the log-density without inverting Σ\boldsymbol\Sigma. Start from the Gaussian density, log⁡p(x)=−12(x−μ)⊤Σ−1(x−μ)−12log⁡det⁡(2πΣ)\log p(\mathbf x) = -\tfrac12 (\mathbf x - \boldsymbol\mu)^{\top}\boldsymbol\Sigma^{-1}(\mathbf x - \boldsymbol\mu) - \tfrac12\log\det(2\pi\boldsymbol\Sigma). Inverting the product LL⊤\mathbf L\mathbf L^{\top} gives Σ−1=L−⊤L−1\boldsymbol\Sigma^{-1} = \mathbf L^{-\top}\mathbf L^{-1}, so the quadratic form is ∥L−1(x−μ)∥2\|\mathbf L^{-1}(\mathbf x - \boldsymbol\mu)\|^2. The determinant of a product is the product of determinants, and that of a triangular matrix is the product of its diagonal, so det⁡Σ=∏iLii2\det\boldsymbol\Sigma = \prod_i L_{ii}^2. Together,

log⁡p(x)=−12∥L−1(x−μ)∥2−∑i=1dlog⁡Lii−d2log⁡2π.\begin{aligned} \log p(\mathbf x) ={}& -\tfrac12 \big\|\mathbf L^{-1}(\mathbf x - \boldsymbol\mu)\big\|^2 \\ &- \sum_{i=1}^d \log L_{ii} - \tfrac d2 \log 2\pi . \end{aligned}

The vector L−1(x−μ)\mathbf L^{-1}(\mathbf x - \boldsymbol\mu) comes from one triangular solve. This is how MultivariateNormal.log_prob computes it, and passing the factor as scale_tril=L skips the re-factorization that covariance_matrix=L @ L.T would trigger. In PyTorch the raw numbers are tensors created with requires_grad=True; the target distribution is built from fixed tensors.

import numpy as np
from scipy.linalg import solve_triangular
from scipy.stats import multivariate_normal

a, b, c = 0.0, 0.5, np.log(np.sqrt(0.75))      # raw parameters: any real numbers
L = np.array([[np.exp(a), 0.0],
              [b, np.exp(c)]])                 # lower triangular, positive diagonal
mu, Sigma = np.zeros(2), L @ L.T
print(L.round(3).ravel(), Sigma.round(3).ravel())   # Sigma = [[1, 0.5], [0.5, 1]]

def log_density(x, mu, L):
    w = solve_triangular(L, (x - mu).T, lower=True)  # L^{-1}(x - mu): no inverse of Sigma
    d = len(mu)
    return -0.5 * (w**2).sum(0) - np.log(np.diag(L)).sum() - 0.5 * d * np.log(2 * np.pi)

x = np.array([[0.0, 0.0], [1.0, 1.0], [1.0, -1.0]])   # the centre, along the tilt, across it
print(log_density(x, mu, L).round(4))
print(multivariate_normal(mu, Sigma).logpdf(x).round(4))   # the same numbers

rng = np.random.default_rng(0)
eps = rng.standard_normal((100_000, 2))
samples = mu + eps @ L.T                       # x = mu + L eps, row by row
print(np.cov(samples.T).round(2).ravel())

# reparameterization: x = m + s * eps, f(x) = x^2, so E f = m^2 + s^2 and dE/ds = 2s
m, s = 1.0, 0.5
e = rng.standard_normal(100_000)
print((2 * (m + s * e) * e).mean().round(3))   # pathwise estimate of 2s = 1
[1.    0.    0.5   0.866] [1.  0.5 0.5 1. ]
[-1.694  -2.3607 -3.694 ]
[-1.694  -2.3607 -3.694 ]
[1.  0.5 0.5 1. ]
1.003

The points (1,1)(1, 1) and (1,−1)(1, -1) are equally far from the centre, yet the one along the tilt has log-density −2.36-2.36 and the one across it −3.69-3.69. The fitting experiments start from a fixed target PP and a trainable model QQ built this way:

Figure

Target P and model Q before fitting

Two Gaussian sample clouds plotted as dotsA square plot with both axes from −10 to 10. A red cloud of 400 dots is centred at (−5, −5), labelled target distribution P with mean (−5, −5), identity covariance and requires_grad False. A blue cloud of 400 dots is centred at the origin, labelled train distribution Q with mean (0, 0) and covariance L L transpose equal to the identity at initialization; its parameters have requires_grad True. Dots near each centre are drawn more intensely because their own density, p(x) for P and q(x) for Q, is higher.−10−50510−10−50510train distr Qμ = (0, 0), Σ = LLᵀ = Irequires_grad=True:μ and L are trainedtarget distr Pμ = (−5, −5), Σ = Irequires_grad=False:fixedx₁x₂stronger colour = higher density:p(x) for P, q(x) for QTwo Gaussian sample clouds plotted as dotsA square plot with both axes from −10 to 10. A red cloud of 400 dots centred at (−5, −5) is the fixed target distribution P with identity covariance (requires_grad False). A blue cloud centred at the origin is the trainable distribution Q with covariance L L transpose equal to the identity at initialization (requires_grad True). Dots near each centre are drawn more intensely, following p(x) for P and q(x) for Q.−10−50510−10−50510target distr Pμ = (−5, −5), Σ = Irequires_grad=False:fixedtrain distr Qμ = (0, 0), Σ = LLᵀ = Irequires_grad=True:μ and L are trainedx₁x₂stronger colour = higher density: p(x) for P, q(x) for Q
400 samples each of the fixed target P = N((−5, −5), I) and of the trainable model Q, initialized at N(0, I), on the plot limits (−10, 10). Each dot is coloured by its own cloud’s density, p(x) for target samples and q(x) for model samples, so stronger colour means higher density.

Where the full factor breaks#

A full covariance in dd dimensions has d(d+1)/2d(d+1)/2 free numbers. For a VAE with a 128-dimensional latent code that is 8,256 numbers per input, which an encoder would have to predict for every image. VAE encoders therefore output a diagonal covariance: dd variances, an L\mathbf L with nothing below the diagonal, and a cloud that can stretch along the axes but never tilt, like the left panel of the first figure.

A singular covariance has no Cholesky factor at all. If one coordinate copies another, Σ=(1111)\boldsymbol\Sigma = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}, and np.linalg.cholesky stops with “Matrix is not positive definite”; torch.linalg.cholesky fails the same way. Estimated covariances hit this when features are collinear or when there are fewer samples than dimensions. The usual repair adds a small jitter ϵI\epsilon\mathbf I. With ϵ=10−6\epsilon = 10^{-6} the factor is (1010.0014)\begin{pmatrix} 1 & 0 \\ 1 & 0.0014 \end{pmatrix}: a valid Gaussian, flattened almost onto the diagonal line. Its log-density is 4.724.72 at the origin, against −1.84-1.84 for N(0,I)\mathcal N(\mathbf 0, \mathbf I), and −20.28-20.28 at (0,0.01)(0, 0.01), a hundredth off the line.

import numpy as np
S = np.array([[1.0, 1.0], [1.0, 1.0]])          # X2 = X1: a singular covariance
try:
    np.linalg.cholesky(S)
except np.linalg.LinAlgError as err:
    print("LinAlgError:", err)
L = np.linalg.cholesky(S + 1e-6 * np.eye(2))    # a small jitter on the diagonal
print(L.round(4).ravel())
LinAlgError: Matrix is not positive definite
[1.     0.     1.     0.0014]

The trained parametrization cannot produce a singular matrix, because eae^{a} and ece^{c} are never zero. It can still drift towards one. Write the second coordinate of x=μ+Lε\mathbf x = \boldsymbol\mu + \mathbf L\varepsilon through the first: ε1=(x1−μ1)e−a\varepsilon_1 = (x_1 - \mu_1)e^{-a}, so

x2=μ2+b ε1+ecε2=μ2+b e−a(x1−μ1)+ecε2.\begin{aligned} x_2 &= \mu_2 + b\,\varepsilon_1 + e^{c}\varepsilon_2 \\ &= \mu_2 + b\,e^{-a}(x_1 - \mu_1) + e^{c}\varepsilon_2 . \end{aligned}

If the training points lie on a line x2=α+βx1x_2 = \alpha + \beta x_1, choose b e−a=βb\,e^{-a} = \beta and μ2−βμ1=α\mu_2 - \beta\mu_1 = \alpha. Then ε2=0\varepsilon_2 = 0 at every point, the quadratic term of the log-density loses its second component, and the term −log⁡L22=−c-\log L_{22} = -c grows without limit as c→−∞c \to -\infty. Two points in the plane always lie on a line, so with no more points than dimensions maximum likelihood follows the same path: the memorizing fit of the first note, in miniature.

Notebook#

The Distances between distributions notebook of the HSE-LAMBDA Deep Generative Models course sets up the Gaussians used here. Parts are named by the notebook’s own headings (its cells count from 1, markdown included), and quoted numbers come from the run saved with the course.

  • The helper functions draw a scatter plot on the window (−10,10)2(-10, 10)^2 and implement the parametrization above: get_parameters creates the mean (μ,μ)(\mu, \mu) and raw entries a=c=ln⁡σa = c = \ln\sigma, b=0b = 0; create_distr assembles L\mathbf L and passes LL⊤\mathbf L\mathbf L^{\top} as covariance_matrix, where scale_tril=L would avoid a second factorization.
  • The toy example with a single Gaussian target creates the fixed target N((−5,−5),I)\mathcal N((-5,-5), \mathbf I) with 1000 samples and the model initialized at N(0,I)\mathcal N(\mathbf 0, \mathbf I), and plots both coloured by their own densities. The fit itself is described in Fitting distributions with KL.

Next#

With a target and a trainable model in hand, the remaining question is what “fit” means: we need a number that says how far QQ is from PP. The first candidate is the KL divergence, built from surprise and entropy in Entropy, cross-entropy and KL divergence.

References#