β-VAE and the importance-weighted bound: tilting and tightening the ELBO
Weighting the KL term changes what a VAE learns, and can switch latent dimensions off. Averaging several draws gives a tighter bound on the log-likelihood. Run both in CodeSplash and read what changes.
What runs in CodeSplash
- DNN036Beta-VAE Runs in CodeSplash (Experimental)
- DNN038Importance-weighted autoencoder (IWAE) Partly runs in CodeSplash (Experimental)
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
You will be able to
- Explain what raising or lowering β does to the code and the rebuilds
- Spot posterior collapse from the active-dimension count and the KL
- Compute an importance-weighted bound and say why it is tighter than the ELBO
- Tell IWAE training apart from using the bound only to evaluate
One weight on the KL term
ReadA β-VAEβ-VAEA VAE whose KL term is multiplied by β; above 1 trades sharper reconstructions for a smoother, more organized latent space. multiplies the KL term by a weight :
With it is the ordinary ELBO. Above 1, codes are pulled harder toward the prior: smoother, more independent coordinates, blurrier rebuilds. Below 1, rebuilds sharpen and the code space gets lumpier. Any is a different, regularized objective, not a bound on the likelihood.
The same row at four weights
ReadThe reference fixes one row's rebuild cost and KL, then prices them at four weights. At = 0.5 the objective is 2.164; at 4 it is 2.616. The KL part scales with β while the rebuild part stays put, so a training run under a big β will give up rebuild accuracy to buy a smaller KL.
Turning dimensions off
ExploreA variational autoencoder mapped 532 rows into 2 latent coordinates (1 in use); the mean squared reconstruction error is 0.918 per standardized column and the mean KL is 0.0643 nats; 54 rows with a loss of at least 12.7 are flagged as anomalies.
- Mean reconstruction error
- 0.9184
- Mean KL (nats per row)
- 0.0643
- Active latent dimensions
- 1
- Trustworthiness (k = 10)
- 0.7543
- Anomalies
- 54
Assumptions
- Latent dimensions in use — 1 of 2 latent dimensions vary across rows (variance of μ > 0.01); the rest collapsed onto the prior and carry no information about the rows.
Rows the model finds least typical
| Rank | Row | Per-row loss | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 58.348 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 157 | 55.282 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 11 | 37.306 | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 279 | 37.119 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 5 | 296 | 34.157 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 6 | 362 | 28.944 | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 7 | 257 | 25.395 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 8 | 403 | 24.704 | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 9 | 222 | 23.675 | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 10 | 272 | 22.177 | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 11 | 221 | 21.625 | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 12 | 358 | 19.680 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 13 | 492 | 19.319 | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 14 | 36 | 18.957 | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 15 | 462 | 18.102 | 1 | 89 | 24 | 19 | 27.800 | 0.5590 | 21 |
| 16 | 432 | 18.073 | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 17 | 255 | 18.030 | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 18 | 50 | 17.533 | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 19 | 80 | 17.504 | 12 | 121 | 78 | 17 | 26.500 | 0.2590 | 62 |
| 20 | 460 | 17.493 | 2 | 82 | 52 | 22 | 28.500 | 1.699 | 25 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.0008 | 0.0015 | no |
| 2 | 0.0635 | 0.1202 | yes |
- Posterior collapse: 1 latent dimension carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.
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 9953b0a1f343b577
# Dataset: ml_pima (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_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
# 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/pima_beta4_no_samples/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "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 <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.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(12)))
LATENT <- as.integer(2)
BETA <- 4
N_SAMPLES <- as.integer(0)
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(100),
lr = 0.005,
batch_size = 128,
weight_decay = 0.0001,
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(100),
lr = 0.005,
batch_size = 128,
weight_decay = 0.0001,
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.1, 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/pima_beta4_no_samples/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 532 rows into 2 latent coordinates (1 in use); the mean squared reconstruction error is 0.918 per standardized column and the mean KL is 0.0643 nats; 54 rows with a loss of at least 12.7 are flagged as anomalies.
- Mean reconstruction error
- 0.9184
- Mean KL (nats per row)
- 0.0643
- Active latent dimensions
- 1
- Trustworthiness (k = 10)
- 0.7543
- Anomalies
- 54
Assumptions
- Latent dimensions in use — 1 of 2 latent dimensions vary across rows (variance of μ > 0.01); the rest collapsed onto the prior and carry no information about the rows.
Rows the model finds least typical
| Rank | Row | Per-row loss | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 58.348 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 157 | 55.282 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 11 | 37.306 | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 279 | 37.119 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 5 | 296 | 34.157 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 6 | 362 | 28.944 | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 7 | 257 | 25.395 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 8 | 403 | 24.704 | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 9 | 222 | 23.675 | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 10 | 272 | 22.177 | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 11 | 221 | 21.625 | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 12 | 358 | 19.680 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 13 | 492 | 19.319 | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 14 | 36 | 18.957 | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 15 | 462 | 18.102 | 1 | 89 | 24 | 19 | 27.800 | 0.5590 | 21 |
| 16 | 432 | 18.073 | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 17 | 255 | 18.030 | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 18 | 50 | 17.533 | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 19 | 80 | 17.504 | 12 | 121 | 78 | 17 | 26.500 | 0.2590 | 62 |
| 20 | 460 | 17.493 | 2 | 82 | 52 | 22 | 28.500 | 1.699 | 25 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.0008 | 0.0015 | no |
| 2 | 0.0635 | 0.1202 | yes |
- Posterior collapse: 1 latent dimension carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.
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 9953b0a1f343b577
# Dataset: ml_pima (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_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
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/pima_beta4_no_samples/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "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 = None
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]
# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [12]]
LATENT = 2
BETA = 4
N_SAMPLES = 0
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=100,
lr=0.005,
batch_size=128,
weight_decay=0.0001,
n_samples=N_SAMPLES,
pretrain_epochs=100,
seed=42,
)
else:
fit = gen.fit_vae(
X, HIDDEN, LATENT,
activation="tanh",
beta=BETA,
epochs=100,
lr=0.005,
batch_size=128,
weight_decay=0.0001,
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.1, 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/pima_beta4_no_samples/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,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Here the KL weight is 4 on the Pima columns. Only 1 of 2 dimensions are in use, and the KL per row is down to 0.064. That is posterior collapsePosterior collapseLatent dimensions that a VAE stops using; their codes equal the prior for every row, so they carry no information.: for the unused dimension, every row's code equals the prior, so it carries no information. The rebuild error, 0.92, shows the price.
Collapse isn't always a failure. If one coordinate is enough, the model is telling you so. It is a failure when you needed the dimension.
Raise β and watch the weak direction switch off first.
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.
A tighter bound from several draws
ReadThe ELBO uses one code draw per row. The importance-weighted boundImportance-weighted boundA tighter lower bound on a row's log-likelihood than the ELBO, from averaging importance weights over several latent draws. draws codes and averages their importance weights inside the log:
With it is the ELBO. As grows, the expected bound rises toward . Compute it in log space: subtract the largest log weight first.
One row, four draws
ReadIn the reference's example four draws have log weights near −1000. A naive mean of exponentials underflows to zero; the log-sum-exp form gives −1000.95. The weights' effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count. is 2.09 of 4: a couple of draws carry most of the weight, which is common when the encoder's Gaussian is narrower than the true posterior.
import numpy as np
logw = np.array([-1002., -1000., -1001., -1003.])
m = logw.max()
bound = m + np.log(np.exp(logw - m).mean()) # stable log-mean-exp
w = np.exp(logw - m); w /= w.sum()
print(bound, 1 / np.sum(w**2)) # bound, effective sample sizelogw <- c(-1002, -1000, -1001, -1003)
m <- max(logw)
bound <- m + log(mean(exp(logw - m))) # stable log-mean-exp
w <- exp(logw - m); w <- w / sum(w)
print(c(bound, 1 / sum(w^2))) # bound, effective sample sizeThe bound in CodeSplash
ExploreA variational autoencoder mapped 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).
- Mean reconstruction error
- 0.4918
- Mean KL (nats per row)
- 1.262
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.8356
- Anomalies
- 27
- Log-likelihood bound (IWAE, 50 draws)
- −9.442
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 | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 41.500 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 36.173 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 11 | 33.548 | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 296 | 29.898 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 5 | 362 | 22.164 | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 6 | 279 | 20.479 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 7 | 257 | 19.638 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 8 | 222 | 18.122 | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 9 | 460 | 15.515 | 2 | 82 | 52 | 22 | 28.500 | 1.699 | 25 |
| 10 | 48 | 15.056 | 2 | 92 | 76 | 20 | 24.200 | 1.698 | 28 |
| 11 | 208 | 14.222 | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 12 | 403 | 12.866 | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 13 | 13 | 12.572 | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 14 | 417 | 12.519 | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 15 | 375 | 12.302 | 2 | 127 | 58 | 24 | 27.700 | 1.600 | 25 |
| 16 | 491 | 12.301 | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 17 | 272 | 12.252 | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 18 | 111 | 12.112 | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 19 | 358 | 12.049 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 20 | 396 | 12.046 | 0 | 189 | 104 | 25 | 34.300 | 0.4350 | 41 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.5317 | 0.6583 | yes |
| 2 | 0.7299 | 0.8052 | 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 4fb7211679042758
# Dataset: ml_pima (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_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
# 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/pima_iwae_normal/out-r")
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "numeric",
age = "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 <- NULL
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.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(12)))
LATENT <- as.integer(2)
BETA <- 1
N_SAMPLES <- as.integer(0)
PRIOR <- "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(50)
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(100),
lr = 0.005,
batch_size = 128,
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(100),
lr = 0.005,
batch_size = 128,
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/pima_iwae_normal/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 532 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.492 per standardized column and the mean KL is 1.26 nats; 27 rows with a loss of at least 11 are flagged as anomalies. The importance-weighted bound with 50 draws is -9.442 nats per row (0.0661 above the ELBO estimate).
- Mean reconstruction error
- 0.4918
- Mean KL (nats per row)
- 1.262
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.8356
- Anomalies
- 27
- Log-likelihood bound (IWAE, 50 draws)
- −9.442
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 | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 41.500 | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 36.173 | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 11 | 33.548 | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 296 | 29.898 | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 5 | 362 | 22.164 | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 6 | 279 | 20.479 | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 7 | 257 | 19.638 | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 8 | 222 | 18.122 | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 9 | 460 | 15.515 | 2 | 82 | 52 | 22 | 28.500 | 1.699 | 25 |
| 10 | 48 | 15.056 | 2 | 92 | 76 | 20 | 24.200 | 1.698 | 28 |
| 11 | 208 | 14.222 | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 12 | 403 | 12.866 | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 13 | 13 | 12.572 | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 14 | 417 | 12.519 | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 15 | 375 | 12.302 | 2 | 127 | 58 | 24 | 27.700 | 1.600 | 25 |
| 16 | 491 | 12.301 | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 17 | 272 | 12.252 | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 18 | 111 | 12.112 | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 19 | 358 | 12.049 | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 20 | 396 | 12.046 | 0 | 189 | 104 | 25 | 34.300 | 0.4350 | 41 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.5317 | 0.6583 | yes |
| 2 | 0.7299 | 0.8052 | 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 4fb7211679042758
# Dataset: ml_pima (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_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
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/pima_iwae_normal/out-python",
)
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "numeric",
"age": "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 = None
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=[LABEL])[LABEL]
# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [12]]
LATENT = 2
BETA = 1
N_SAMPLES = 0
PRIOR = "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 50
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=100,
lr=0.005,
batch_size=128,
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=100,
lr=0.005,
batch_size=128,
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/pima_iwae_normal/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,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Importance-weighted bound draws set to 50 reports both numbers per row. The ELBO estimate is −9.508 nats and the importance-weighted bound −9.442, a gap of 0.066. On penguins with a mixture prior and 20 draws the gap is 0.076.
A small gap says the one-draw ELBO was already close for this encoder. It says nothing about whether the decoder's likelihood is right for the data.
Training with it, or only scoring
ReadTraining on changes the encoder too: with large its gradient signal can weaken. Report which you did. A finite gives a random estimate, so it can land above the true value on a given row; the bound holds in expectation.
Check: β and K
CheckpointCheck yourself
You raise β from 1 to 4. What do you expect?
Show the answer
Answer: a
β prices the KL term. Making it dearer pushes codes toward the prior, at the cost of rebuild accuracy, and can switch unneeded dimensions off.
Check yourself
A VAE with 4 latent dimensions reports 1 active dimension and a KL near zero. What happened?
Show the answer
Answer: b
That is posterior collapse. It may be fine if one coordinate is enough; if you needed the others, lower β or change the model.
Check yourself
Is a β-VAE's objective with β = 4 a lower bound on the log-likelihood?
Show the answer
Answer: c
Only β = 1 gives the ELBO. Other weights tilt the trade-off and shouldn't be reported as likelihood bounds.
Check yourself
What is the importance-weighted bound with K = 1?
Show the answer
Answer: a
With one draw, the average inside the log has one term, and its expectation is the ELBO. More draws tighten it.
Check yourself
CodeSplash's VAE reports an importance-weighted bound with 50 draws. Which description is accurate?
Show the answer
Answer: b
The option evaluates a trained VAE. IWAE training would optimize the K-draw bound itself, which also changes the encoder.
Check yourself
Log weights near −1000 make mean(exp(logw)) return 0. What's the fix?
Show the answer
Answer: c
That is the log-sum-exp trick. The shifted weights are at most 1, so nothing underflows to an all-zero sum.
Recap
Recap- β weights the KL term: above 1 gives smoother codes and blurrier rebuilds, and can collapse dimensions.
- Only β = 1 is the ELBO; other weights give a regularized objective.
- The K-draw importance-weighted bound is tighter than the ELBO in expectation; compute it with log-sum-exp.
- CodeSplash runs β and scores VAEs with the K-draw bound; IWAE training is explained here.
Concepts in this lesson