Gaussianity diagnostics
Did we reach a standard Gaussian? QQ-plots, moments, negentropy and a joint energy test
06 · Gaussianity diagnostics¶
We can build a Gaussianization and trust its arithmetic. The last foundational question is how we know it worked: that the latent really follows , the base density of the log-density (4). Gaussianity has two levels and each needs its own diagnostic. Coordinate by coordinate, is every marginal a standard normal? Jointly, is the whole vector a standard normal, which also requires the coordinates to be independent?
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import matplotlib.pyplot as plt
import numpy as np
import rbig
from jaxtyping import ArrayLike, Float, Int
from scipy import stats
from scipy.spatial.distance import cdist
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
rng = np.random.default_rng(7)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("numpy", "scipy", "matplotlib", "rbig")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
numpy : 2.4.3
scipy : 1.17.1
matplotlib: 3.11.2
rbig : 0.1.16
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. Three states to diagnose¶
We take points of the two-moons dataset in dimensions, standardised per coordinate, and fit an RBIG model of 30 layers, each a marginal Gaussianization followed by a random rotation. We keep three states to compare: the data , the data after one marginal Gaussianization only, , and the fully Gaussianized latent . We also keep every intermediate state of (2), for section 5.
# Shapes: sample (N) = 2,000; state (D_x) = 2; latent (D_x) = 2
SampleState = Float[ArrayLike, "sample state"]
# x ~ two moons, (sample, state)
moons: SampleState
moons, _ = make_moons(2000, noise=0.06, random_state=0)
# x ← (x − mean) / std, per coordinate, (sample, state)
data: SampleState = (moons - moons.mean(0)) / moons.std(0)
# today (rbig)
# f = f_K ∘ … ∘ f₁, each a marginal Gaussianization and a random rotation, K = 30
model = rbig.AnnealedRBIG(n_layers=30, rotation="random", random_state=0)
# today (rbig)
# fit f to the data
model.fit(data)
# x₀ = x
states = [data]
for layer in model.layers_:
# today (rbig)
# xₖ = fₖ(xₖ₋₁), (sample, state)
next_state: SampleState = layer.transform(states[-1])
states.append(next_state)
print(f"{len(model.layers_)} RBIG layers fitted")30 RBIG layers fitted
The latent is the last state, and the marginal-only state applies one marginal Gaussianization to the data with no rotation.
SampleLatent = Float[ArrayLike, "sample latent"]
# z = x_K, (sample, latent)
latent: SampleLatent = states[-1]
# today (rbig)
# fit T = Φ⁻¹ ∘ F̂_N to each coordinate of the data
marginal_gaussianize = rbig.MarginalGaussianize().fit(data)
# today (rbig)
# m = T(x), coordinate by coordinate, and nothing else, (sample, latent)
marginal_only: SampleLatent = marginal_gaussianize.transform(data)
three_states = {
"data x": data,
"marginal only m": marginal_only,
"Gaussianized z": latent,
}2. Marginal diagnostics: QQ-plots and moments¶
The cheapest check is per coordinate. Write for coordinate of , with density , mean and standard deviation . A QQ-plot sorts the samples of and plots the -th smallest against the standard-normal quantile , where is the standard-normal CDF. If , the points fall on the identity line. Two scalar summaries put a number on what the plot shows, the skewness (asymmetry) and the excess kurtosis (tail weight),
both zero for a Gaussian. Figure 1 shows the first coordinate of the three states.
def qq_plot(ax, values, title):
"""Sorted samples against the matching standard-normal quantiles."""
ordered = np.sort(values)
n_samples = len(ordered)
# Φ⁻¹((i − 0.5) / N), i = 1, …, N
theory = stats.norm.ppf((np.arange(1, n_samples + 1) - 0.5) / n_samples)
ax.plot([-4, 4], [-4, 4], **GAUSS_KW, label="standard normal")
ax.plot(theory, ordered, ".", ms=2, alpha=0.5, color=DATA_COLOR)
ax.set(
title=title,
xlabel=r"standard-normal quantile $\Phi^{-1}$",
xlim=(-4, 4),
ylim=(-4, 4),
)
ax.set_aspect("equal")
ax.legend(loc="upper left")
style_ax(ax)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
qq_plot(axes[0], data[:, 0], "data $x_1$")
qq_plot(axes[1], marginal_only[:, 0], "marginal only $m_1$")
qq_plot(axes[2], latent[:, 0], "Gaussianized $z_1$")
axes[0].set_ylabel("sample quantile")
fig.tight_layout()
plt.show()
Figure 1:QQ-plots of the first coordinate of the data (left), the data after one marginal Gaussianization (centre) and the Gaussianized latent (right), against standard-normal quantiles. The dashed line is where a standard normal falls.
PerState = Float[ArrayLike, " state"]
print(f"{'':18s}{'skewness':>20s}{'excess kurtosis':>22s}")
for name, values in three_states.items():
# γ₁,d = E[(z_d − μ_d)³] / σ_d³, per coordinate, (state)
skewness: PerState = np.round(stats.skew(values), 3)
# γ₂,d = E[(z_d − μ_d)⁴] / σ_d⁴ − 3, per coordinate, (state)
kurtosis: PerState = np.round(stats.kurtosis(values), 3)
print(f"{name:18s}{skewness!s:>20s}{kurtosis!s:>22s}") skewness excess kurtosis
data x [-0.003 0.003] [-0.883 -1.251]
marginal only m [0. 0.] [-0.016 -0.016]
Gaussianized z [-0. 0.002] [0.027 0.017]
The data’s QQ-plot is S-shaped: the two-moons marginals have light tails, with excess kurtosis -0.88 and -1.25. Their skewness is already near zero, because the two moons are symmetric, so for this dataset skewness alone would miss the problem. After Gaussianization the points sit on the line and both moments are within 0.03 of zero. The middle panel matters most: one marginal Gaussianization, with no rotation at all, already passes both marginal checks.
3. Negentropy and total correlation¶
Skewness and kurtosis only probe the third and fourth moments. The complete measure of how far one marginal is from a Gaussian is its negentropy, the entropy it lacks compared with the Gaussian of the same mean and variance.
Notebook 03 defined both measures. Negentropy (3), applied to one coordinate, compares with the Gaussian of the same mean and variance, and total correlation (5) is the sum of the marginal entropies minus the joint one. Both are non-negative: exactly when coordinate is Gaussian, and exactly when the coordinates are independent.
Together they account for the whole distance to the standard normal.
Driving (3) to zero is what RBIG does: marginal Gaussianization removes the negentropy term, and the rotations turn the remaining total correlation into new marginal non-Gaussianity for the next layer to remove. We estimate the negentropy of each coordinate with rbig.negentropy, which estimates with a kernel density estimate. Once a flow is trained, gauss_flows estimates the same quantities from the flow itself, with negentropy and total_correlation.
negentropies = {}
for name, values in three_states.items():
# today (rbig)
# Neg[p_{z_d}] for each coordinate d, from a KDE of its entropy, (state)
estimate: PerState = rbig.negentropy(values)
# max(Neg[p_{z_d}], 0), since the KDE estimate can dip a hair below zero
negentropies[name] = np.clip(estimate, 0.0, None)
print(f"negentropy of {name:16s}: {np.round(negentropies[name], 4)} nats")negentropy of data x : [0.1199 0.1703] nats
negentropy of marginal only m : [0. 0.] nats
negentropy of Gaussianized z : [0.0014 0.0009] nats
Figure 2 compares the three states coordinate by coordinate.
fig, ax = plt.subplots(figsize=(12, 4.5))
width = 0.25
coordinates = np.arange(2)
colors = [DATA_COLOR, "0.5", LATENT_COLOR]
for offset, (name, values), color in zip(
(-width, 0.0, width), negentropies.items(), colors, strict=True
):
ax.bar(coordinates + offset, values, width, color=color, label=name)
ax.set_xticks(coordinates, ["coordinate 1", "coordinate 2"])
ax.set(ylabel="negentropy (nats)")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Estimated negentropy of each coordinate of the three states. One marginal Gaussianization removes it as completely as the full RBIG model does.
The data carries 0.12 and 0.17 nats of negentropy, and both the marginal-only state and the Gaussianized latent are at or below 0.002 nats.
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
for ax, (name, values), color in zip(axes, three_states.items(), colors, strict=True):
ax.scatter(values[:, 0], values[:, 1], color=color, **SCATTER_KW)
ax.set(title=name, xlabel="coordinate 1", xlim=(-4, 4), ylim=(-4, 4))
ax.set_aspect("equal")
style_ax(ax)
axes[0].set_ylabel("coordinate 2")
fig.tight_layout()
plt.show()
Figure 3:Samples of the data (left), the data after one marginal Gaussianization (centre) and the Gaussianized latent (right). The centre panel has standard-normal marginals but keeps the structure of the two moons.
4. A joint test: the energy distance¶
For the joint verdict we compare with through the energy distance of Székely and Rizzo, a two-sample statistic built from Euclidean distances alone,
where are independent draws of and independent draws of .
We estimate (4) by replacing each expectation with an average over samples of and fresh standard-normal samples. To turn the estimate into a test we need its spread when really is : we compute the same statistic between 200 pairs of standard-normal samples, and the p-value is the fraction of those null statistics at least as large as the observed one. The classical alternative is the Henze–Zirkler test of multivariate normality; the energy test needs no tables and takes a few lines.
# Shapes: subsample (n) = 1,000 rows of a state or of N(0, I); state (D_x) = 2
SubsampleState = Float[ArrayLike, "subsample state"]
Scalar = Float[ArrayLike, ""]
# n = 1000
n_test = 1000
# user
# ED = 2 mean‖a − b‖ − mean‖a − a'‖ − mean‖b − b'‖
def energy_distance(first: SubsampleState, second: SubsampleState) -> Scalar:
"""Sample energy distance between the rows of first and the rows of second."""
# mean‖a − b‖ over every pair of rows
cross: Scalar = np.mean(cdist(first, second))
# mean‖a − a'‖
within_first: Scalar = np.mean(cdist(first, first))
# mean‖b − b'‖
within_second: Scalar = np.mean(cdist(second, second))
return 2 * cross - within_first - within_secondTo compare a state with the standard normal, we pick of its rows and draw fresh standard-normal rows.
# user
# ED from n rows of a state to n draws of N(0, I)
def energy_to_normal(values: SampleState, n_samples: int = n_test) -> Scalar:
"""Energy distance from n_samples rows of values to as many N(0, I) draws."""
# n row indices, without replacement, (subsample)
rows: Int[ArrayLike, " subsample"] = rng.choice(
len(values), n_samples, replace=False
)
# g ~ N(0, I), n rows, (subsample, state)
normal: SubsampleState = rng.standard_normal((n_samples, values.shape[1]))
# user
# ED between the chosen rows and the normal rows
return energy_distance(values[rows], normal)The null distribution repeats the statistic between two genuine standard-normal samples of the same size, and the p-value counts the null statistics that reach the observed one.
# Shapes: null_draw = 200 draws of the statistic under N(0, I)
# ED between two N(0, I) samples of n rows, 200 times, (null_draw)
null: Float[ArrayLike, " null_draw"] = np.zeros(200)
for index in range(200):
# g ~ N(0, I), n rows, (subsample, state)
first_normal: SubsampleState = rng.standard_normal((n_test, 2))
# g' ~ N(0, I), n rows, (subsample, state)
second_normal: SubsampleState = rng.standard_normal((n_test, 2))
# user
# ED between g and g'
null[index] = energy_distance(first_normal, second_normal)
print(f"{'':18s}{'energy distance':>18s}{'p-value':>10s}")
for name, values in three_states.items():
# user
# ED from the state to N(0, I)
observed: Scalar = energy_to_normal(values)
# p = (1 + #{null ≥ observed}) / (1 + number of null draws)
p_value: Scalar = (1 + np.sum(null >= observed)) / (1 + len(null))
print(f"{name:18s}{observed:18.4f}{p_value:10.3f}") energy distance p-value
data x 0.0406 0.005
marginal only m 0.0312 0.005
Gaussianized z 0.0031 0.547
The test separates what the marginal checks could not. The data and the marginal-only state both get , the smallest value 200 null draws can give (), so normality is rejected for both, while the Gaussianized latent gets and is consistent with .
5. Watching RBIG converge¶
The same statistic, computed once on every intermediate state , shows how many layers the joint Gaussianization needs. The grey band is the central 95 % of the null distribution: a state inside it cannot be told apart from with samples.
# Shapes: layer = 31 states x₀, …, x₃₀
# user
# ED from each state xₖ to N(0, I), k = 0, …, K, (layer)
energies: Float[ArrayLike, " layer"] = np.array(
[energy_to_normal(state) for state in states]
)
# 2.5 % and 97.5 % quantiles of the null statistic
null_low: Scalar
null_high: Scalar
null_low, null_high = np.quantile(null, [0.025, 0.975])
print(f"layer 0: {energies[0]:.4f}, layer 30: {energies[-1]:.4f}")
print(f"null band: [{null_low:.4f}, {null_high:.4f}]")layer 0: 0.0570, layer 30: 0.0054
null band: [0.0014, 0.0096]
We then find the first layer whose state enters the band, and count the later states that leave it again.
# first k with ED(xₖ) ≤ upper edge of the band
first_inside: int = np.argmax(energies <= null_high)
# #{k ≥ first_inside : ED(xₖ) > upper edge}
above_later: int = np.sum(energies[first_inside:] > null_high)
# K + 1 − first_inside
n_later: int = len(energies) - first_inside
print(f"first state inside the null band: layer {first_inside}")
print(f"states from there on above the band: {above_later} of {n_later}")first state inside the null band: layer 3
states from there on above the band: 0 of 28
Figure 4 plots the statistic against the number of layers applied, with the null band behind it.
fig, ax = plt.subplots(figsize=(12, 4.5))
layer_index = np.arange(len(states))
ax.axhspan(null_low, null_high, color="0.85", label="null, central 95 %")
ax.plot(layer_index, energies, "-o", color=DATA_COLOR, ms=4, label="RBIG state")
ax.set(xlabel="RBIG layers applied", ylabel=r"energy distance to $\mathcal{N}(0, I)$")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 4:Energy distance from each RBIG state to the standard normal, against the number of layers applied. The band is the central 95 % of the statistic between two standard-normal samples.
The energy distance falls from 0.057 on the data into the null band by layer 3 and stays inside it for every later layer, so the remaining layers change nothing a test with samples can detect. This is a practical stopping rule: keep adding layers until the joint statistic enters the null band, a decision that the noisy negentropy estimates of nearly Gaussian states cannot make reliably.
Recap¶
| Level | Diagnostic | Value for a standard normal | Tool |
|---|---|---|---|
| marginal shape | QQ-plot | points on the identity line | scipy.stats.norm.ppf |
| marginal moments | skewness (1), excess kurtosis (2) | 0 and 0 | scipy.stats.skew, scipy.stats.kurtosis |
| marginal information | negentropy (3) | 0 | rbig.negentropy |
| dependence | total correlation (5) | 0 | flow-based total_correlation |
| joint | energy distance (4), with a p-value | inside the null band | scipy.spatial.distance.cdist |
By (3), the marginal checks only see the second term of the distance to , so a Gaussianization is certified by a joint check.
End of Part 0. We now have the foundations: the change-of-variables formula and its log-determinant, how log-determinants add under composition, why the target is a standard Gaussian, what a density destructor is, how to keep one numerically stable, and how to check that it reached a standard Gaussian. Part 1 builds the first real component, the one-dimensional marginal transforms that every method in this curriculum stacks.
- Laparra, V., Camps-Valls, G., & Malo, J. (2011). Iterative Gaussianization: From ICA to Random Rotations. IEEE Transactions on Neural Networks, 22(4), 537–549. 10.1109/TNN.2011.2106511