Skip to content
svglatent-prior

Latent means against the prior

Does a variational autoencoder's latent space fill its N(0, I) prior, or leave holes and collapse?

Demo data · seed 20261101 · 150 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each point as one row's position in the latent space (its posterior mean μ).
  2. The dashed rings are the prior's 1σ and 2σ circles; rows should spread across them without big empty regions.
  3. Clusters of colour show what the model separates; points far outside 2σ decode from places the prior rarely samples.
  1. Callout 1: The prior's centre.
  2. Callout 2: The 2σ ring.
  3. Callout 3: A group the model keeps together.

Watch out

  • Everything piled near the centre on one axis suggests that dimension collapsed onto the prior.
  • Holes inside the rings are regions that decode to rows unlike any in the data; generated rows can land there.

Defaults

No settings: the chart draws one way.

Pinned in the code

  • Draws the engine's numbers as given (codesplash ↔ codesplashr torch twins); the chart computes nothing statistical.
  • Both axes span the same symmetric range around 0; the prior's rings are circles in latent units (they look oval when the plot isn't square).
  • Labels give the share of posterior means inside each ring next to the prior's mass (39.3% inside 1σ, 86.5% inside 2σ in two dimensions); means sit closer to 0 than draws because each row's own spread is left out.
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

try:
    import codesplash as cs  # optional: the app's chart theme
except ImportError:
    cs = None
if cs:
    cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]

df = pd.read_csv("latent-prior-demo.csv", keep_default_na=False, na_values=[""])  # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["species"] = pd.Categorical(df["species"].astype("string"), categories=["setosa", "versicolor", "virginica"])

def levels_of(s):
    """Declared level order (categoricals), else order of first appearance."""
    if isinstance(s.dtype, pd.CategoricalDtype):
        return [v for v in s.cat.categories if (s == v).any()]
    return list(dict.fromkeys(s.dropna().astype(str)))
X = "latent 1 (μ)"
Y = "latent 2 (μ)"
G = "species"
d = df.dropna(subset=[X, Y])
fig, ax = plt.subplots(figsize=(6, 6))
for i, name in enumerate(levels_of(d[G]) if G else [None]):
    s = d if name is None else d[d[G].astype(str) == name]
    ax.scatter(s[X], s[Y], s=10, alpha=0.75, label=name, linewidths=0, marker=SERIES_MARKERS[i % 8])  # marker shape per group, as in the app
theta = np.linspace(0, 2 * np.pi, 200)
r2 = d[X] ** 2 + d[Y] ** 2
for r in (1, 2):  # the N(0, I) prior's 1σ and 2σ rings; 39.3% and 86.5% of its mass lie inside
    ax.plot(r * np.cos(theta), r * np.sin(theta), color="grey", linestyle="--", linewidth=1)
    ax.annotate(f"{r}σ: {(r2 <= r * r).mean():.0%} inside (prior {1 - np.exp(-r * r / 2):.0%})", (r * 0.707, r * 0.707), fontsize=8, color="grey")
m = max(2.2, 1.05 * float(np.abs(d[[X, Y]].to_numpy()).max()))
ax.set_xlim(-m, m)
ax.set_ylim(-m, m)
ax.set_aspect("equal")
ax.set_xlabel(X)
ax.set_ylabel(Y)
if G:
    ax.legend(frameon=False)
plt.show()

Needs pandas, numpy, matplotlib · reads latent-prior-demo.csv · app theme from the optional codesplash helper