ECDF and histograms
The atom of Gaussianization, from rank to uniform to normal, and where the empirical CDF breaks
00 · ECDF and histograms¶
Part 0 described a density destructor as marginal Gaussianizations (2) interleaved with rotations (3). Part 1 builds the marginal piece, the map that turns one coordinate’s distribution into a standard normal. Every method in the curriculum, from RBIG to coupling and spline flows, stacks these one-dimensional maps, so getting them right is most of the work; the rest is composition (1).
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
repo = "git+https://github.com/jejjohnson/gauss_flows@main"
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
f"gauss-flows-maps @ {repo}#subdirectory=packages/gauss-flows-maps",
f"gauss-flows-models @ {repo}#subdirectory=packages/gauss-flows-models",
f"gauss-flows-docs[notebooks] @ {repo}#subdirectory=docs",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import jax.scipy.stats as jstats
import matplotlib.pyplot as plt
import numpy as np
import rbig
from flowjax.bijections import Chain
from jaxtyping import ArrayLike, Float, Int
from scipy import stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
GAUSS_KW,
LATENT_COLOR,
standard_normal_pdf,
style_ax,
use_compact_figures,
)
from gauss_flows_maps.bijections import HistogramCDF, InverseGaussCDF
# Log-determinants and round trips get float64.
jax.config.update("jax_enable_x64", True)
rng = np.random.default_rng(10)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("jax", "numpy", "scipy", "matplotlib", "rbig", "gauss_flows_maps")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
jax : 0.12.1
numpy : 2.4.3
scipy : 1.17.1
matplotlib : 3.11.2
rbig : 0.1.16
gauss_flows_maps: 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
Throughout, the data are draws of one coordinate from a unit exponential, a skewed marginal with a hard edge at zero and a long right tail, far from Gaussian.
# Shapes: sample (N) = 6,000; state (D_x) = 1
SampleState = Float[ArrayLike, "sample state"]
# x ~ Exp(1), (sample, state)
samples: SampleState = rng.exponential(1.0, size=(6000, 1))
print(f"x: shape {samples.shape}, min {samples.min():.4f}, max {samples.max():.2f}")x: shape (6000, 1), min 0.0001, max 9.68
1. The probability integral transform¶
Everything rests on one classical fact. If a continuous variable has a strictly increasing CDF , then applied to its own draws is uniform,
which is the probability integral transform. The probit then sends that uniform level to a standard normal, and the two steps together are the marginal map of (3). We write it when we need its derivative.
In one dimension this Gaussianizes exactly, provided we know . We never do, so we estimate it from the samples, and the two simplest estimators, the empirical CDF and the histogram, show where the difficulty lies.
2. The empirical CDF and the DKW rate¶
The empirical CDF of the samples counts how many fall at or below a point,
a right-continuous staircase that jumps by at each sample. The Glivenko–Cantelli theorem says that the worst-case gap tends to zero almost surely, and the Dvoretzky–Kiefer–Wolfowitz inequality Dvoretzky et al., 1956, with the constant 2 that Massart later showed is tight, says how fast: for any gap ,
Setting the right-hand side to 0.05 gives a band that holds the whole empirical CDF with probability at least 0.95, and it shrinks like . We measure the gap on a grid for growing subsets of the data.
PerSample = Float[ArrayLike, " sample"]
PerTestPoint = Float[ArrayLike, " test"]
# user
# F̂_N(x) = (1/N) ∑ₙ 𝟏[xₙ ≤ x]
def ecdf(data: PerSample, points: PerTestPoint) -> PerTestPoint:
"""The empirical CDF of ``data`` at ``points``."""
# x₍₁₎ ≤ … ≤ x₍N₎, (sample)
sorted_data: PerSample = np.sort(data)
# #{n : xₙ ≤ x} at each point, (test)
count_below: Int[ArrayLike, " test"] = np.searchsorted(
sorted_data, points, side="right"
)
return count_below / len(data)We evaluate it on a grid over , for 15 subset sizes from 10 to 5000, and compare each with the true CDF .
# Shapes: test = 400 evaluation points; subset = 15 sample sizes
# evaluation points on [0, 6], (test)
grid: PerTestPoint = np.linspace(0, 6, 400)
# F(x) = 1 − e⁻ˣ on the grid, (test)
true_cdf: PerTestPoint = stats.expon.cdf(grid)
# N from 10 to 5000, log-spaced, (subset)
subset_sizes: Int[ArrayLike, " subset"] = np.logspace(1, 3.7, 15).astype(int)
PerSubset = Float[ArrayLike, " subset"]
# sup_x |F̂_N(x) − F(x)| for each N, (subset)
sup_gap: PerSubset = np.zeros(len(subset_sizes))
for index, size in enumerate(subset_sizes):
# user
# F̂_N on the grid, from the first N samples, (test)
estimate: PerTestPoint = ecdf(samples[:size, 0], grid)
# sup_x |F̂_N(x) − F(x)|
sup_gap[index] = np.max(np.abs(estimate - true_cdf))
# λ_N = √(log 40 / (2N)), (subset)
dkw_band: PerSubset = np.sqrt(np.log(40) / (2 * subset_sizes))
# slope of log sup_gap against log N
slope: float
slope, _ = np.polyfit(np.log(subset_sizes), np.log(sup_gap), 1)
print(f"fitted slope of log gap against log N: {slope:.2f}")
print(f"every gap inside the 95% DKW band: {bool(np.all(sup_gap < dkw_band))}")fitted slope of log gap against log N: -0.45
every gap inside the 95% DKW band: True
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
for n, color in zip([20, 200, 2000], ["C2", "C3", DATA_COLOR], strict=True):
estimate = ecdf(samples[:n, 0], grid)
axes[0].step(grid, estimate, where="post", lw=1.2, color=color, label=f"N = {n}")
axes[0].plot(grid, true_cdf, "k--", lw=1.5, label="true $F$")
axes[0].set(xlabel="$x$", ylabel="CDF", title="Empirical CDF against the truth")
axes[0].legend()
style_ax(axes[0])
axes[1].loglog(subset_sizes, sup_gap, "o-", color=DATA_COLOR, ms=4, label="gap")
axes[1].loglog(subset_sizes, dkw_band, "k--", lw=1.2, label=r"95% DKW band $\lambda_N$")
axes[1].set(xlabel="$N$", ylabel="worst-case gap", title="Uniform convergence")
axes[1].legend()
style_ax(axes[1])
fig.tight_layout()
plt.show()
Figure 1:Left: the empirical CDF of 20, 200 and 2000 samples closes in on the exponential CDF. Right: the worst-case gap against the sample size stays inside the 95% DKW band and falls at about its rate.
The fitted slope is close to and every measured gap sits inside the band, so the empirical CDF is a consistent estimate of with a known rate. That is the guarantee behind every rank-based Gaussianization.
3. Rank, uniform, normal¶
Putting into (1) gives the rank transform: the uniform level of a sample is close to its rank divided by , and the probit of that level is its Gaussianized value. rbig.MarginalUniformize does the first step and rbig.MarginalGaussianize both. In gauss_flows the same map is a chain of two bijections, a HistogramCDF that sends data to uniform and an InverseGaussCDF that applies the probit, so it also carries a log-determinant (section 5).
# today (rbig)
# fit F̂_N to the samples
uniformize = rbig.MarginalUniformize().fit(samples)
# today (rbig)
# τ = F̂_N(x), (sample, state)
levels_rbig: SampleState = uniformize.transform(samples)
SampleLatent = Float[ArrayLike, "sample latent"]
# today (rbig)
# fit T = Φ⁻¹ ∘ F̂_N to the samples
gaussianize = rbig.MarginalGaussianize().fit(samples)
# today (rbig)
# z = Φ⁻¹(F̂_N(x)), (sample, latent)
latent_rbig: SampleLatent = gaussianize.transform(samples)The gauss_flows version chains two bijections, so the same map also returns its log-determinant.
# the samples as a JAX array, (sample, state)
samples_jax: SampleState = jnp.asarray(samples)
# today (gauss_flows)
# F̂ as a 64-bin histogram CDF, fitted to the samples
histogram_cdf = HistogramCDF(n_bins=64, shape=(1,)).fit(samples_jax)
# today (flowjax, gauss_flows)
# T = Φ⁻¹ ∘ F̂
marginal_map = Chain([histogram_cdf, InverseGaussCDF(shape=(1,))])
# today (gauss_flows)
# τ = F̂(x), (sample, state)
levels_gf: SampleState = jax.vmap(histogram_cdf.transform)(samples_jax)
# today (gauss_flows)
# z = T(x) and log |T'(x)|, (sample, latent), (sample)
latent_gf: SampleLatent
logdet_gf: PerSample
latent_gf, logdet_gf = jax.vmap(marginal_map.transform_and_log_det)(samples_jax)We compare rbig’s levels with the rank over , the two estimators’ levels with each other, and the moments of both latents.
# user
# F̂_N(xₙ), the rank of each sample over N, (sample)
ranks: PerSample = ecdf(samples[:, 0], samples[:, 0])
# maxₙ |τₙ − F̂_N(xₙ)|, rbig's level against the rank
rank_gap: float = np.max(np.abs(levels_rbig[:, 0] - ranks))
# τ₍₁₎ ≤ … ≤ τ₍N₎ from rbig, (sample)
sorted_rbig: PerSample = np.sort(levels_rbig[:, 0])
# τ₍₁₎ ≤ … ≤ τ₍N₎ from HistogramCDF, (sample)
sorted_gf: PerSample = np.sort(np.asarray(levels_gf[:, 0]))
# maxₙ |τ₍ₙ₎ rbig − τ₍ₙ₎ HistogramCDF|
sorted_gap: float = np.max(np.abs(sorted_rbig - sorted_gf))
print(f"rbig level against rank / N: max gap {rank_gap:.1e}")
print(f"rbig against HistogramCDF levels (sorted): max gap {sorted_gap:.3f}")
latents = [("rbig", latent_rbig[:, 0]), ("HistogramCDF", np.asarray(latent_gf[:, 0]))]
for name, z in latents:
print(
f"{name:>12}: mean {z.mean():+.3f}, std {z.std():.3f}, "
f"range [{z.min():.2f}, {z.max():.2f}]"
)rbig level against rank / N: max gap 8.3e-05
rbig against HistogramCDF levels (sorted): max gap 0.035
rbig: mean +0.000, std 1.000, range [-3.76, 3.76]
HistogramCDF: mean +0.013, std 0.964, range [-1.81, 3.71]
fig, axes = plt.subplots(1, 3, figsize=(18, 4.5))
axes[0].hist(samples[:, 0], bins=60, density=True, color=DATA_COLOR, alpha=0.6)
axes[0].set(xlabel="$x$", ylabel="density", title="1. data, exponential")
axes[1].hist(levels_rbig[:, 0], bins=40, density=True, color="C2", alpha=0.6)
axes[1].axhline(1.0, **GAUSS_KW, label=r"$\mathcal{U}(0, 1)$")
axes[1].set(xlabel=r"$\tau$", title=r"2. $\tau = \hat{F}_N(x)$, uniform")
axes[1].legend()
z_grid = np.linspace(-4, 4, 200)
bins = np.linspace(-4, 4, 50)
axes[2].hist(
latent_rbig[:, 0],
bins=bins,
density=True,
color=LATENT_COLOR,
alpha=0.5,
label="rbig",
)
axes[2].hist(
latent_gf[:, 0],
bins=bins,
density=True,
histtype="step",
color="C4",
lw=1.5,
label="HistogramCDF",
)
axes[2].plot(
z_grid, standard_normal_pdf(z_grid), **GAUSS_KW, label=r"$\mathcal{N}(0, 1)$"
)
axes[2].set(xlabel="$z$", title=r"3. $z = \Phi^{-1}(\tau)$, normal")
axes[2].legend()
for ax in axes:
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:The marginal map in three stages on exponential data. Left: the data. Middle: the uniform levels from rbig’s empirical CDF. Right: the Gaussianized values from rbig and from a 64-bin HistogramCDF, against ; the histogram cannot resolve the steep density next to zero, so its lower tail stops near -1.8.
rbig’s level is the rank over to within 10-4, so it really is the empirical CDF, and its output has mean zero and unit standard deviation. The 64-bin histogram is coarser. Its first bin is wider than the region where the exponential density is steepest, and its edges are padded past the smallest sample, so the smallest samples land at a level of a few percent instead of near zero and the lower tail of stops near -1.8. A histogram trades the empirical CDF’s jumps for a resolution set by its bin width.
4. The boundary problem¶
The empirical CDF puts the largest sample at a level near one and the smallest near zero, and it knows nothing outside the observed range. The probit of a level near zero or one is huge, and the inverse has no information about where between the extreme samples a tail point should go, so tail samples do not survive the round trip. This is the saturated-CDF failure of Part 0, notebook 05 seen from the estimator’s side. rbig’s remedy is support extension, pdf_extension, which pads the estimated density a fraction of the data range beyond the extremes so the inverse has room to place tail samples.
roundtrip_error = {}
for extension in [0.0, 0.1]:
# today (rbig)
# fit F̂_N with the support padded by a fraction of the data range
extended = rbig.MarginalUniformize(pdf_extension=extension).fit(samples)
# today (rbig)
# τ = F̂_N(x), (sample, state)
levels: SampleState = extended.transform(samples)
# today (rbig)
# x̂ = F̂_N⁻¹(τ), (sample, state)
recovered: SampleState = extended.inverse_transform(levels)
# |x − x̂|
roundtrip_error[extension] = np.abs(samples - recovered).ravel()
# n⋆ = argmaxₙ |xₙ − x̂ₙ|
worst: int = int(np.argmax(roundtrip_error[extension]))
print(
f"pdf_extension = {extension}: worst round-trip error "
f"{roundtrip_error[extension][worst]:.2e} at x = {samples[worst, 0]:.2f}"
)
# worst error without the extension over worst error with it
ratio: float = roundtrip_error[0.0].max() / roundtrip_error[0.1].max()
print(f"the worst error falls by a factor of {ratio:.0f}")pdf_extension = 0.0: worst round-trip error 7.62e-01 at x = 9.68
pdf_extension = 0.1: worst round-trip error 1.17e-02 at x = 6.79
the worst error falls by a factor of 65
fig, ax = plt.subplots(figsize=(12, 4.5))
order = np.argsort(samples.ravel())
for extension, color, label in [
(0.0, DATA_COLOR, "no support extension"),
(0.1, "C2", "pdf_extension = 0.1"),
]:
error = np.maximum(roundtrip_error[extension][order], 1e-17)
ax.semilogy(
samples.ravel()[order], error, ".", ms=3, alpha=0.5, color=color, label=label
)
ax.set(xlabel="$x$", ylabel="round-trip error", title="Support extension in the tail")
ax.legend()
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 3:Round-trip error of rbig’s uniformization at each sample, without and with a 10% support extension. Without it the error spikes at the largest samples; with it the worst error is far smaller, though not zero.
Support extension cuts the worst error by the printed factor, but it is a heuristic, a guess about mass beyond the data. The HistogramCDF makes the opposite choice and refuses to guess: a point outside its fitted range is clamped to the boundary level and gets a log-determinant of , which says the point is outside the support of the fitted CDF.
# Shapes: test = 2 points outside the data
TestState = Float[ArrayLike, "test state"]
# one point below the data and one far above it, (test, state)
outside: TestState = jnp.array([[-0.5], [100.0]])
# today (gauss_flows)
# z = T(x) and log |T'(x)|, (test, latent), (test)
latent_out: Float[ArrayLike, "test latent"]
logdet_out: PerTestPoint
latent_out, logdet_out = jax.vmap(marginal_map.transform_and_log_det)(outside)
points = zip(outside[:, 0], latent_out[:, 0], logdet_out, strict=True)
for point, z_value, ld in points:
print(f"x = {float(point):6.1f}: z = {float(z_value):+.2f}, log-det = {float(ld)}")x = -0.5: z = -4.75, log-det = -inf
x = 100.0: z = +4.75, log-det = -inf
The there is the clamp of (2) at . Neither estimator has a model of the tail, which is the first reason Part 1 moves on to smooth CDFs.
5. The log-determinant of a marginal map¶
A marginal map earns its place in a flow only if we can compute its log-determinant, the term that change of variables (4) adds to . For the chain rule, with and the derivative of at equal to , gives
and so, per coordinate,
with . The log-determinant of a marginal map is its own log-density re-referenced to the standard normal, and a -dimensional marginal Gaussianization sums it over coordinates, because its Jacobian is diagonal. With an estimated CDF, is replaced by the density of the estimate, .
This exposes the second flaw of the empirical CDF. is a staircase, so is a sum of point masses: zero between samples and undefined at them. The log-determinant (5) is then almost everywhere, so the rank transform Gaussianizes but is not a density model. A histogram with bins of width , where bin holds samples, has the piecewise-constant density
which gives the first finite log-determinant. We check that the gauss_flows chain returns exactly (5), then compare it with the true log-determinant of the exponential, whose CDF we know.
# today (gauss_flows)
# log p̂_x(x), the log-det of F̂ alone, (sample)
log_density: PerSample
_, log_density = jax.vmap(histogram_cdf.transform_and_log_det)(samples_jax)
# log 𝒩(z; 0, 1) at the latent, (sample)
reference: PerSample = jstats.norm.logpdf(latent_gf[:, 0])
# log p̂_x(x) − log 𝒩(z; 0, 1), (sample)
formula_logdet: PerSample = log_density - reference
Scalar = Float[ArrayLike, ""]
# maxₙ |chain log-det − formula log-det|
identity_gap: Scalar = jnp.max(jnp.abs(logdet_gf - formula_logdet))
print(f"chain log-det against log p - log N(z): max gap {float(identity_gap):.1e}")chain log-det against log p - log N(z): max gap 0.0e+00
On a grid over , where the exponential’s CDF gives the true log-determinant, we compare it with the histogram’s.
# Shapes: test = 600 evaluation points
# evaluation points on (0, 6], as one-coordinate events, (test, state)
x_grid: TestState = np.linspace(0.01, 6, 600)[:, None]
# today (gauss_flows)
# log p̂_x on the grid, (test)
hist_log_density: PerTestPoint
_, hist_log_density = jax.vmap(histogram_cdf.transform_and_log_det)(x_grid)
# today (gauss_flows)
# log |T'(x)| of the histogram map on the grid, (test)
hist_logdet: PerTestPoint
_, hist_logdet = jax.vmap(marginal_map.transform_and_log_det)(x_grid)The true log-determinant follows from (5) with the exponential’s own density and CDF.
# F(x) = 1 − e⁻ˣ on the grid, (test)
grid_cdf: PerTestPoint = stats.expon.cdf(x_grid[:, 0])
# z = Φ⁻¹(F(x)), the exact marginal map, (test)
z_true: PerTestPoint = stats.norm.ppf(grid_cdf)
# log p_x(x) = −x, the true log-density, (test)
true_log_density: PerTestPoint = stats.expon.logpdf(x_grid[:, 0])
# log 𝒩(z; 0, 1) at the exact latent, (test)
true_reference: PerTestPoint = stats.norm.logpdf(z_true)
# log |T'(x)| = log p_x(x) − log 𝒩(z; 0, 1), (test)
true_logdet: PerTestPoint = true_log_density - true_reference
# |log |T̂'(x)| − log |T'(x)||, histogram against the truth
logdet_gap: PerTestPoint = np.abs(np.asarray(hist_logdet) - true_logdet)
# median over the grid
median_gap: float = np.median(logdet_gap)
print(f"histogram log-det against the truth on (0, 6]: median gap {median_gap:.2f}")histogram log-det against the truth on (0, 6]: median gap 0.12
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
axes[0].plot(
x_grid[:, 0], np.exp(hist_log_density), color=DATA_COLOR, label="histogram"
)
axes[0].plot(x_grid[:, 0], stats.expon.pdf(x_grid[:, 0]), "k--", lw=1.5, label="true")
axes[0].set(xlabel="$x$", ylabel=r"$\hat{p}_x(x)$", title="Estimated density")
axes[0].legend()
axes[1].plot(x_grid[:, 0], hist_logdet, color=LATENT_COLOR, label="histogram")
axes[1].plot(x_grid[:, 0], true_logdet, "k--", lw=1.5, label="true")
axes[1].set(xlabel="$x$", ylabel=r"$\log \vert T'(x) \vert$", title="Log-determinant")
axes[1].legend()
for ax in axes:
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 4:Left: the density of the 64-bin HistogramCDF, constant within each bin, against the exponential density. The first bin starts below the smallest sample, so its density is too low next to zero. Right: its log-determinant against the true one; it follows the truth on average but inherits the bin structure, and its jumps grow in the right tail, where each bin holds few samples.
The two agree to machine precision on the identity, so the log-determinant a gauss_flows marginal reports is the formula above. Against the truth it is finite and right on average, with a median gap of about 0.1 nats, but jagged: it moves smoothly within each bin and jumps at the edges, more so in the sparse right tail. A flow trained by gradient descent wants a smooth , so that the log-determinant and its gradients are smooth too, and that is what the kernel, mixture and spline CDFs of the next notebooks provide.
Recap¶
| Step | Equation | In code |
|---|---|---|
| data to uniform | (1) with , (2) | rbig.MarginalUniformize, HistogramCDF |
| uniform to normal | (3) | InverseGaussCDF |
| full marginal map | rbig.MarginalGaussianize, Chain([hist, InverseGaussCDF(...)]) | |
| consistency | (3) | Figure 1 |
| tail fix | support extension | pdf_extension |
| log-determinant | (5), (6) | transform_and_log_det |
Next. The empirical CDF is consistent but jagged and blind to the tails. The next notebook replaces the staircase with a smooth density estimate, a kernel density or a Gaussian mixture, whose CDF and log-determinant are analytic and differentiable.
- Dvoretzky, A., Kiefer, J., & Wolfowitz, J. (1956). Asymptotic Minimax Character of the Sample Distribution Function and of the Classical Multinomial Estimator. The Annals of Mathematical Statistics, 27(3), 642–669. 10.1214/aoms/1177728174