Boundaries and support
The empirical marginal step knows the data only between its smallest and largest points, which shows at the edges of the range, in generation and in discrete data
03 · Boundaries and support¶
The marginal step of every RBIG layer is the midpoint empirical CDF (1) followed by the probit. That CDF is defined by the sorted training points, so it knows nothing below the smallest or above the largest, and nothing about values that several points share. This notebook looks at what rbig.MarginalGaussianize does in those places, which options it offers, and which of them matter for Gaussianizing data and which for generating it. One marginal is enough to see all of it, so we work in one dimension.
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 matplotlib.pyplot as plt
import numpy as np
import rbig
from jaxtyping import ArrayLike, Float
from scipy import stats
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
REF_COLOR,
standard_normal_pdf,
style_ax,
use_compact_figures,
)
rng = np.random.default_rng(123)
# 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. A skewed sample¶
We draw 5,000 points from a gamma distribution with shape 4, whose long right tail makes the boundary effects easy to see. rbig takes a two-dimensional array, so the sample is one column.
# Shapes: sample (N) = 5,000; state (D_x) = 1
SampleState = Float[ArrayLike, "sample state"]
PerSample = Float[ArrayLike, " sample"]
# today (scipy)
# xₙ ~ Gamma(4, 1), (sample, state)
samples: SampleState = stats.gamma.rvs(4, size=(5000, 1), random_state=123)
print(f"training range [{samples.min():.2f}, {samples.max():.2f}]")training range [0.17, 18.28]
2. Beyond the range¶
For a new point the midpoint empirical CDF counts the training points below it, so a point above the largest one gets the level , which is above 1. With bound_correct=False the probit of that level is NaN, and with the default bound_correct=True the level is clipped as in (1), so the point maps to with . We map two points beyond the range, one close to it and one far.
# Shapes: test = 2
# x_max + 0.5 and x_max + 5, (point, state), (test, state)
beyond: Float[ArrayLike, "test state"] = samples.max() + np.array([[0.5], [5.0]])
for bound_correct in (False, True):
# today (rbig)
# the midpoint empirical CDF and the probit, with or without the clip
marginal = rbig.MarginalGaussianize(bound_correct=bound_correct).fit(samples)
# today (rbig)
# g(x) for the two points, (point, state), (test, state)
mapped: Float[ArrayLike, "test state"] = marginal.transform(beyond)
print(f"bound_correct={bound_correct!s:5s} z = {mapped.ravel()}")bound_correct=False z = [nan nan]
bound_correct=True z = [4.75342431 4.75342431]
Without the clip both points are lost; with it both map to 4.753, however far they are, so the marginal map is flat beyond the range and cannot be inverted there. The clip never touches the training points themselves: the largest of them sits at the level , well inside .
# today (rbig)
# the marginal step with the default clip
marginal = rbig.MarginalGaussianize().fit(samples)
# today (rbig)
# zₙ = g(xₙ), (sample, state)
latent: SampleState = marginal.transform(samples)
# today (rbig)
# the marginal step without the clip
unclipped = rbig.MarginalGaussianize(bound_correct=False).fit(samples)
# today (rbig)
# zₙ without the clip, (sample, state)
latent_unclipped: SampleState = unclipped.transform(samples)
print(
f"largest |z| {np.abs(latent).max():.3f}, clip value {stats.norm.ppf(1 - 1e-6):.3f}"
)
print(
f"largest change from removing the clip {np.abs(latent - latent_unclipped).max():.1e}"
)largest |z| 3.719, clip value 4.753
largest change from removing the clip 0.0e+00
3. The round trip in the tails¶
rbig’s inverse loses accuracy in the tails, and the clip is often blamed for it. It cannot be the cause, because no training point is clipped. The cause is the one notebook 00 found: the forward map puts the sorted data at the midpoint levels, and inverse_transform interpolates them at the levels , a bug in rbig (rbig#161). The gap between neighbouring points is widest in the tails, so that is where the mismatch shows. We compare rbig’s inverse with the midpoint inverse of notebook 00.
# user
# g⁻¹(z) = the sorted data interpolated at Φ(z), on the midpoint levels
def midpoint_inverse(
marginal: rbig.MarginalGaussianize, points: SampleState
) -> SampleState:
"""The inverse of a one-dimensional ``marginal`` with the levels of its forward map."""
# (n − 1/2) / N for n = 1, …, N, (sample)
levels: PerSample = (np.arange(len(marginal.support_)) + 0.5) / len(
marginal.support_
)
# x = F̂⁻¹(Φ(z)), (sample, state)
return np.interp(stats.norm.cdf(points), levels, marginal.support_[:, 0])The two round trips, point by point:
# today (rbig)
# |g⁻¹(g(xₙ)) − xₙ| with rbig's inverse, (sample)
rbig_error: PerSample = np.abs(marginal.inverse_transform(latent) - samples)[:, 0]
# user
# |g⁻¹(g(xₙ)) − xₙ| with the midpoint inverse, (sample)
midpoint_error: PerSample = np.abs(midpoint_inverse(marginal, latent) - samples)[:, 0]
print(
f"rbig's inverse: median {np.median(rbig_error):.1e}, max {rbig_error.max():.3f} at |z| = {np.abs(latent[np.argmax(rbig_error), 0]):.2f}"
)
print(f"midpoint inverse: max {midpoint_error.max():.1e}")
# the gap between the two largest training points
top_gap: float = np.diff(np.sort(samples[:, 0])[-2:])[0]
print(f"gap between the two largest points {top_gap:.3f}")rbig's inverse: median 1.8e-04, max 1.318 at |z| = 3.72
midpoint inverse: max 8.9e-15
gap between the two largest points 2.636
The largest error of rbig’s inverse, 1.318, is at the largest point and is exactly half the gap of 2.636 between it and its neighbour: the inverse sends the largest level halfway back to the next point down. The midpoint inverse removes it to rounding error.
4. What pdf_extension changes¶
rbig.MarginalUniformize, the uniformizing half of the marginal step, has an option pdf_extension, the percentage of the data range added on each side of the support. The option does more than widen the support: any value above zero switches the fit from the empirical CDF to a histogram CDF with about bins, interpolated on a fine grid that both directions share. We measure the round trip and how Gaussian the training points come out, through the probit, for a few extensions, including a vanishing one.
# Shapes: extension = 4
for extension in (0.0, 1e-6, 5.0, 10.0):
# today (rbig)
# the uniformizing step, with the support widened by the extension in percent
uniformize = rbig.MarginalUniformize(pdf_extension=extension).fit(samples)
# today (rbig)
# uₙ = F̂(xₙ), (sample, state)
levels: SampleState = uniformize.transform(samples)
# today (rbig)
# max |F̂⁻¹(F̂(xₙ)) − xₙ|
round_trip: float = np.abs(uniformize.inverse_transform(levels) - samples).max()
# the Kolmogorov-Smirnov distance of Φ⁻¹(uₙ) to N(0, 1)
distance: float = stats.kstest(stats.norm.ppf(levels[:, 0]), "norm").statistic
print(
f"pdf_extension {extension:6g}%: round trip {round_trip:.1e}, KS of z {distance:.4f}"
)pdf_extension 0%: round trip 1.3e+00, KS of z 0.0001
pdf_extension 1e-06%: round trip 7.1e-05, KS of z 0.0049
pdf_extension 5%: round trip 1.1e-13, KS of z 0.0049
pdf_extension 10%: round trip 6.9e-14, KS of z 0.0049
A vanishing extension of 10-6% already cuts the round-trip error from 1.3 to below 10-4, and 5% takes it to rounding error: the gain comes mostly from the switch to a CDF that both directions interpolate the same way, and the extension adds only the last few digits. The switch has a cost on the way forward. The histogram CDF puts the training points about fifty times further from Gaussian than the empirical CDF does (a KS distance of 0.005 against 0.0001), though both are far inside the sampling noise of 5,000 points. Its gain is that points just past the range get a graded value instead of the clip.
# today (rbig)
# the uniformizing step with a 5% extension on each side
extended = rbig.MarginalUniformize(pdf_extension=5.0).fit(samples)
# today (rbig)
# Φ⁻¹(F̂(x)) for x_max + 0.5 and x_max + 5, (point, state), (test, state)
extended_beyond: Float[ArrayLike, "test state"] = stats.norm.ppf(
extended.transform(beyond)
)
print(f"pdf_extension 5%: z = {extended_beyond.ravel()}")pdf_extension 5%: z = [3.7106877 4.75342431]
The near point, inside the 5% extension, maps to 3.71 instead of 4.75; the far point, beyond it, is still clipped.
5. Generating beyond the range¶
Gaussianizing data needs the forward map only where the data are. Generating needs the inverse everywhere, because draws from land at any level. The empirical inverse interpolates between the sorted training points and holds the end values beyond them, so it can never generate a value above the largest training point, however many draws we take. rbig.MarginalGaussianize offers a parametric tail beyond the quantile (q_tail, 0.95 by default): with tail="pareto" the CDF above the seam is
where is the CDF of a generalised Pareto distribution fitted to the exceedances , the limit law of exceedances over a high threshold Pickands, 1975, and mirrored below . With tail="gaussian" a normal matched to two quantiles takes its place. We generate a million values with each, and compare the share above 14, where the training data are already sparse, and the number above the largest training point with the gamma’s.
# Shapes: draw = 1,000,000
# z ~ 𝒩(0, 1), (draw, state)
draws: Float[ArrayLike, "draw state"] = rng.standard_normal((1_000_000, 1))
# x = g⁻¹(z) without a tail and with each parametric tail
generated: dict[str, Float[ArrayLike, "draw state"]] = {
"empirical": marginal.inverse_transform(draws)
}
for tail in ("gaussian", "pareto"):
# today (rbig)
# the marginal step with a parametric tail beyond the 0.95 quantiles
tailed = rbig.MarginalGaussianize(tail=tail).fit(samples)
# today (rbig)
# x = g⁻¹(z) with the tail, (draw, state)
generated[tail] = tailed.inverse_transform(draws)
for name, values in generated.items():
print(
f"{name:9s} share above 14 {(values > 14).mean():.1e}, values above the training maximum {(values > samples.max()).sum()}"
)
print(
f"gamma share above 14 {stats.gamma.sf(14, 4):.1e}, values above the training maximum {1e6 * stats.gamma.sf(samples.max(), 4):.1f} expected"
)empirical share above 14 3.2e-04, values above the training maximum 0
gaussian share above 14 1.6e-04, values above the training maximum 0
pareto share above 14 5.5e-04, values above the training maximum 29
gamma share above 14 4.7e-04, values above the training maximum 13.9 expected
# today (rbig)
# the seam x_s of the Pareto marginal's upper tail
seam: float = tailed.tails_[0]["x_hi"]
# the exceedances x − x_s of the training points above the seam, (sample,), (sample)
exceedances: PerSample = samples[samples > seam] - seam
# today (scipy)
# the maximum-likelihood generalised Pareto shape of the exceedances
shape: float = stats.genpareto.fit(exceedances, floc=0)[0]
print(f"seam {seam:.2f}, free shape {shape:.3f}, rbig's tail {tailed.tails_[0]['hi']}")seam 7.82, free shape -0.034, rbig's tail {'kind': 'pareto', 'c': 0.0, 'scale': 1.3710149517688734}
The empirical inverse never goes past the training maximum, 18.3, and already falls short at 14, where only a few training points are left. The Gaussian tail is too light for the gamma and falls short too. The Pareto tail generates beyond the training maximum, but about twice as often as the gamma would (29 values against 13.9 expected), and is a little heavy at 14 as well. The maximum-likelihood shape of the exceedances is slightly negative, which rbig clamps to zero, so its tail is an exponential whose scale is the mean exceedance, 1.37. The gamma’s tail decays like an exponential of scale 1 far out, so this one is too heavy there; the Pareto tail is the right family, but its fit to the 250 points above the seam carries this much error.
# Shapes: threshold = 161
# the levels at which the shares are counted, (threshold,), (threshold)
grid: Float[ArrayLike, " threshold"] = np.linspace(8, 24, 161)
fig, ax = plt.subplots(figsize=(7.5, 4.2))
for name, values in generated.items():
ax.plot(grid, [(values > level).mean() for level in grid], lw=2, label=name)
ax.plot(grid, stats.gamma.sf(grid, 4), color=REF_COLOR, ls="--", lw=1.5, label="gamma")
ax.axvline(samples.max(), color="0.5", ls=":", lw=1)
ax.set(yscale="log", ylim=(1e-6, 0.1), xlabel="level x", ylabel="share above x")
ax.legend(fontsize=8)
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 1:The share of a million generated values above each level, for the empirical inverse and for the Gaussian and Pareto tails of rbig, against the gamma distribution the data came from; the dotted line is the largest of the 5,000 training points. The empirical inverse stops at it, the Gaussian tail falls away too fast, and the Pareto tail continues past it, somewhat heavier than the gamma.
rbig.MarginalKDEGaussianize is the smooth alternative from Part 1: a kernel density estimate whose CDF runs a little past the data. It grades the near point, still clips the far one, and inverts itself to rounding error.
# today (rbig)
# a kernel-density CDF and the probit
smooth = rbig.MarginalKDEGaussianize().fit(samples)
# today (rbig)
# zₙ = g(xₙ) through the kernel-density CDF, (sample, state)
smooth_latent: SampleState = smooth.transform(samples)
# today (rbig)
# max |g⁻¹(g(xₙ)) − xₙ|
smooth_round_trip: float = np.abs(
smooth.inverse_transform(smooth_latent) - samples
).max()
print(
f"z beyond the range {smooth.transform(beyond).ravel()}, round trip {smooth_round_trip:.1e}"
)
print(f"KS of z {stats.kstest(smooth_latent[:, 0], 'norm').statistic:.3f}")z beyond the range [4.14603782 4.75342431], round trip 6.3e-13
KS of z 0.011
The kernel smooths the training points too: their KS distance to , 0.011, is a hundred times the empirical CDF’s.
6. Discrete data¶
Counts break the empirical CDF in a different way: many points share a value, so the sorted data have long runs of ties. We draw 5,000 counts from a Poisson distribution with mean 3.
# today (numpy)
# cₙ ~ Poisson(3), (sample, state)
counts: SampleState = rng.poisson(3, size=(5000, 1)).astype(float)
# today (rbig)
# the marginal step fitted to the counts, ties and all
tied_marginal = rbig.MarginalGaussianize().fit(counts)
# today (rbig)
# zₙ = g(cₙ) with the ties left in, (sample, state)
tied_latent: SampleState = tied_marginal.transform(counts)
print(
f"{np.unique(counts).size} distinct counts give {np.unique(tied_latent).size} distinct z"
)
print(
f"mean of z {tied_latent.mean():+.3f}, standard deviation {tied_latent.std():.3f}"
)11 distinct counts give 11 distinct z
mean of z -0.375, standard deviation 1.221
# the share of zeros among the counts
zero_share: float = (counts == 0).mean()
print(
f"zeros: {zero_share:.1%} of the sample, z = {tied_latent[counts == 0].max():.2f}"
)
print(f"probit of the middle of their block {stats.norm.ppf(zero_share / 2):.2f}")zeros: 5.4% of the sample, z = -3.72
probit of the middle of their block -1.92
Each count maps to one value of , so the eleven counts become eleven atoms. Worse, the atoms are biased low: their mean is -0.37, not 0. rbig gives a new point the level , where counts the training points strictly below it, so every copy of a tied value gets the lowest level of its block. All the zeros, 5.4% of the sample, map to -3.72, the bottom of the whole range, where the middle of their block would give -1.92. This is a defect in rbig (rbig#164): the comment above the count says it counts the points at or below , and counting half of the ties (the midrank) would put each atom in the middle of its block.
Two remedies are on offer. dither=True breaks the ties with a small seeded jitter (1% of the smallest gap between values), which spreads each block over its levels. Uniform dequantisation adds to each count, which turns the counts into a continuous variable whose density bounds their probabilities from below Theis et al., 2016,
so a density fitted to the dequantised counts is a model of the counts.
# today (rbig)
# the marginal step with the ties broken by a seeded jitter
dithered = rbig.MarginalGaussianize(dither=True, random_state=0).fit(counts)
# today (rbig)
# zₙ = g(cₙ + jitter), (sample, state)
dithered_latent: SampleState = dithered.transform(counts)
# cₙ + uₙ with uₙ ~ 𝒰(0, 1), (sample, state)
dequantised: SampleState = counts + rng.uniform(0, 1, counts.shape)
# today (rbig)
# the marginal step fitted to the dequantised counts
dequantise_marginal = rbig.MarginalGaussianize().fit(dequantised)
# today (rbig)
# zₙ = g(cₙ + uₙ), (sample, state)
dequantised_latent: SampleState = dequantise_marginal.transform(dequantised)We compare the three latents, and the mean log-density of the dequantised counts with the best a model of the counts can do, minus the entropy of the Poisson distribution.
# the three latents of the counts
latents: dict[str, SampleState] = {
"ties": tied_latent,
"dither": dithered_latent,
"dequantised": dequantised_latent,
}
for name, values in latents.items():
print(
f"{name:11s} distinct z {np.unique(values).size:5d}, KS of z {stats.kstest(values[:, 0], 'norm').statistic:.3f}"
)
# today (rbig)
# log p_x(cₙ + uₙ) = log φ(zₙ) + log |g'(cₙ + uₙ)|, (sample)
log_density: PerSample = stats.norm.logpdf(
dequantised_latent[:, 0]
) + dequantise_marginal.log_det_jacobian(dequantised)
print(f"mean log-density of the dequantised counts {log_density.mean():.3f}")
print(f"minus the Poisson entropy {-stats.poisson(3).entropy():.3f}")ties distinct z 11, KS of z 0.223
dither distinct z 5000, KS of z 0.000
dequantised distinct z 5000, KS of z 0.000
mean log-density of the dequantised counts -1.945
minus the Poisson entropy -1.931
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8), sharex=True, sharey=True)
for ax, (name, values) in zip(
axes, [("ties", tied_latent), ("dequantised", dequantised_latent)], strict=True
):
ax.hist(
values[:, 0],
bins=np.linspace(-4, 4, 81),
density=True,
color=DATA_COLOR if name == "ties" else LATENT_COLOR,
)
ax.plot(
np.linspace(-4, 4, 201),
standard_normal_pdf(np.linspace(-4, 4, 201)),
color=REF_COLOR,
lw=1.5,
)
ax.set(title=name, xlabel="z")
style_ax(ax)
axes[0].set_ylabel("density")
fig.tight_layout()
plt.show()
Figure 2:Histograms of the marginal step’s output for 5,000 Poisson counts, with the standard normal density. Left: the ties map to twelve atoms, each at the bottom of its block. Right: after uniform dequantisation the output is standard normal.
Dithering and dequantisation both give an exactly standard normal output on the training counts. They differ in what the fitted map means: the dither is a device to break ties, while dequantisation makes the marginal step a density model of the counts. Its mean log-density, -1.945, is within 0.02 of minus the Poisson entropy, -1.931, the expected log-probability of the counts under the distribution they came from. Part 8 treats dequantisation as a surjection.
Recap¶
| Boundary | What rbig does | What to use |
|---|---|---|
| a point beyond the range | NaN, or the clip (1) for any distance | a tail, or pdf_extension just past the range |
| the inverse in the tails | wrong levels (rbig#161) | the midpoint inverse |
pdf_extension | a histogram CDF in both directions | a consistent round trip |
| generation beyond the range | never past the largest point | tail="pareto" (1) |
| tied values | atoms at the bottom of each block | dequantisation (2) |
The clip is a guard for new points, not a cause of error on the training data, and for Gaussianizing data the empirical CDF needs nothing else. Generation is where the boundary matters: the inverse must know what lies beyond the data, which only a parametric tail tells it.
Next. Part 4 trains the layers of a Gaussianization flow end to end by maximum likelihood, starting from the RBIG stacks of this part (RBIG as a warm start).
- Pickands, J. (1975). Statistical Inference Using Extreme Order Statistics. The Annals of Statistics, 3(1), 119–131.
- Theis, L., van den Oord, A., & Bethge, M. (2016). A Note on the Evaluation of Generative Models. International Conference on Learning Representations.