Why a standard Gaussian?
Maximum entropy, separability and cheap primitives: three reasons the target is N(0, I)
03 · Why a standard Gaussian?¶
Every notebook so far has mapped data to a standard Gaussian, the base of (4), without asking why that destination. Why not a uniform, a Laplace or a heavy-tailed base? The choice is not arbitrary: the standard Gaussian earns its place through three properties, and each one buys Gaussianization something concrete.
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import rbig
from flowjax.distributions import Normal, Transformed
from jaxtyping import ArrayLike, Float
from scipy import stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import SCATTER_KW, style_ax, use_compact_figures
from gauss_flows_models.flows import gaussianization_flow
from gauss_flows_models.info_theory import (
gaussian_entropy,
gaussian_total_correlation,
)
# Entropies and log-densities are sums of many logs, so they get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(3)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "matplotlib", "rbig", "gauss_flows_models")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
matplotlib : 3.11.2
rbig : 0.1.16
gauss_flows_models: 0.3.0
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
1. Maximum entropy at a fixed covariance¶
Let have density , mean and covariance , and write for the set of all densities with that mean and covariance. The differential entropy of is , in nats.
Fixing the first two moments, the Gaussian assumes the least about everything else. That makes it the honest target: a Gaussianized dataset says “the mean and covariance are captured, and what remains is structureless”. The proof also names the gap. The negentropy of is
which equals , so it is non-negative and zero exactly when is Gaussian. We compare four unit-variance distributions in one dimension, : their analytic entropies, the analytic negentropy, and an estimate of the negentropy from samples with rbig.negentropy. The Gaussian entropy comes from gaussian_entropy, the closed form (2).
# Shapes: distribution = 4 unit-variance distributions; sample (N) = 10,000 draws of each; state (D_x) = 1
Scalar = Float[ArrayLike, ""]
# b = 1/√2, so a Laplace has unit variance
laplace_scale: Scalar = 1 / np.sqrt(2)
# s = √3/π, so a logistic has unit variance
logistic_scale: Scalar = np.sqrt(3) / np.pi
# a = √3, so U(−a, a) has unit variance
uniform_half_width: Scalar = np.sqrt(3)
# today (gauss_flows)
# H = ½ log det(2πe Σ) with Σ = 1
gaussian_h: float = float(gaussian_entropy(jnp.eye(1)))Each distribution needs a sampler, for the estimate, and its entropy in closed form.
# user
# n draws of each distribution
samplers = {
"Gaussian": lambda n: rng.standard_normal(n),
"Logistic": lambda n: rng.logistic(0, logistic_scale, n),
"Laplace": lambda n: rng.laplace(0, laplace_scale, n),
"Uniform": lambda n: rng.uniform(-uniform_half_width, uniform_half_width, n),
}
# H[p]: ½ log(2πe), log s + 2, 1 + log 2b and log 2a
entropy_by_name = {
"Gaussian": gaussian_h,
"Logistic": np.log(logistic_scale) + 2,
"Laplace": 1 + np.log(2 * laplace_scale),
"Uniform": np.log(2 * uniform_half_width),
}The analytic negentropy follows from the entropies, and rbig estimates it from 10 000 draws of each distribution.
# the distribution names, in a fixed order
names: list[str] = list(samplers)
PerDistribution = Float[ArrayLike, " distribution"]
# H[p] of each distribution, (distribution)
entropy_analytic: PerDistribution = np.array([entropy_by_name[name] for name in names])
# Neg[p] = H[N] − H[p], against the unit-variance Gaussian, (distribution)
negentropy_analytic: PerDistribution = entropy_analytic[0] - entropy_analytic
SampleState = Float[ArrayLike, "sample state"]
# Neg[p] of each distribution, estimated from its draws, (distribution)
negentropy_rbig: PerDistribution = np.zeros(len(names))
for index, name in enumerate(names):
# user
# x ~ p, 10,000 draws as one column, (sample, state)
draws: SampleState = samplers[name](10_000)[:, None]
# today (rbig)
# Neg[p] = H[N(μ̂, σ̂²)] − Ĥ[p], with Ĥ a KDE entropy of the draws
negentropy_rbig[index] = rbig.negentropy(draws)[0]Side by side, the analytic and estimated negentropies of the four distributions:
print("Neg[p] = H[N] - H[p], in nats")
for name, analytic, estimate in zip(
names, negentropy_analytic, negentropy_rbig, strict=True
):
print(f" {name:9s} analytic {analytic:.4f} rbig {estimate:.4f}")Neg[p] = H[N] - H[p], in nats
Gaussian analytic 0.0000 rbig 0.0011
Logistic analytic 0.0144 rbig 0.0163
Laplace analytic 0.0724 rbig 0.0771
Uniform analytic 0.1765 rbig 0.1401
colors = ["C3", "C1", "C2", "C0"]
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
bars = axes[0].bar(names, entropy_analytic, color=colors)
axes[0].axhline(gaussian_h, color="C3", ls="--", lw=1, label="Gaussian entropy")
axes[0].bar_label(bars, fmt="%.3f", padding=3)
axes[0].set(ylabel=r"$\mathbb{H}[p]$ (nats)", ylim=(1.1, 1.48))
axes[0].legend(loc="center right")
style_ax(axes[0])
bars = axes[1].bar(names, negentropy_analytic, color=colors, alpha=0.55)
axes[1].plot(names, negentropy_rbig, "ko", ms=8, label="rbig estimate")
axes[1].set(ylabel=r"$\mathrm{Neg}[p]$ (nats)")
axes[1].legend(loc="upper left")
style_ax(axes[1])
fig.tight_layout()
plt.show()
Figure 1:Left: differential entropy of four unit-variance distributions; the Gaussian has the most. Right: their negentropy, analytic (bars) and estimated from 10 000 samples by rbig (black dots); only the Gaussian’s is zero.
The Gaussian bar is the tallest, and every other distribution has a positive negentropy, a number that says how non-Gaussian it is. The rbig estimates match the analytic values closely except for the uniform, which they underestimate: rbig.negentropy estimates the entropy with a kernel density estimate, which rounds off the uniform’s hard edges and so overstates its entropy. Driving the negentropy to zero is what Gaussianization does, which is why the negentropy doubles as a convergence signal in the iterative methods of later parts.
2. Separability¶
With identity covariance the Gaussian factorises into independent unit-variance coordinates,
where is coordinate of . Independent coordinates carry no shared information, so the total correlation Watanabe, 1960, the gap between the sum of the marginal entropies and the joint entropy,
is zero. Gaussianization is therefore two jobs in one: remove the dependence between coordinates and make each margin standard normal. We watch the dependence disappear on a correlated 2-D Gaussian with correlation : whiten it to with rbig.PCARotation and estimate its total correlation with rbig.total_correlation before and after. That estimator takes the marginal entropies from kernel density estimates and the joint entropy from a Gaussian fit, which is exact here because the data are Gaussian. For a Gaussian the total correlation also has a closed form, gaussian_total_correlation, to check the estimate against.
# Shapes: sample (N) = 5,000; state (D_x) = 2; latent (D_x) = 2
# ρ, the correlation between the two coordinates
rho: float = 0.85
StateMatrix = Float[ArrayLike, "state state"]
# Σ = [[1, ρ], [ρ, 1]], (state, state)
covariance: StateMatrix = np.array([[1.0, rho], [rho, 1.0]])
# L with L Lᵀ = Σ, (state, state)
cholesky_factor: StateMatrix = np.linalg.cholesky(covariance)
# ε ~ N(0, I), (sample, state)
noise: SampleState = rng.standard_normal((5_000, 2))
# x = L ε, so x ~ N(0, Σ), (sample, state)
correlated: SampleState = noise @ cholesky_factor.Trbig.PCARotation whitens the samples, and the total correlation is estimated before and after.
# today (rbig)
# fit the whitening map: rotate onto the principal axes, scale each to unit variance
whitener = rbig.PCARotation(whiten=True).fit(correlated)
SampleLatent = Float[ArrayLike, "sample latent"]
# today (rbig)
# z = the whitened samples, (sample, latent)
whitened: SampleLatent = whitener.transform(correlated)
# today (rbig)
# TC = ∑_d H[p(x_d)] − H[p(x)], marginals by KDE, joint by a Gaussian fit
tc_before: Scalar = rbig.total_correlation(correlated)
# today (rbig)
# TC of the whitened samples, the same estimator
tc_after: Scalar = rbig.total_correlation(whitened)
# today (gauss_flows)
# TC = ½ (∑_d log Σ_dd − log det Σ)
tc_closed_form: float = float(gaussian_total_correlation(jnp.asarray(covariance)))
print(f"TC before whitening, closed form = {tc_closed_form:.4f} nats")
print(f"TC before whitening, rbig = {tc_before:.4f} nats")
print(f"TC after whitening, rbig = {tc_after:.4f} nats")TC before whitening, closed form = 0.6410 nats
TC before whitening, rbig = 0.6343 nats
TC after whitening, rbig = -0.0043 nats
fig, axes = plt.subplots(1, 2, figsize=(12, 5.5), sharex=True, sharey=True)
panels = [
(axes[0], correlated, f"correlated Gaussian, TC = {tc_before:.3f} nats", "x", "C0"),
(axes[1], whitened, f"after whitening, TC = {tc_after:.3f} nats", "z", "C1"),
]
for ax, samples, title, symbol, color in panels:
ax.scatter(samples[:3000, 0], samples[:3000, 1], color=color, **SCATTER_KW)
ax.set(title=title, xlabel=f"${symbol}_1$", ylabel=f"${symbol}_2$")
ax.set(xlim=(-4, 4), ylim=(-4, 4))
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:A correlated 2-D Gaussian (left) and the same samples after whitening (right), with the total correlation estimated by rbig. Whitening a Gaussian makes its coordinates independent.
The left cloud leans along the diagonal: knowing says a lot about . The right cloud is round, its coordinates are independent and its total correlation has dropped to about zero. Once data reach , information-theoretic quantities split into one term per coordinate, which is what makes Gaussianized representations convenient for entropy and mutual-information estimates.
The cell below shows it on a banana-shaped dataset , with independent. Its two coordinates are uncorrelated, so whitening only centres and rescales them, and its total correlation keeps the value we can compute exactly.
The exact total correlation of the banana
The map from to has a Jacobian determinant of one, so by (3) the joint density of is the standard Gaussian density at and . The first coordinate is standard normal, with entropy . By (5) the total correlation is therefore , and the density is a 1-D integral that Gauss–Hermite quadrature evaluates to high accuracy. Rescaling a coordinate does not change the total correlation, so whitening leaves this value as it is.
# Shapes: sample (N) = 5,000; state (D_x) = 2; latent (D_x) = 2
# w₁, w₂ ~ N(0, 1) independent, (sample, state)
independent: SampleState = rng.standard_normal((5_000, 2))
# x = [w₁, w₂ + 0.6 w₁²], (sample, state)
banana: SampleState = np.stack(
[independent[:, 0], independent[:, 1] + 0.6 * independent[:, 0] ** 2], axis=1
)
# today (rbig)
# fit the whitening map to the banana
banana_whitener = rbig.PCARotation(whiten=True).fit(banana)
# today (rbig)
# z = the whitened banana, (sample, latent)
banana_white: SampleLatent = banana_whitener.transform(banana)
# Σ̂_z, the covariance after whitening, (latent, latent)
covariance_white: Float[ArrayLike, "latent latent"] = np.cov(banana_white.T)The exact total correlation needs the density of , which Gauss–Hermite quadrature over gives on a fine set of points.
# Shapes: node = 200 Gauss–Hermite nodes; test = 20,001 points on [−8, 25]
PerNode = Float[ArrayLike, " node"]
# Gauss–Hermite nodes w₁ₖ and weights for the weight e^(−w²/2), (node), (node)
nodes: PerNode
hermite_weights: PerNode
nodes, hermite_weights = np.polynomial.hermite_e.hermegauss(200)
# ωₖ, normalised to sum to 1 under N(0, 1), (node)
weights: PerNode = hermite_weights / np.sqrt(2 * np.pi)
PerTestPoint = Float[ArrayLike, " test"]
# x₂ on [−8, 25], (test)
x2_points: PerTestPoint = np.linspace(-8, 25, 20_001)
# x₂ − 0.6 w₁ₖ² at every point and node, (test, node)
residual: Float[ArrayLike, "test node"] = x2_points[:, None] - 0.6 * nodes[None, :] ** 2
# p(x₂) = 𝔼_w₁[N(x₂; 0.6 w₁², 1)] ≈ ∑ₖ ωₖ N(x₂ − 0.6 w₁ₖ²; 0, 1), (test)
density_x2: PerTestPoint = stats.norm.pdf(residual) @ weightsIts entropy gives the exact total correlation, which we compare with the rbig estimate on the whitened banana.
# H[p(x₂)] = −∫ p log p dx₂, by the trapezoid rule
entropy_x2: Scalar = -np.trapezoid(
density_x2 * np.log(np.maximum(density_x2, 1e-300)), x2_points
)
# TC = H[p(x₂)] − ½ log(2πe)
tc_exact: Scalar = entropy_x2 - 0.5 * np.log(2 * np.pi * np.e)
# today (rbig)
# TC with a Gaussian fit for the joint entropy
tc_banana_rbig: Scalar = rbig.total_correlation(banana_white)
print(f"covariance after whitening:\n{covariance_white.round(3)}")
print(f"TC after whitening, exact = {tc_exact:.4f} nats")
print(f"TC after whitening, rbig (Gaussian) = {tc_banana_rbig:.4f} nats")covariance after whitening:
[[ 1. -0.]
[-0. 1.]]
TC after whitening, exact = 0.2337 nats
TC after whitening, rbig (Gaussian) = -0.0437 nats
The whitened covariance is the identity, yet the exact total correlation is still 0.234 nats. An estimate built on the covariance cannot see that dependence: rbig.total_correlation, whose joint entropy is a Gaussian fit, reports a value near zero. Removing the dependence that whitening leaves is the job of the marginal transforms that Gaussianization interleaves with its rotations.
3. Cheap primitives¶
The standard Gaussian is also the cheapest base a flow could sit on. The three things a flow needs from its base are one line each.
Sampling. is
jax.random.normal: no Markov chain, no rejection step.Log-density. It is a squared norm,
Score. The gradient of the log-density is a linear field pointing at the origin,
A linear score is what makes the standard Gaussian the natural end point of score-based and diffusion models Song & Ermon, 2019. We read the base off a flow built by gaussianization_flow and check (6) and (7) on it, the score by autodiff.
# Shapes: latent (D_x) = 2
# today (gauss_flows)
# a Gaussianization flow on D_x = 2, to read its base from
flow: Transformed = gaussianization_flow(
jr.key(0), n_dims=2, n_layers=4, n_components=8
)
# today (flowjax)
# p_z = N(0, I), the flow's base
base: Normal = flow.base_dist
PerLatent = Float[ArrayLike, " latent"]
# z ~ N(0, I), (latent)
latent: PerLatent = jnp.asarray(rng.standard_normal(2))
# log N(z; 0, I) = −(D_x/2) log 2π − ½‖z‖²
log_p_closed_form: Scalar = -0.5 * latent.size * jnp.log(2 * jnp.pi) - 0.5 * jnp.sum(
latent**2
)
# today (flowjax)
# log p_z(z), from the base
log_p_base: Scalar = base.log_prob(latent)
# today (flowjax)
# ∇_z log p_z(z), by autodiff, (latent)
score: PerLatent = jax.grad(base.log_prob)(latent)Both checks agree to rounding:
print(f"z = {np.asarray(latent)}")
print(f"base.log_prob(z) = {float(log_p_base):.10f}")
print(f"closed form = {float(log_p_closed_form):.10f}")
print(f"score, autodiff = {np.asarray(score)}")
print(f"-z = {np.asarray(-latent)}")
assert jnp.allclose(log_p_base, log_p_closed_form)
assert jnp.allclose(score, -latent)z = [ 0.19977046 -1.28493524]
base.log_prob(z) = -2.6833604690
closed form = -2.6833604690
score, autodiff = [-0.19977046 1.28493524]
-z = [-0.19977046 1.28493524]
For the figure we evaluate the score on a 13 by 13 grid of points.
# Shapes: row = 13 values of z₂; column = 13 values of z₁; test = 169 = 13 × 13 grid points
# 13 values on [−2.5, 2.5], (column)
ticks: Float[ArrayLike, " column"] = np.linspace(-2.5, 2.5, 13)
RowColumn = Float[ArrayLike, "row column"]
# z₁ and z₂ over the 13 × 13 grid, (row, column), (row, column)
grid_z1: RowColumn
grid_z2: RowColumn
grid_z1, grid_z2 = np.meshgrid(ticks, ticks)
TestLatent = Float[ArrayLike, "test latent"]
# the grid as 169 points z = [z₁, z₂], (test, latent)
test_points: TestLatent = np.stack([grid_z1.ravel(), grid_z2.ravel()], axis=1)
# today (flowjax)
# ∇_z log p_z(z) at every test point, by autodiff, (test, latent)
scores: TestLatent = jax.vmap(jax.grad(base.log_prob))(jnp.asarray(test_points))fig, ax = plt.subplots(figsize=(6, 6))
ax.quiver(
test_points[:, 0],
test_points[:, 1],
scores[:, 0],
scores[:, 1],
color="C4",
scale=30,
)
ax.plot(0, 0, "k*", ms=12)
ax.set(xlabel="$z_1$", ylabel="$z_2$")
ax.set_aspect("equal")
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:The score of the standard Gaussian on a grid, by autodiff of the flow’s base log-density: a linear field pointing at the origin (star).
Autodiff confirms (7), and the field in Figure 3 is a plain linear pull towards the origin. Cheap sampling, a squared-norm log-density and a linear score together keep the base term of every flow’s log_prob and sample cheap.
Recap¶
| Property | Equation | What it buys | In code |
|---|---|---|---|
| maximum entropy | (1), (2) | a reference point for non-Gaussianity | gaussian_entropy |
| negentropy | (3) | a non-negative distance from Gaussian | rbig.negentropy |
| separability | (4) | total correlation (5) is zero | rbig.total_correlation |
| cheap log-density | (6) | the base term of log_prob | flow.base_dist.log_prob |
| linear score | (7) | a simple end point for score-based models | jax.grad(base.log_prob) |
Next. With the target justified, the next notebook names the object we have been building: a density destructor, which frames Gaussianization as repeated whitening followed by an elementwise nonlinearity.
- Jaynes, E. T. (1957). Information Theory and Statistical Mechanics. Physical Review, 106(4), 620–630. 10.1103/PhysRev.106.620
- Cover, T. M., & Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). Wiley-Interscience.
- Watanabe, S. (1960). Information Theoretical Analysis of Multivariate Correlation. IBM Journal of Research and Development, 4(1), 66–82. 10.1147/rd.41.0066
- Song, Y., & Ermon, S. (2019). Generative Modeling by Estimating Gradients of the Data Distribution. Advances in Neural Information Processing Systems (NeurIPS).