00 · The rotation zoo¶
Part 1 built the marginal map that sends one coordinate to a standard normal. A stack of such maps acts on each coordinate separately, so it can fix every marginal but never the dependence between coordinates. On correlated data it makes each coordinate look like and then stops, with the joint still far from .
The other half of Gaussianization is a rotation between marginal passes, which mixes the coordinates so that the next marginal pass has something left to do. Alternating the two is the density destructor of (3), and with a fresh rotation at every layer it is RBIG Laparra et al., 2011.
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, Int
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
DATA_COLOR,
LATENT_COLOR,
SCATTER_KW,
style_ax,
use_compact_figures,
)
rng = np.random.default_rng(0)
# Figures are stored as palette PNGs to keep the notebook small.
use_compact_figures()
watermark("numpy", "matplotlib", "rbig")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.12.0
numpy : 2.4.3
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 rotation is free¶
A rotation here is an orthogonal linear map
with . Orthogonality gives two things at once. The inverse is exact and cheap, , and since the map preserves volume, so its Jacobian adds nothing to the log-determinant of a flow,
which is the “rotations are free” term of the composition rule (4). Whitening is a rotation followed by a rescale, and the rescale is not free. With the eigendecomposition of the data covariance
where the columns of are the principal axes and the diagonal holds the variance along each, PCA whitening is , and its log-determinant is that of the diagonal,
We check both on a correlated Gaussian cloud: two coordinates that share one standard normal factor, with loadings 2 and 1.2 and independent noise of standard deviation 0.6.
# Shapes: sample (N) = 4,000; state (D_x) = 2
PerSample = Float[ArrayLike, " sample"]
# s ~ 𝒩(0, 1), the shared factor, (sample)
factor: PerSample = rng.standard_normal(4000)
# ε ~ 𝒩(0, 0.6² I), the noise of each coordinate, (sample, state)
noise: Float[ArrayLike, "sample state"] = 0.6 * rng.standard_normal((4000, 2))
SampleState = Float[ArrayLike, "sample state"]
# x = (2 s, 1.2 s) + ε, (sample, state)
correlated: SampleState = np.outer(factor, [2.0, 1.2]) + noiserbig.PCARotation rotates onto the principal axes, and with whiten=True it also applies .
# today (rbig)
# fit Q = Vᵀ to the data
pca_rotation = rbig.PCARotation(whiten=False).fit(correlated)
# today (rbig)
# fit Λ^(−1/2) Vᵀ to the data
pca_whitening = rbig.PCARotation(whiten=True).fit(correlated)
# today (rbig)
# log |det Q| at each sample, (sample)
rotation_logdet: PerSample = pca_rotation.log_det_jacobian(correlated)
# today (rbig)
# log |det J| of whitening at each sample, (sample)
whitening_logdet: PerSample = pca_whitening.log_det_jacobian(correlated)We compare the whitening log-determinant with (4), from the eigenvalues of the sample covariance.
# Shapes: state (D_x) = 2
# the diagonal of Λ, the eigenvalues of the sample covariance Σ_x, (state)
principal_variances: Float[ArrayLike, " state"] = np.linalg.eigvalsh(
np.cov(correlated.T)
)
# −½ log det Λ
formula_logdet: float = -0.5 * np.sum(np.log(principal_variances))
print(f"rotation only : log|det J| = {np.mean(rotation_logdet):+.4f}")
print(f"whitening : log|det J| = {np.mean(whitening_logdet):+.4f}")
print(f"formula : log|det J| = {formula_logdet:+.4f}")rotation only : log|det J| = +0.0000
whitening : log|det J| = -0.3698
formula : log|det J| = -0.3698
The rotation costs nothing and the whitening log-determinant is (4) to every digit printed. Most RBIG variants keep the rotation pure and let the marginal step do any rescaling, which keeps the bookkeeping clean.
2. The rotation zoo¶
The rotations in rbig differ only in how they choose .
| Rotation | How is chosen | What it finds |
|---|---|---|
| PCA | the eigenvectors of the covariance (3) | the directions of largest variance |
| random | Haar-uniform on the orthogonal group, from a QR factorisation (5) | nothing; it costs no fitting |
| ICA Hyvärinen & Oja, 2000 | the rotation whose outputs are most independent (6) | non-Gaussian directions |
A random rotation factorises a matrix of independent standard normal entries,
into an orthogonal and an upper-triangular , and flips the sign of each column of where the diagonal of is negative, which makes uniform on the orthogonal group. ICA asks for the rotation that makes the output coordinates as independent as possible. A rotation keeps the joint entropy, , so in the total correlation (5) of the rotated data
only the sum of marginal entropies depends on , and the most independent rotation is the one with the smallest sum. rbig.ICARotation and rbig.PicardRotation both fit it with the Picard algorithm Ablin et al., 2018 when the picard package is installed, as it is here, so they agree.
PCA sees only the covariance, so to tell the rotations apart we use data whose covariance carries no information: two independent Laplace sources of unit variance, mixed by a 30° rotation. The covariance is close to , so every rotation leaves it unchanged, but the source axes are where the marginals are most non-Gaussian.
# Shapes: sample (N) = 4,000; state (D_x) = 2
# sources sᵢ ~ Laplace with unit variance, (sample, state)
sources: SampleState = rng.laplace(size=(4000, 2)) / np.sqrt(2)
StateMatrix = Float[ArrayLike, "state state"]
# the 30° mixing rotation, (state, state)
mixing: StateMatrix = np.array(
[[np.cos(np.pi / 6), -np.sin(np.pi / 6)], [np.sin(np.pi / 6), np.cos(np.pi / 6)]]
)
# x = M s, (sample, state)
mixed: SampleState = sources @ mixing.TWe fit each rotation and score it two ways: the sum of marginal entropies of its output, which is the part of (6) a rotation can change, and the angle between its first output axis and the nearest source axis. rbig.marginal_entropy estimates each entropy from a kernel density.
# Shapes: latent (D_x) = 2
LatentState = Float[ArrayLike, "latent state"]
# user
# the angle between the first output axis and the nearest source axis, in degrees
def angle_to_sources(rotation: LatentState) -> float:
"""The angle between ``rotation``'s first row, mapped back to the sources, and a source axis."""
# Q M, the map from sources to outputs, (latent, state)
sources_to_outputs: LatentState = rotation @ mixing
# the angle of its first row against the first source axis
angle: float = np.degrees(np.arctan2(*np.abs(sources_to_outputs[0, ::-1])))
return min(angle, 90.0 - angle)rbig keeps the fitted matrix in a different attribute for each rotation, and PCA also subtracts the mean, so we read back from the transform itself: the images of the basis vectors minus the image of the origin.
# user
# Q, from z = Q (x − x̄): column j is the image of e_j minus the image of 0
def matrix_of(rotation) -> LatentState:
"""The orthogonal matrix of a fitted ``rbig`` rotation."""
# today (rbig)
# Q eⱼ − Q 0 for each basis vector eⱼ, as rows, (state, latent)
images: Float[ArrayLike, "state latent"] = rotation.transform(
np.eye(2)
) - rotation.transform(np.zeros((1, 2)))
return images.TNow we fit each rotation and score it.
# today (rbig)
# the three rotations, before fitting
rotations = {
"PCA": rbig.PCARotation(whiten=False),
"random": rbig.RandomRotation(random_state=0),
"ICA (rbig)": rbig.ICARotation(random_state=0),
}
SampleLatent = Float[ArrayLike, "sample latent"]
rotated = {}
for name, rotation in rotations.items():
# today (rbig)
# fit Q to the mixed data
rotation.fit(mixed)
# today (rbig)
# z = Q x, (sample, latent)
rotated[name]: SampleLatent = rotation.transform(mixed)
# user
# Q, read back from the fitted rotation, (latent, state)
matrix: LatentState = matrix_of(rotation)
# today (rbig)
# ∑_d H[p_{z_d}], estimated by kernel densities
entropy_sum: float = np.sum(rbig.marginal_entropy(rotated[name]))
print(f"{name:11s} ∑ H = {entropy_sum:.3f}, angle {angle_to_sources(matrix):4.1f}°")PCA ∑ H = 2.649, angle 2.4°
random ∑ H = 2.708, angle 18.9°
ICA (rbig) ∑ H = 2.735, angle 29.0°
In this draw PCA lands within a few degrees of the sources and rbig’s ICA about 30° away, with a larger entropy sum than PCA. Both results are misleading, and the next section shows why.
3. Orthogonal ICA in rbig¶
Picard first whitens the data with a matrix and then finds an orthogonal unmixing for the whitened data, so the full unmixing is . To stay orthogonal, rbig.ICARotation with orthogonal=True applies alone. But is not just a rescale: it also rotates the data into Picard’s own frame, and is correct only in that frame. Dropping drops that rotation too, so is applied in the wrong frame even when the data are already white, as here. rbig.PicardRotation does the same.
The orthogonal part of , the factor of its singular value decomposition , keeps that rotation and drops only the rescale, so is orthogonal. For white data, as here, it is Picard’s full unmixing; for data that are not white it keeps Picard’s frame and drops its rescale.
# user
# Q = W U_K V_Kᵀ, the orthogonal ICA rotation
def orthogonal_ica(ica: rbig.ICARotation) -> LatentState:
"""The orthogonal ICA rotation of a fitted ``rbig.ICARotation``."""
left: StateMatrix
right: StateMatrix
# today (rbig)
# K = U_K diag(·) V_Kᵀ, the SVD of Picard's whitening matrix
left, _, right = np.linalg.svd(ica.K_)
# today (rbig)
# Q = W U_K V_Kᵀ, (latent, state)
return ica.W_ @ left @ rightWe apply it to the same fit, check that it is orthogonal, and score it like the others.
# user
# Q = W U_K V_Kᵀ, (latent, state)
corrected_ica: LatentState = orthogonal_ica(rotations["ICA (rbig)"])
# z = Q x, (sample, latent)
rotated["ICA (corrected)"]: SampleLatent = mixed @ corrected_ica.T
# today (rbig)
# ∑_d H[p_{z_d}], estimated by kernel densities
corrected_entropy_sum: float = np.sum(rbig.marginal_entropy(rotated["ICA (corrected)"]))
# max |QᵀQ − I|
orthogonality_gap: float = np.max(np.abs(corrected_ica.T @ corrected_ica - np.eye(2)))
print(
f"ICA (corr.) ∑ H = {corrected_entropy_sum:.3f}, angle {angle_to_sources(corrected_ica):4.1f}°"
)
print(f"max |Q^T Q - I| = {orthogonality_gap:.1e}")ICA (corr.) ∑ H = 2.648, angle 1.4°
max |Q^T Q - I| = 7.8e-16
panels = {"data": mixed, **rotated}
fig, axes = plt.subplots(1, len(panels), figsize=(17, 3.8), sharex=True, sharey=True)
for ax, (name, points) in zip(axes, panels.items(), strict=True):
color = DATA_COLOR if name == "data" else LATENT_COLOR
ax.scatter(points[:, 0], points[:, 1], color=color, **SCATTER_KW)
to_frame = np.eye(2)
if name in rotations:
to_frame = matrix_of(rotations[name])
if name == "ICA (corrected)":
to_frame = corrected_ica
axes_in_frame = to_frame @ mixing
for column in axes_in_frame.T:
ax.plot(*np.outer([-6, 6], column).T, "k--", lw=1)
ax.set(title=name, xlabel="first coordinate", xlim=(-6, 6), ylim=(-6, 6))
style_ax(ax)
axes[0].set_ylabel("second coordinate")
fig.tight_layout()
plt.show()
Figure 1:The same mixed Laplace data (left) in the frame each rotation chooses. The dashed lines are the source axes carried into that frame, and a rotation that finds the sources lines them up with the coordinate axes. In this draw PCA and the corrected ICA do, the random rotation and rbig’s orthogonal ICA do not.
The corrected rotation is orthogonal to machine precision, has the smallest entropy sum and lies within about a degree of the source axes. PCA’s good result in this draw was luck: the covariance of the sources is , so every frame is a principal frame and PCA’s axes are set by sampling noise. We repeat the fit on 20 fresh draws.
# Shapes: draw = 20 fresh data sets
angles = {"PCA": [], "ICA (rbig)": [], "ICA (corrected)": []}
for _ in range(20):
# x = M s for fresh Laplace sources, (sample, state)
draw: SampleState = rng.laplace(size=(4000, 2)) / np.sqrt(2) @ mixing.T
# today (rbig)
# fit Q = Vᵀ to the draw
pca = rbig.PCARotation(whiten=False).fit(draw)
# today (rbig)
# fit Picard's K and W to the draw
ica = rbig.ICARotation(random_state=0).fit(draw)
# user
# PCA's angle to the sources
angles["PCA"].append(angle_to_sources(matrix_of(pca)))
# user
# the angle of rbig's orthogonal ICA
angles["ICA (rbig)"].append(angle_to_sources(matrix_of(ica)))
# user
# the angle of the corrected ICA
angles["ICA (corrected)"].append(angle_to_sources(orthogonal_ica(ica)))We summarise each rotation’s angle over the 20 draws.
for name, values in angles.items():
print(
f"{name:15s} angle: median {np.median(values):4.1f}°, max {np.max(values):4.1f}°"
)PCA angle: median 12.4°, max 38.8°
ICA (rbig) angle: median 35.3°, max 45.0°
ICA (corrected) angle: median 0.5°, max 3.8°
Over 20 draws PCA’s axes wander up to about 40° from the sources, rbig’s orthogonal ICA is off by about 35° at the median, and the corrected ICA stays within 4°. PCA cannot see structure that the covariance does not carry, and ICA can, once it is applied in the right frame.
4. Marginal passes stall, a rotation unsticks them¶
Now the reason rotations matter. We take the correlated Gaussian cloud of section 1, where only the dependence stands between the data and , and run eight marginal passes three ways: alone, with a PCA rotation after each pass, and with a fresh random rotation after each pass. We track the total correlation (5), which is zero exactly when the coordinates are independent.
rbig.total_correlation estimates the marginal entropies with kernel densities and the joint entropy by fitting a Gaussian. The Gaussian fit suits this cloud, which stays close to Gaussian under every marginal pass and rotation, so the estimate is accurate here; its small negative values are estimation noise.
# user
# one marginal pass, z_d = Φ⁻¹(F̂_d(x_d)) for each coordinate d
def marginal_pass(points: SampleState) -> SampleState:
"""One marginal Gaussianization pass, fitted to ``points``."""
# today (rbig)
# fit F̂_d to each coordinate
gaussianize = rbig.MarginalGaussianize().fit(points)
# today (rbig)
# z_d = Φ⁻¹(F̂_d(x_d)), (sample, state)
return gaussianize.transform(points)
# user
# z = Q x, with Q fitted to the points
def rotate(rotation, points: SampleState) -> SampleState:
"""Fit an ``rbig`` rotation to ``points`` and apply it."""
# today (rbig)
# fit Q to the points
rotation.fit(points)
# today (rbig)
# z = Q x, (sample, state)
return rotation.transform(points)Each scheme starts from the same cloud and records the total correlation before the first pass and after each one.
# Shapes: step = 9, the data and the 8 passes
PerStep = Float[ArrayLike, " step"]
# user
# TC of the data, then after each of eight passes, (step)
def run_scheme(new_rotation) -> PerStep:
"""Eight marginal passes, each followed by ``new_rotation(step)`` when given."""
# x⁽⁰⁾ = x, (sample, state)
points: SampleState = correlated
# today (rbig)
# TC[p_x] of the data
history = [rbig.total_correlation(points)]
for step in range(8):
# user
# z_d = Φ⁻¹(F̂_d(x_d)), (sample, state)
points = marginal_pass(points)
if new_rotation is not None:
# user
# z = Q x, a fresh rotation fitted to the current points, (sample, state)
points = rotate(new_rotation(step), points)
# today (rbig)
# TC after this pass
history.append(rbig.total_correlation(points))
return np.array(history)We run it with no rotation, a PCA rotation and a fresh random rotation after each pass.
# today (rbig)
# the rotation after each pass, if any
schemes = {
"marginal only": None,
"marginal + PCA rotation": lambda step: rbig.PCARotation(whiten=False),
"marginal + random rotation": lambda step: rbig.RandomRotation(random_state=step),
}
# user
# the TC history of each scheme, (step)
histories: dict[str, PerStep] = {
label: run_scheme(new_rotation) for label, new_rotation in schemes.items()
}
for label, history in histories.items():
print(f"{label:27s} TC: " + " ".join(f"{value:6.3f}" for value in history))marginal only TC: 0.647 0.651 0.651 0.651 0.651 0.651 0.651 0.651 0.651
marginal + PCA rotation TC: 0.647 -0.005 -0.005 -0.000 0.000 0.000 0.000 0.000 0.000
marginal + random rotation TC: 0.647 0.594 -0.002 -0.002 -0.001 -0.002 -0.000 -0.001 0.000
For the figure we also keep the points after eight passes of the first two schemes.
# x⁽⁰⁾ = x for marginal passes alone, (sample, state)
stalled: SampleState = correlated
# x⁽⁰⁾ = x for marginal passes with PCA rotations, (sample, state)
unstuck: SampleState = correlated
for _ in range(8):
# user
# one marginal pass alone, (sample, state)
stalled = marginal_pass(stalled)
# user
# one marginal pass, (sample, state)
unstuck = marginal_pass(unstuck)
# user
# z = Q x with a PCA rotation, (sample, state)
unstuck = rotate(rbig.PCARotation(whiten=False), unstuck)fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
colors = {
"marginal only": "C3",
"marginal + PCA rotation": "C2",
"marginal + random rotation": "C0",
}
for label, history in histories.items():
axes[0].plot(history, "o-", color=colors[label], lw=2, ms=5, label=label)
axes[0].axhline(0, color="k", lw=1.5, ls="--", label="independent, TC = 0")
axes[0].set(xlabel="pass", ylabel="total correlation (nats)", title="Total correlation")
axes[0].legend(fontsize=8)
axes[1].scatter(
stalled[:, 0], stalled[:, 1], color="C3", label="marginal only", **SCATTER_KW
)
axes[1].scatter(
unstuck[:, 0], unstuck[:, 1], color="C2", label="with PCA rotations", **SCATTER_KW
)
axes[1].set(
xlabel="$z_1$",
ylabel="$z_2$",
xlim=(-4, 4),
ylim=(-4, 4),
title="After eight passes",
)
axes[1].legend(fontsize=8, loc="upper left")
for ax in axes:
style_ax(ax)
fig.tight_layout()
plt.show()
Figure 2:Left: the total correlation over eight passes. Marginal passes alone leave it where it started, while a PCA rotation after each pass removes it in one pass and a random rotation in two. Right: the points after eight passes. Marginal passes alone leave a tilted ellipse with standard normal marginals; with rotations the cloud is isotropic.
Marginal passes alone leave the total correlation at about 0.65 nats from start to finish. Each pass makes both coordinates standard normal, but the cloud stays a tilted ellipse. With a PCA rotation after each pass the total correlation is gone after one pass, and with a random rotation after two. We count the passes to .
for label, history in histories.items():
# the passes with |TC| < 0.01, (step)
below: Int[ArrayLike, " step"] = np.flatnonzero(np.abs(history) < 1e-2)
# the first of them, if any
passes: int | str = below[0] if below.size else "never"
print(f"{label:27s} passes to TC < 0.01: {passes}")marginal only passes to TC < 0.01: never
marginal + PCA rotation passes to TC < 0.01: 1
marginal + random rotation passes to TC < 0.01: 2
5. Why the rotation is what removes dependence¶
The KL divergence from splits into the total correlation and one KL term per marginal (3). The two steps of a layer act on different terms.
A marginal pass applies an invertible map to each coordinate separately. That changes each marginal entropy and the joint entropy by the same log-derivatives, so the total correlation does not move,
for any coordinate-wise invertible , while the marginal KL terms drop to zero. A rotation leaves the total unchanged instead, because looks the same in every orthogonal frame,
but it moves divergence between the terms: part of the total correlation comes back as non-Gaussian marginals, which the next marginal pass removes. So each layer lowers the total by whatever the rotation moved into the marginals Laparra et al., 2011, and a rotation that moves more converges faster. The flat red line of Figure 2 is (7) measured. PCA wins here because after a marginal pass this cloud is a correlated Gaussian, whose dependence a decorrelating rotation turns into marginal structure all at once; on non-Gaussian data ICA can move more. Part 3 studies rotation choice properly.
Recap¶
| Idea | Equation | In code |
|---|---|---|
| a rotation | (1) | rbig.PCARotation, rbig.RandomRotation, rbig.ICARotation |
| its log-determinant is zero | (2) | log_det_jacobian |
| whitening is not free | (3), (4) | PCARotation(whiten=True) |
| random rotations | (5) | rbig.RandomRotation |
| ICA minimises the marginal entropies | (6) | rbig.ICARotation, with for an orthogonal map |
| marginal passes keep TC | (7) | Figure 2 |
| rotations keep the total KL | (8) | Figure 2 |
Next. A PCA or random rotation is fixed once fitted. To learn a rotation inside a flow by gradient descent we need an orthogonal matrix that stays orthogonal under every update. The next notebook builds two: a product of Householder reflections and the Cayley map.
- 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
- Hyvärinen, A., & Oja, E. (2000). Independent Component Analysis: Algorithms and Applications. Neural Networks, 13(4–5), 411–430.
- Ablin, P., Cardoso, J.-F., & Gramfort, A. (2018). Faster Independent Component Analysis by Preconditioning with Hessian Approximations. IEEE Transactions on Signal Processing, 66(15), 4040–4049.