Rotation choices
The rotation between marginal steps does not change where RBIG ends, but it sets how many layers the loop needs, and some rotations never get there
02 · Rotation choices¶
Every RBIG layer ends in a rotation, and notebook 00 already showed that the choice matters: with PCA rotations the loop stalled on two moons, with random rotations it did not. By (3) a layer removes the marginal divergence its rotation exposes, so a rotation that turns the remaining dependence into non-Gaussian marginals converges fast, and one that exposes nothing stalls. We compare the four rotations of rbig on three datasets, counting the layers each needs to pass the projection test (3).
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.*")
# Picard warns when it stops short of its tolerance, which it does in the layers where a loop has stalled.
warnings.filterwarnings("ignore", message=r"Picard did not converge.*")
import matplotlib.pyplot as plt
import numpy as np
import rbig
from jaxtyping import ArrayLike, Float
from scipy import stats
from sklearn.datasets import make_moons
from gauss_flows_docs.environment import watermark
from gauss_flows_docs.plotting import (
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", "scipy", "matplotlib", "scikit-learn", "rbig", "picard")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
scikit-learn: 1.8.0
rbig : 0.1.16
picard : 0.8.2
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. The yardstick and the rotations¶
We measure how Gaussian the state is with the projection test of notebook 00: the largest Kolmogorov–Smirnov distance to over unit directions , here drawn uniformly on the sphere so that the test works in any dimension. A loop has converged when the statistic is below its 95% quantile on standard-normal samples of the same size.
# Shapes: sample (N) = 2,000; state (D_x) = 2 or 4; direction (J) = 64
SampleState = Float[ArrayLike, "sample state"]
DirectionState = Float[ArrayLike, "direction state"]
# user
# J unit directions eⱼ, uniform on the sphere, (direction, state)
def unit_directions(dimension: int) -> DirectionState:
"""Sixty-four fixed unit directions in ``dimension`` dimensions."""
# gⱼ ~ 𝒩(0, I), (direction, state)
draws: DirectionState = np.random.default_rng(7).standard_normal((64, dimension))
# eⱼ = gⱼ / ‖gⱼ‖, (direction, state)
return draws / np.linalg.norm(draws, axis=1, keepdims=True)The statistic and its null quantile follow.
# user
# KS_max = maxⱼ supₜ |F̂_{N,j}(t) − Φ(t)|
def projection_ks(points: SampleState) -> float:
"""The largest Kolmogorov-Smirnov distance of a projection of ``points`` to N(0, 1)."""
# user
# eⱼ for the dimension of the points, (direction, state)
directions: DirectionState = unit_directions(points.shape[1])
# eⱼᵀ xₙ, (sample, direction)
projections: Float[ArrayLike, "sample direction"] = points @ directions.T
return max(stats.kstest(projections[:, j], "norm").statistic for j in range(64))
# user
# the 95% quantile of KS_max on 30 standard-normal samples of 2,000 points
def null_threshold(dimension: int) -> float:
"""The 95% quantile of ``projection_ks`` on standard-normal data."""
return np.quantile(
[projection_ks(rng.standard_normal((2000, dimension))) for _ in range(30)], 0.95
)Two of the rotations need care. rbig.ICARotation and rbig.PicardRotation fit Picard’s whitening matrix and unmixing Ablin et al., 2018, and in their default orthogonal mode they apply without the rotation part of , which puts in the wrong frame. That is a bug in rbig (rbig#159), worked through in Part 2. Until it is fixed we apply the orthogonal rotation ourselves, where .
StateMatrix = Float[ArrayLike, "state state"]
# user
# Q = W U_K V_Kᵀ, the orthogonal ICA rotation
def orthogonal_ica(ica: rbig.ICARotation | rbig.PicardRotation) -> StateMatrix:
"""The orthogonal rotation of a fitted ``rbig`` ICA or Picard rotation."""
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ᵀ, (state, state)
return ica.W_ @ left @ rightOne layer fits the marginal step and the rotation to the current state. We compare five rotations: PCA, a fresh random rotation in every layer, rbig’s orthogonal ICA as it is, ICA with the corrected frame, and rbig’s Picard rotation with the corrected frame.
# today (rbig)
# the unfitted rotation of each kind for layer k
def make_rotation(
kind: str, k: int
) -> rbig.PCARotation | rbig.RandomRotation | rbig.ICARotation | rbig.PicardRotation:
"""A fresh ``rbig`` rotation of ``kind`` for layer ``k``."""
if kind == "PCA":
return rbig.PCARotation(whiten=False)
if kind == "random":
return rbig.RandomRotation(random_state=k)
if kind == "Picard":
return rbig.PicardRotation(random_state=0)
if kind == "Picard, extended":
return rbig.PicardRotation(extended=True, random_state=0)
return rbig.ICARotation(random_state=0)The layer applies the fitted rotation, through transform for the first three kinds and through the corrected matrix for the last two.
# the kinds whose rotation is applied through the corrected frame
CORRECTED: set[str] = {"ICA", "Picard", "Picard, extended"}
# user
# x_k = Q_k g_k(x_{k−1})
def rbig_layer(points: SampleState, kind: str, k: int) -> SampleState:
"""One RBIG layer with a ``kind`` rotation, fitted to ``points``."""
# today (rbig)
# fit ĝ_k to each coordinate of x_{k−1}
marginal = rbig.MarginalGaussianize().fit(points)
# today (rbig)
# g_k(x_{k−1}), (sample, state)
marginalised: SampleState = marginal.transform(points)
# today (rbig)
# fit Q_k to g_k(x_{k−1})
rotation: (
rbig.PCARotation | rbig.RandomRotation | rbig.ICARotation | rbig.PicardRotation
) = make_rotation(kind, k).fit(marginalised)
if kind in CORRECTED:
# user
# Q_k g_k(x_{k−1}) with the corrected frame, (sample, state)
return marginalised @ orthogonal_ica(rotation).T
# today (rbig)
# Q_k g_k(x_{k−1}), (sample, state)
return rotation.transform(marginalised)The loop runs fifteen layers and records the projection statistic after each.
# Shapes: layer (K) = 15
PerLayer = Float[ArrayLike, " layer"]
KINDS = ["PCA", "random", "ICA (rbig)", "ICA", "Picard"]
# user
# KS_max of x_k for k = 1, …, K
def ks_trace(points: SampleState, kind: str, n_layers: int = 15) -> PerLayer:
"""Run ``n_layers`` RBIG layers with ``kind`` rotations, recording KS_max after each."""
# KS_max of x_1, …, x_k so far
trace: list[float] = []
for k in range(n_layers):
# user
# x_k, (sample, state)
points: SampleState = rbig_layer(points, kind, k)
# user
# KS_max of x_k
trace.append(projection_ks(points))
return np.array(trace)Two small helpers read the first layer at which a trace passes the test, and run every rotation on a dataset.
# user
# the first k with KS_max of x_k below the threshold, or never
def first_pass(trace: PerLayer, threshold: float) -> str:
"""The first layer at which ``trace`` is below ``threshold``."""
# indices of the layers that pass, (layer,), (layer)
passed: Float[ArrayLike, " layer"] = np.flatnonzero(trace < threshold)
return f"layer {passed[0] + 1}" if passed.size else "never"
# user
# KS_max traces of every kind on one dataset, and the layer at which each passes
def compare(points: SampleState) -> tuple[dict[str, PerLayer], float]:
"""Run all five rotations on ``points`` and report the layer each passes the test."""
# user
# the 95% quantile of KS_max on standard-normal data
threshold: float = null_threshold(points.shape[1])
# user
# the KS_max trace of each kind
traces: dict[str, PerLayer] = {kind: ks_trace(points, kind) for kind in KINDS}
for kind, trace in traces.items():
print(
f"{kind:11s} passes at {first_pass(trace, threshold):9s} KS_max after 15 layers {trace[-1]:.3f}"
)
print(f"null 95% quantile {threshold:.3f}")
return traces, threshold2. A correlated Gaussian¶
The first dataset is four correlated Gaussian coordinates, standardised.
# Shapes: state (D_x) = 4
# the upper-triangular mixing matrix, (state, state)
gaussian_mixing: StateMatrix = np.array(
[[1, 0.8, 0.6, 0.4], [0, 1, 0.7, 0.5], [0, 0, 1, 0.6], [0, 0, 0, 1.0]]
)
# x = A w with w ~ 𝒩(0, I), (sample, state)
correlated: SampleState = rng.standard_normal((2000, 4)) @ gaussian_mixing.T
# x standardised per coordinate, (sample, state)
correlated: SampleState = (correlated - correlated.mean(axis=0)) / correlated.std(
axis=0
)
# user
# the KS_max traces and the threshold
results: dict[str, tuple[dict[str, PerLayer], float]] = {
"correlated Gaussian": compare(correlated)
}PCA passes at layer 2 KS_max after 15 layers 0.017
random passes at layer 13 KS_max after 15 layers 0.022
ICA (rbig) passes at layer 10 KS_max after 15 layers 0.018
ICA passes at layer 8 KS_max after 15 layers 0.016
Picard passes at never KS_max after 15 layers 0.112
null 95% quantile 0.039
PCA passes after two layers: its first rotation decorrelates the Gaussian, which makes the coordinates independent, and the second marginal step only rescales them. Random rotations take thirteen layers to stumble on the same result. ICA has nothing to find, because a decorrelated Gaussian looks the same in every orthogonal frame and has no non-Gaussian direction, so its rotation is arbitrary; it passes after eight layers with the corrected frame and ten without. The Picard rotation never passes, for a reason section 5 explains.
3. Rotated independent sources¶
The second dataset is the one ICA is made for: four independent unit-variance sources, two uniform (lighter tails than a Gaussian, sub-Gaussian) and two Laplace (heavier, super-Gaussian), rotated by a fixed random orthogonal matrix. The data are white, so PCA has no variance differences to align with.
# s, two uniform and two Laplace sources of unit variance, (sample, state)
sources: SampleState = np.column_stack(
[
rng.uniform(-np.sqrt(3), np.sqrt(3), (2000, 2)),
rng.laplace(0, 1 / np.sqrt(2), (2000, 2)),
]
)
# today (scipy)
# a fixed random orthogonal matrix, (state, state)
source_rotation: StateMatrix = stats.ortho_group.rvs(4, random_state=1)
# x = M s, (sample, state)
rotated_sources: SampleState = sources @ source_rotation.T
# user
# the KS_max traces and the threshold
results["rotated sources"] = compare(rotated_sources)PCA passes at layer 2 KS_max after 15 layers 0.022
random passes at layer 4 KS_max after 15 layers 0.025
ICA (rbig) passes at layer 3 KS_max after 15 layers 0.039
ICA passes at layer 2 KS_max after 15 layers 0.021
Picard passes at never KS_max after 15 layers 0.051
null 95% quantile 0.040
ICA with the corrected frame passes after two layers: its first rotation recovers the sources, which the second marginal step makes Gaussian. On this draw PCA does as well, random rotations need four layers and rbig’s orthogonal ICA as it is needs three, because its rotation misses the sources. The Picard rotation stays above the threshold. One draw is a thin basis for ranking rotations that differ by a layer or two, so we repeat the run on five fresh draws of the sources and their rotation, for eight layers each.
# user
# x = M s for a fresh draw of the sources and of M, (sample, state)
def rotated_source_draw(seed: int) -> SampleState:
"""Two uniform and two Laplace sources, rotated at random, from ``seed``."""
# s, two uniform and two Laplace sources of unit variance, (sample, state)
draw_sources: SampleState = np.column_stack(
[
np.random.default_rng(seed).uniform(-np.sqrt(3), np.sqrt(3), (2000, 2)),
np.random.default_rng(seed + 100).laplace(0, 1 / np.sqrt(2), (2000, 2)),
]
)
# today (scipy)
# x = M s for a random orthogonal M, (sample, state)
return draw_sources @ stats.ortho_group.rvs(4, random_state=seed).T# Shapes: draw = 5; layer (K) = 8
# the 95% quantile of KS_max on standard-normal data
source_threshold: float = results["rotated sources"][1]
for seed in range(10, 15):
# user
# x for draw seed, (sample, state)
draw_mixed: SampleState = rotated_source_draw(seed)
# user
# the first passing layer of each kind within eight layers
passes: list[str] = [
first_pass(ks_trace(draw_mixed, kind, 8), source_threshold) for kind in KINDS
]
print(
f"draw {seed - 9}: "
+ ", ".join(
f"{kind} {first}" for kind, first in zip(KINDS, passes, strict=True)
)
)draw 1: PCA layer 4, random layer 3, ICA (rbig) never, ICA layer 2, Picard never
draw 2: PCA layer 4, random layer 5, ICA (rbig) layer 5, ICA layer 2, Picard never
draw 3: PCA layer 3, random layer 7, ICA (rbig) layer 6, ICA layer 2, Picard never
draw 4: PCA layer 4, random layer 2, ICA (rbig) layer 7, ICA layer 2, Picard layer 2
draw 5: PCA layer 5, random layer 7, ICA (rbig) layer 8, ICA layer 2, Picard never
ICA with the corrected frame passes at layer two on every draw. PCA needs three to five layers, random rotations two to seven, and rbig’s orthogonal ICA as it is five to eight or never. The Picard rotation passes on one draw in five.
4. Two moons¶
The third dataset is the two moons of notebook 00, whose dependence is curved, so no single rotation removes it.
# Shapes: state (D_x) = 2
# today (scikit-learn)
# two interleaved half circles with noise of standard deviation 0.07, (sample, state)
moons: SampleState = make_moons(n_samples=2000, noise=0.07, random_state=0)[0]
# x standardised per coordinate, (sample, state)
moons: SampleState = (moons - moons.mean(axis=0)) / moons.std(axis=0)
# user
# the KS_max traces and the threshold
results["two moons"] = compare(moons)PCA passes at never KS_max after 15 layers 0.055
random passes at layer 11 KS_max after 15 layers 0.042
ICA (rbig) passes at never KS_max after 15 layers 0.160
ICA passes at layer 4 KS_max after 15 layers 0.019
Picard passes at never KS_max after 15 layers 0.148
null 95% quantile 0.040
fig, axes = plt.subplots(1, 3, figsize=(15, 4.2), sharey=True)
for ax, (name, (traces, threshold)) in zip(axes, results.items(), strict=True):
for kind, trace in traces.items():
ax.plot(np.arange(1, 16), trace, "o-", ms=3, label=kind)
ax.axhline(threshold, color="0.5", lw=1)
ax.set(title=name, xlabel="layer k", yscale="log")
style_ax(ax)
axes[0].set_ylabel("KS_max of x_k")
axes[0].legend(fontsize=8)
fig.tight_layout()
plt.show()
Figure 1:The projection statistic KS_max after each of fifteen RBIG layers, for five rotations on three datasets; the loop has converged once the statistic is below the grey line, its 95% quantile on standard-normal data. PCA wins on the correlated Gaussian and stalls on two moons; ICA with the corrected frame ties with PCA on the rotated sources and wins on two moons; rbig’s orthogonal ICA as it is and rbig’s Picard rotation stall on two moons.
On two moons PCA stalls above the threshold, as in notebook 00, and random rotations first pass after eleven layers and end on the threshold. ICA with the corrected frame first passes after four, hovers near the threshold until layer ten and ends at half of it: after a marginal step the moons are a cloud with a few non-Gaussian directions, and ICA turns them onto the axes, where the next marginal step removes them. rbig’s orthogonal ICA as it is and the Picard rotation both stall far from Gaussian, worse than PCA. We look at where four of the loops are after fifteen layers.
# Shapes: layer (K) = 15
# user
# x_15 for four of the rotations, (sample, state)
after_fifteen: dict[str, SampleState] = {}
for kind in ["PCA", "random", "ICA (rbig)", "ICA"]:
# x_0, the standardised moons, (sample, state)
state: SampleState = moons
for k in range(15):
# user
# x_k, (sample, state)
state: SampleState = rbig_layer(state, kind, k)
after_fifteen[kind] = statefig, axes = plt.subplots(1, 4, figsize=(15, 4), sharex=True, sharey=True)
for ax, (kind, state) in zip(axes, after_fifteen.items(), strict=True):
ax.scatter(state[:, 0], state[:, 1], color=LATENT_COLOR, **SCATTER_KW)
ax.set(title=kind, xlabel="first coordinate", xlim=(-4, 4), ylim=(-4, 4))
ax.set_aspect("equal")
style_ax(ax)
axes[0].set_ylabel("second coordinate")
fig.tight_layout()
plt.show()
Figure 2:Two moons after fifteen RBIG layers with four rotations. PCA and rbig’s orthogonal ICA as it is have each stalled on a shape of arms; random rotations leave faint arms; ICA with the corrected frame is close to a round cloud, with faint bands left.
5. ICA and Picard¶
rbig.ICARotation and rbig.PicardRotation call the same solver, picard.picard Ablin et al., 2018, with orthogonal constraints; they differ only in the options they pass, so Picard is not a different, faster ICA here.
The option that matters is extended. Picard’s extended=True lets each component be sub-Gaussian or super-Gaussian, and the solver turns it on by default when the rotation is orthogonal. rbig.ICARotation keeps that default, but rbig.PicardRotation passes extended=False, which assumes every source is super-Gaussian. We fit both to two uniform sources, which are sub-Gaussian, with the full unmixing , so the frame bug plays no part, and score the separation with the Amari index, which is 0 for a perfect separation and grows towards 1 as the unmixing misses.
# Shapes: state (D_x) = 2
# s, two uniform sources of unit variance, (sample, state)
uniform_sources: SampleState = rng.uniform(-np.sqrt(3), np.sqrt(3), (4000, 2))
# M, a rotation by 30°, (state, state)
thirty_degrees: StateMatrix = stats.special_ortho_group.rvs(2, random_state=3)
# x = M s, (sample, state)
uniform_mixed: SampleState = uniform_sources @ thirty_degrees.T
# user
# the Amari index of P = W K M, 0 for a scaled permutation
def amari_index(product: StateMatrix) -> float:
"""How far ``product`` is from a scaled permutation matrix."""
# |P|, (state, state)
magnitudes: StateMatrix = np.abs(product)
# rᵢ = ∑ⱼ |Pᵢⱼ| / maxⱼ |Pᵢⱼ| − 1, (state,), (state)
rows: Float[ArrayLike, " state"] = (
magnitudes / magnitudes.max(axis=1, keepdims=True)
).sum(axis=1) - 1
# cⱼ = ∑ᵢ |Pᵢⱼ| / maxᵢ |Pᵢⱼ| − 1, (state,), (state)
columns: Float[ArrayLike, " state"] = (
magnitudes / magnitudes.max(axis=0, keepdims=True)
).sum(axis=0) - 1
# A = (∑ᵢ rᵢ + ∑ⱼ cⱼ) / (2 D_x (D_x − 1))
return (rows.sum() + columns.sum()) / (2 * len(product) * (len(product) - 1))We compare ICARotation, PicardRotation with its default and PicardRotation with extended=True.
for name, model in [
("ICARotation", rbig.ICARotation(orthogonal=False, random_state=0)),
("PicardRotation", rbig.PicardRotation(orthogonal=False, random_state=0)),
(
"PicardRotation, extended",
rbig.PicardRotation(orthogonal=False, extended=True, random_state=0),
),
]:
# today (rbig)
# fit Picard's K and W to the mixture
model.fit(uniform_mixed)
# user
# the Amari index of W K M
separation: float = amari_index(model.W_ @ model.K_ @ thirty_degrees)
print(f"{name:25s} Amari index {separation:.3f}")ICARotation Amari index 0.014
PicardRotation Amari index 0.977
PicardRotation, extended Amari index 0.014
With its default the Picard rotation does not separate the uniform sources at all, and with extended=True it matches ICARotation. A bimodal projection, which two moons have after a marginal step, is sub-Gaussian too. We rerun the loop on two moons with the Picard rotation, extended=True and the corrected frame, and compare it with ICA.
# Shapes: layer (K) = 15
# user
# KS_max of x_k with the extended Picard rotation, (layer,), (layer)
extended_trace: PerLayer = ks_trace(moons, "Picard, extended")
# KS_max of x_k with ICA, from section 4, (layer,), (layer)
ica_trace: PerLayer = results["two moons"][0]["ICA"]
print(
f"largest difference from the ICA trace {np.abs(extended_trace - ica_trace).max():.1e}"
)
print(f"KS_max after 15 layers {extended_trace[-1]:.3f}")largest difference from the ICA trace 0.0e+00
KS_max after 15 layers 0.019
The two loops agree layer for layer, so on two moons the default extended=False is the whole reason the Picard rotation stalled. That is a defect in rbig (rbig#163): picard turns extended on by default for orthogonal rotations, and rbig.PicardRotation overrides it. Until it is fixed, pass extended=True, or use ICARotation.
Recap¶
| Rotation | Finds | Correlated Gaussian | Rotated sources | Two moons |
|---|---|---|---|---|
| PCA | variance axes | 2 layers | 2 to 5 layers | stalls |
| random | nothing (Haar) | 13 layers | 2 to 7 layers | 11 layers, borderline |
rbig orthogonal ICA as it is | wrong frame (rbig#159) | 10 layers | 3 to 8 layers, or stalls | stalls |
| ICA, corrected frame | independent axes | 8 layers | 2 layers | 4 layers, clear by 11 |
rbig.PicardRotation, default | super-Gaussian axes only | stalls | stalls on five draws of six | stalls |
The layer counts are from one draw of the correlated Gaussian and of two moons, and six draws of the rotated sources, with a projection test at the 95% level. PCA is the right rotation when the dependence is Gaussian, ICA when it comes from non-Gaussian sources or curved structure, and a random rotation is the slow, fit-free choice that always gets there.
Next. Every loop here used rbig’s empirical marginal step. The next notebook looks at what happens at the edges of its support.
- 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.