Variational autoencoders: a code you can sample, and the ELBO
A VAE turns each row into a small Gaussian instead of a point, and trains on a bound on the log-likelihood. Read the two parts of that bound, the trick that makes it trainable, and what a fitted VAE reports.
What runs in CodeSplash
- DNN035Variational autoencoder (VAE) Runs in CodeSplash (Experimental)
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
You will be able to
- Write the ELBO as a rebuild term minus a KL term and say what each pulls toward
- Explain the reparameterization trick
- Read a VAE's rebuild error, KL, active dimensions and sample fit in CodeSplash
- Say why the ELBO is a lower bound and not the likelihood itself
From a point to a cloud
ReadA plain autoencoder maps each row to one point. Nothing says what lies between those points, so decoding a random spot can give nonsense.
A variational autoencoderVariational autoencoderAn autoencoder trained so its latent space is smooth and close to a normal distribution, which lets you sample from it. makes the code a probability model. The encoder gives each row a small Gaussian, , with a mean and a spread per coordinate. The decoder gives a distribution for the row given a code, . And every code is meant to come from one shared prior, usually a standard normal . Sample from the prior, decode, and you get a new row.
The bound it trains on
ReadThe VAE would like to maximize each row's log-likelihood , but that integral over all codes has no closed form. It maximizes a lower bound instead, the ELBOEvidence lower boundThe quantity a VAE maximizes; minus it is the loss — how badly rows are rebuilt plus how far their codes stray from the prior.:
The first term rewards rebuilding the row from codes drawn near its mean. The second, the KLKullback–Leibler divergenceHow many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match. term, pulls each row's cloud toward the prior. The gap between the bound and the true log-likelihood is the KL from to the true posterior, so a better encoder makes the bound tighter.
The reparameterization trick
ReadTraining needs gradients through a random draw. The reparameterization trickReparameterization trickWrites a random code as z = μ + σ·ε with ε drawn separately, so gradients flow through μ and σ during training. moves the randomness outside: draw from a standard normal, then set . Now is a smooth function of and , and backpropagation goes through.
With a diagonal Gaussian encoder the KL term has a closed form. In the reference's example a two-coordinate code draws = (0.612, −1.305) and has a KL of 0.129 nats.
import numpy as np
mu, logvar = np.array([.3, -.2]), np.array([-.5, .2])
eps = np.array([.4, -1.]) # drawn outside the network
z = mu + np.exp(.5 * logvar) * eps # reparameterized code
kl = .5 * np.sum(np.exp(logvar) + mu**2 - 1 - logvar)
print(z, kl)mu <- c(.3, -.2); logvar <- c(-.5, .2)
eps <- c(.4, -1) # drawn outside the network
z <- mu + exp(.5 * logvar) * eps # reparameterized code
kl <- .5 * sum(exp(logvar) + mu^2 - 1 - logvar)
print(c(z, kl))A VAE on iris
ExploreA variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.133 per standardized column and the mean KL is 1.11 nats; 8 rows with a loss of at least 3.53 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.160.
- Mean reconstruction error
- 0.1330
- Mean KL (nats per row)
- 1.110
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.9773
- Anomalies
- 8
Plots
View data
| species | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|
| setosa | 1.176 | 0.3987 |
| setosa | 1.151 | −0.3919 |
| setosa | 1.291 | −0.1713 |
| setosa | 1.287 | −0.3178 |
| setosa | 1.216 | 0.4858 |
| setosa | 0.9957 | 1.062 |
| setosa | 1.326 | 0.0476 |
| setosa | 1.196 | 0.2171 |
| setosa | 1.299 | −0.6013 |
| setosa | 1.195 | −0.2248 |
| setosa | 1.062 | 0.8139 |
| setosa | 1.261 | 0.1357 |
| setosa | 1.212 | −0.3913 |
| setosa | 1.401 | −0.4933 |
| setosa | 0.9543 | 1.329 |
| setosa | 0.8756 | 1.628 |
| setosa | 1.038 | 1.057 |
| setosa | 1.157 | 0.3926 |
| setosa | 0.9139 | 1.076 |
| setosa | 1.147 | 0.7914 |
| setosa | 1.012 | 0.3939 |
| setosa | 1.132 | 0.6660 |
| setosa | 1.376 | 0.2936 |
| setosa | 1.053 | 0.0777 |
| setosa | 1.232 | 0.1401 |
| setosa | 1.090 | −0.3562 |
| setosa | 1.145 | 0.2015 |
| setosa | 1.129 | 0.4465 |
| setosa | 1.126 | 0.2994 |
| setosa | 1.267 | −0.1591 |
| setosa | 1.205 | −0.2643 |
| setosa | 0.9870 | 0.3600 |
| setosa | 1.113 | 1.155 |
| setosa | 1.005 | 1.393 |
| setosa | 1.175 | −0.2433 |
| setosa | 1.187 | −0.0832 |
| setosa | 1.025 | 0.5760 |
| setosa | 1.268 | 0.4352 |
| setosa | 1.340 | −0.4887 |
| setosa | 1.157 | 0.2596 |
| setosa | 1.203 | 0.3455 |
| setosa | 0.9491 | −1.270 |
| setosa | 1.387 | −0.2521 |
| setosa | 1.109 | 0.3276 |
| setosa | 1.084 | 0.7959 |
| setosa | 1.170 | −0.4365 |
| setosa | 1.155 | 0.7866 |
| setosa | 1.318 | −0.1957 |
| setosa | 1.099 | 0.7653 |
| setosa | 1.191 | 0.0722 |
| versicolor | −0.7822 | 0.5444 |
| versicolor | −0.5493 | 0.3661 |
| versicolor | −0.8450 | 0.3862 |
| versicolor | −0.0362 | −1.121 |
| versicolor | −0.6487 | −0.1629 |
| versicolor | −0.1764 | −0.4722 |
| versicolor | −0.5748 | 0.4935 |
| versicolor | 0.4366 | −1.172 |
| versicolor | −0.5992 | 0.0041 |
| versicolor | 0.1325 | −0.8017 |
First 60 of 150 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 1.315 |
| false | 1.521 |
| false | 1.439 |
| false | 1.607 |
| false | 1.447 |
| false | 2.103 |
| false | 1.513 |
| false | 1.256 |
| false | 2.173 |
| false | 1.447 |
| false | 1.670 |
| false | 1.346 |
| false | 1.629 |
| false | 2.195 |
| false | 3.030 |
| true | 4.902 |
| false | 2.189 |
| false | 1.291 |
| false | 2.056 |
| false | 1.816 |
| false | 1.316 |
| false | 1.577 |
| false | 1.776 |
| false | 1.197 |
| false | 1.390 |
| false | 1.463 |
| false | 1.235 |
| false | 1.315 |
| false | 1.268 |
| false | 1.437 |
| false | 1.440 |
| false | 1.268 |
| false | 3.056 |
| true | 3.605 |
| false | 1.389 |
| false | 1.322 |
| false | 1.514 |
| false | 1.527 |
| false | 1.994 |
| false | 1.245 |
| false | 1.321 |
| true | 4.088 |
| false | 1.772 |
| false | 1.399 |
| false | 1.808 |
| false | 1.546 |
| false | 1.840 |
| false | 1.524 |
| false | 1.625 |
| false | 1.251 |
| false | 1.800 |
| false | 1.094 |
| false | 1.385 |
| false | 1.944 |
| false | 0.9980 |
| false | 0.8023 |
| false | 1.252 |
| false | 2.226 |
| false | 1.176 |
| false | 1.287 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.289 | 1 |
| total | 4.931 | 2 |
| total | 4.907 | 3 |
| total | 4.597 | 4 |
| total | 4.359 | 5 |
| total | 4.254 | 6 |
| total | 4.013 | 7 |
| total | 4.176 | 8 |
| total | 3.925 | 9 |
| total | 3.803 | 10 |
| total | 3.695 | 11 |
| total | 3.666 | 12 |
| total | 3.498 | 13 |
| total | 3.508 | 14 |
| total | 3.288 | 15 |
| total | 3.405 | 16 |
| total | 3.289 | 17 |
| total | 3.099 | 18 |
| total | 3.077 | 19 |
| total | 2.741 | 20 |
| total | 2.695 | 21 |
| total | 2.857 | 22 |
| total | 2.831 | 23 |
| total | 2.777 | 24 |
| total | 2.936 | 25 |
| total | 3.031 | 26 |
| total | 2.904 | 27 |
| total | 2.756 | 28 |
| total | 2.762 | 29 |
| total | 2.678 | 30 |
| total | 2.718 | 31 |
| total | 2.730 | 32 |
| total | 2.485 | 33 |
| total | 2.564 | 34 |
| total | 2.607 | 35 |
| total | 2.527 | 36 |
| total | 2.674 | 37 |
| total | 2.597 | 38 |
| total | 2.680 | 39 |
| total | 2.474 | 40 |
| total | 2.685 | 41 |
| total | 2.623 | 42 |
| total | 2.750 | 43 |
| total | 2.712 | 44 |
| total | 2.497 | 45 |
| total | 2.564 | 46 |
| total | 2.446 | 47 |
| total | 2.577 | 48 |
| total | 2.516 | 49 |
| total | 2.452 | 50 |
| total | 2.507 | 51 |
| total | 2.410 | 52 |
| total | 2.433 | 53 |
| total | 2.332 | 54 |
| total | 2.369 | 55 |
| total | 2.496 | 56 |
| total | 2.520 | 57 |
| total | 2.474 | 58 |
| total | 2.656 | 59 |
| total | 2.405 | 60 |
First 60 of 600 rows.
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2222 | real | 4.360 |
| 0.0556 | real | 4.480 |
| 0.2222 | real | 4.600 |
| 0.1111 | real | 4.720 |
| 0.2778 | real | 4.840 |
| 0.8889 | real | 4.960 |
| 0.5000 | real | 5.080 |
| 0.2222 | real | 5.200 |
| 0.0556 | real | 5.320 |
| 0.3333 | real | 5.440 |
| 0.7222 | real | 5.560 |
| 0.4444 | real | 5.680 |
| 0.3889 | real | 5.800 |
| 0.1667 | real | 5.920 |
| 0.6667 | real | 6.040 |
| 0.2222 | real | 6.160 |
| 0.5000 | real | 6.280 |
| 0.3889 | real | 6.400 |
| 0.2778 | real | 6.520 |
| 0.1111 | real | 6.640 |
| 0.6111 | real | 6.760 |
| 0.2222 | real | 6.880 |
| 0.0556 | real | 7 |
| 0.0556 | real | 7.120 |
| 0.2222 | real | 7.240 |
| 0.0556 | real | 7.360 |
| 0 | real | 7.480 |
| 0.0556 | real | 7.600 |
| 0.2222 | real | 7.720 |
| 0.0556 | real | 7.840 |
| 0 | synthetic | 4.360 |
| 0.0556 | synthetic | 4.480 |
| 0.1111 | synthetic | 4.600 |
| 0.2778 | synthetic | 4.720 |
| 0.4444 | synthetic | 4.840 |
| 0.3333 | synthetic | 4.960 |
| 0.3889 | synthetic | 5.080 |
| 0.3333 | synthetic | 5.200 |
| 0.6111 | synthetic | 5.320 |
| 0.2778 | synthetic | 5.440 |
| 0.5000 | synthetic | 5.560 |
| 0.5000 | synthetic | 5.680 |
| 0.6111 | synthetic | 5.800 |
| 0.3889 | synthetic | 5.920 |
| 0.3333 | synthetic | 6.040 |
| 0.4444 | synthetic | 6.160 |
| 0.6111 | synthetic | 6.280 |
| 0.5000 | synthetic | 6.400 |
| 0.4444 | synthetic | 6.520 |
| 0.4444 | synthetic | 6.640 |
| 0.4444 | synthetic | 6.760 |
| 0.1667 | synthetic | 6.880 |
| 0.1111 | synthetic | 7 |
| 0 | synthetic | 7.120 |
| 0 | synthetic | 7.240 |
| 0 | synthetic | 7.360 |
| 0 | synthetic | 7.480 |
| 0 | synthetic | 7.600 |
| 0 | synthetic | 7.720 |
| 0 | synthetic | 7.840 |
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec dddd5c04a52df612
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_deep_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width"))), c("sepal_length", "sepal_width", "petal_length", "petal_width"))
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.vae/iris_map/out-r")
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = LABEL))[[LABEL]]
# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(8)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(150)
PRIOR <- "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(0)
if (PRIOR == "mixture" && length(rows) <= 3) {
cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
cs_deep_fit_vade(
X, HIDDEN, LATENT, as.integer(3),
activation = "tanh",
beta = BETA,
epochs = as.integer(200),
lr = 0.01,
batch_size = NULL,
weight_decay = 0,
n_samples = N_SAMPLES,
pretrain_epochs = as.integer(100),
seed = 42
)
} else {
cs_deep_fit_vae(
X, HIDDEN, LATENT,
activation = "tanh",
beta = BETA,
epochs = as.integer(200),
lr = 0.01,
batch_size = NULL,
weight_decay = 0,
n_samples = N_SAMPLES,
seed = 42
)
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding # posterior means mu (n x LATENT)
scores <- fit$score # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error # mean squared reconstruction error per standardized column
# %% Anomalies by the per-row loss
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # largest loss first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN # undefined with fewer than 3 rows
# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
clusters <- cs_ml_canonical(fit$cluster)
comp_of <- integer(0)
for (j in seq_along(fit$pi)) {
members <- which(fit$cluster == j - 1L)
if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
}
}
# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) else NULL
# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/iris_map/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
loss = vapply(fit$history, function(h) h$loss, numeric(1)),
reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(
list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
if (N_SAMPLES > 0L) {
nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
title = "Rows generated from the prior")
}
# %% Result
active <- as.integer(fit$active)
values <- list(
n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
values$components <- length(fit$pi)
values$n_clusters <- length(comp_of)
for (j in names(comp_of)) {
values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
}
}
if (!is.null(bound)) {
values$iwae_samples <- IWAE
values$iwae_bound <- mean(bound$iwae)
values$elbo_estimate <- mean(bound$elbo)
values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- df[[LABEL]][rows[pick] + 1L]
ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L && !is.null(clusters)) {
cent_ <- as.integer(names(comp_of))[order(comp_of)]
charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
levels = as.character(sort(as.integer(comp_of)))),
centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
group = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", list(
score = cs_col("Per-row loss", scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
f0 <- NUMERIC[1]
d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
if (!is.null(d)) {
charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
}
}
assumptions <- list(list(
key = "active_units", label = "Latent dimensions in use",
status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
ordj <- as.integer(names(comp_of))[order(comp_of)]
extra_tables[[1]] <- list(
key = "components", title = "Mixture prior components",
columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
list(key = "weight", label = "Prior weight", type = "number")),
lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
rows = lapply(ordj, function(j) {
cc <- comp_of[[as.character(j)]]
r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
r
})
)
}
cs_publish(list(
title = "Variational autoencoder (latent map, anomalies and generated rows)",
engine = cs_engine_info("torch", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = c(list(
list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
), extra_stats),
tables = c(list(
list(
key = "top", title = "Rows the model finds least typical",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = "Per-row loss", type = "number")),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
),
list(
key = "latent", title = "Latent dimensions",
columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
rows = dim_rows
)
), extra_tables),
charts = charts,
assumptions = assumptions,
values = values,
warnings = warnings,
artifacts = artifacts
))
A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.133 per standardized column and the mean KL is 1.11 nats; 8 rows with a loss of at least 3.53 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.160.
- Mean reconstruction error
- 0.1330
- Mean KL (nats per row)
- 1.110
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.9773
- Anomalies
- 8
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec dddd5c04a52df612
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"])
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/discover.vae/iris_map/out-python",
)
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=[LABEL])[LABEL]
# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [8]]
LATENT = 2
BETA = 1
N_SAMPLES = 150
PRIOR = "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 0
if PRIOR == "mixture" and len(rows) <= 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
fit = du.fit_vade(
X, HIDDEN, LATENT, 3,
activation="tanh",
beta=BETA,
epochs=200,
lr=0.01,
batch_size=None,
weight_decay=0,
n_samples=N_SAMPLES,
pretrain_epochs=100,
seed=42,
)
else:
fit = gen.fit_vae(
X, HIDDEN, LATENT,
activation="tanh",
beta=BETA,
epochs=200,
lr=0.01,
batch_size=None,
weight_decay=0,
n_samples=N_SAMPLES,
seed=42,
)
if not np.all(np.isfinite(fit["score"])):
cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"] # posterior means μ (n × LATENT)
scores = fit["score"] # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"] # mean squared reconstruction error per standardized column
# %% Anomalies by the per-row loss
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores)) # largest loss first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval) if k_eval >= 1 else float("nan") # undefined with fewer than 3 rows
# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
from codesplash.ml import cluster as csc
clusters = csc.canonical(fit["cluster"])
comp_of = {}
for j in range(len(fit["pi"])):
members = np.flatnonzero(fit["cluster"] == j)
if len(members):
comp_of[j] = int(clusters[members[0]])
# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "tanh", IWAE, 42) if IWAE > 0 else None
# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
sample_ks[f] = gen.ks_distance(real, gen_cols[f])
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/iris_map/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
"epoch": [h["epoch"] for h in fit["history"]],
"loss": [h["loss"] for h in fit["history"]],
"reconstruction": [h["recon"] for h in fit["history"]],
"kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
]
if N_SAMPLES > 0:
pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})
# %% Result
active = int(fit["active"])
values = {
"n": len(rows),
"n_features": int(X.shape[1]),
"latent_dim": LATENT,
"recon_mse": float(np.mean(errors)),
"kl": float(np.mean(fit["kl_row"])),
"elbo_loss": float(np.mean(scores)),
"active_dims": active,
"error_check": csembed.checksum(scores, rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"final_loss": float(fit["history"][-1]["loss"]),
"epochs_run": int(fit["epochs_run"]),
"trustworthiness": trust,
"n_samples": N_SAMPLES,
"sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
values[f"sample_ks[{f}]"] = v
if clusters is not None:
values["components"] = int(len(fit["pi"]))
values["n_clusters"] = len(comp_of)
for j, c in comp_of.items():
values[f"pi[{c}]"] = float(fit["pi"][j])
values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
values["iwae_samples"] = IWAE
values["iwae_bound"] = float(np.mean(bound["iwae"]))
values["elbo_estimate"] = float(np.mean(bound["elbo"]))
values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
for f in FEATURES:
v = df[f].iloc[rows[i]]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2 and clusters is not None:
_cent = sorted(comp_of, key=lambda j: comp_of[j])
charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
"x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
"y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
"cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
levels=[str(c) for c in sorted(comp_of.values())]),
"centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
"x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
"y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
"group": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", {
"score": cs.col("Per-row loss", scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
"x": cs.col("Epoch", ep * 3, "numeric"),
"value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
"component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
f0 = NUMERIC[0]
xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
if xs:
charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
"x": cs.col(f0, xs, "numeric"),
"density": cs.col("Density", dens, "numeric"),
"source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
}))
assumptions = [{
"key": "active_units",
"label": "Latent dimensions in use",
"status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
"detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
+ ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
extra_tables.append({
"key": "components",
"title": "Mixture prior components",
"columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
{"key": "weight", "label": "Prior weight", "type": "number"}]
+ [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
"rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
**{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
})
cs.publish({
"title": "Variational autoencoder (latent map, anomalies and generated rows)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
{"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
{"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
{"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
] + extra_stats,
"tables": [
{
"key": "top",
"title": "Rows the model finds least typical",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
},
{
"key": "latent",
"title": "Latent dimensions",
"columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
{"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
"rows": dim_rows,
},
] + extra_tables,
"charts": charts,
"assumptions": assumptions,
"values": values,
"warnings": warnings,
"artifacts": artifacts,
})
The loss per row ends near 1.64 nats, the negative ELBO. Of that, the KL part is 1.11. The rebuild error of the posterior means is 0.133, higher than the plain autoencoder's, because the KL term keeps the codes from spreading out to fit every row.
2 of 2 latent dimensions are in use. The method also decoded 150 prior draws; their columns differ from the real ones by a mean Kolmogorov–Smirnov distance of 0.16.
Between the training points
ExploreThe KL term is what makes the space between codes usable. Drag the point below around a toy latent space and watch what the decoder makes there.
DExplorable · A toy latent space
If every point in a latent space decodes to something, does every point decode to something real?
- Decoded from your point
- Nearest training curve
- Distance to nearest
- 0.093
- Peaks
- 1
- Variance captured
- 0.81
- Puzzle: Find a point inside the plotted range that decodes to something unlike the training data.
The training data are 150 bump curves of different centers and widths. Two coordinates capture 81% of their variance, and this point decodes to a curve with 1 peak, 0.093 from the nearest training curve. It looks like the data.
This toy decoder is linear, so it decodes every point, including points far from any training curve. A VAE's prior tells you where to sample; the KL term is what encourages the codes to fill that region. Neither guarantees that every sampled row looks real, which is why you compare samples with real rows.
Watch the reconstruction term and the KL trade off as β and the decoder noise change.
DExplorable · The ELBO: reconstruction against KL
What does a VAE trade off, and when does it stop using its latent code?
The data vary strongly in one direction and weakly in another. How many latent dimensions will the VAE use?
1 is the ELBO; above 1 is a β-VAE.
How noisy the decoder says the data are.
Commit your prediction above to see the result
Make your prediction to see the result.
What the bound is not
Read- The ELBO is a lower bound. A higher ELBO can come from a better model or a tighter encoder, and two models' bounds can differ in tightness.
- Latent dimensions are a setting, not a discovered number of real factors.
- Low rebuild error and good samples are different goals. Check both.
Check: VAEs and the ELBO
CheckpointCheck yourself
Which pair of terms makes up the ELBO?
Show the answer
Answer: a
The ELBO trades rebuilding each row against keeping each row's code distribution close to the shared prior.
Check yourself
Why write the code as with drawn separately?
Show the answer
Answer: b
The randomness sits in , outside the network, so is a differentiable function of the encoder's outputs.
Check yourself
Two VAEs on the same rows report ELBOs of −5.1 and −4.8 nats per row. What can you say for sure?
Show the answer
Answer: b
Each ELBO sits below its own model's log-likelihood by an unknown gap. A tighter bound on a worse model can beat a looser bound on a better one. The importance-weighted bound in the next lesson narrows that gap.
Check yourself
On the same rows and code size, a VAE rebuilds rows less precisely than a plain autoencoder. Why?
Show the answer
Answer: a
The KL term is a price for spreading codes out. The VAE pays some rebuild accuracy for a code space you can sample from.
Recap
Recap- A VAE gives each row a Gaussian code and decodes codes into rows; a shared prior makes sampling possible.
- It trains on the ELBO: rebuild term minus KL to the prior, a lower bound on the log-likelihood.
- The reparameterization trick moves the randomness outside the network so gradients flow.
- Read rebuild error, KL, active dimensions and sample fit together.
Concepts in this lesson