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?
How to read it
- Read each point as one row's position in the latent space (its posterior mean μ).
- The dashed rings are the prior's 1σ and 2σ circles; rows should spread across them without big empty regions.
- Clusters of colour show what the model separates; points far outside 2σ decode from places the prior rarely samples.
- Callout 1: The prior's centre.
- Callout 2: The 2σ ring.
- 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
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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 px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
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 = go.Figure()
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]
fig.add_trace(go.Scatter(x=s[X], y=s[Y], mode="markers", marker=dict(size=5, opacity=0.75, symbol=SERIES_MARKERS[i % 8]), name=name or "rows")) # marker shape per group
for r in (1, 2): # the N(0, I) prior's 1σ and 2σ rings
fig.add_shape(type="circle", x0=-r, y0=-r, x1=r, y1=r, line=dict(color="grey", dash="dash", width=1))
m = max(2.2, 1.05 * float(np.abs(d[[X, Y]].to_numpy()).max()))
fig.update_xaxes(range=[-m, m], title=X)
fig.update_yaxes(range=[-m, m], title=Y, scaleanchor="x", scaleratio=1)
fig.update_layout(template="plotly_white")
fig.show()Needs pandas, numpy, plotly · reads latent-prior-demo.csv · app theme from the optional codesplash helper
# Latent means against the prior — Codesplash Chart Lab (recipe "latent-prior")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("latent-prior-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["species"]] <- factor(df[["species"]], levels = c("setosa", "versicolor", "virginica"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "latent 1 (μ)"
Y <- "latent 2 (μ)"
G <- "species"
d <- df[!is.na(df[[X]]) & !is.na(df[[Y]]), ]
d$grp <- if (is.null(G)) "rows" else factor(as.character(d[[G]]), levels = levels_of(d[[G]]))
theta <- seq(0, 2 * pi, length.out = 200)
rings <- do.call(rbind, lapply(1:2, function(r) data.frame(r = r, x = r * cos(theta), y = r * sin(theta))))
r2 <- d[[X]]^2 + d[[Y]]^2
labs_df <- data.frame(x = c(1, 2) * 0.707, y = c(1, 2) * 0.707,
label = sprintf("%dσ: %.0f%% inside (prior %.0f%%)", 1:2, 100 * sapply(1:2, function(r) mean(r2 <= r^2)), 100 * (1 - exp(-(1:2)^2 / 2))))
m <- max(2.2, 1.05 * max(abs(c(d[[X]], d[[Y]]))))
p <- ggplot(d, aes(x = .data[[X]], y = .data[[Y]])) +
geom_path(data = rings, aes(x = x, y = y, group = r), linetype = "dashed", colour = "grey50", inherit.aes = FALSE) +
geom_point(aes(colour = grp, shape = grp), size = 1.2, alpha = 0.75) + scale_shape_manual(values = cs_shapes) + # marker shape per group, as in the app
geom_text(data = labs_df, aes(x = x, y = y, label = label), size = 2.8, colour = "grey40", hjust = 0, inherit.aes = FALSE) +
coord_equal(xlim = c(-m, m), ylim = c(-m, m)) + labs(x = X, y = Y, colour = NULL, shape = NULL) + theme_minimal()
print(p)Needs ggplot2 · reads latent-prior-demo.csv · app theme from the optional codesplashr helper