A VAE workflow: fit, select, and check samples as well as rebuilds
Fit a VAE the way the reference's full workflow does. Split first, pick a checkpoint on validation rows, report each part of the loss on its own, and compare prior samples with real rows, where a well-rebuilding VAE can still fail.
What runs in CodeSplash
- DNN035Variational autoencoder (VAE) Runs in CodeSplash (Experimental)
- DNN036Beta-VAE Runs in CodeSplash (Experimental)
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
- Synthetic data — tabular VAE (TVAE) Experimental
You will be able to
- Plan the splits and fixed draws for fitting and selecting a VAE
- Report the negative ELBO, its KL and rebuild parts, and posterior-mean error as separate numbers
- Check prior samples against held-out rows and recognize the failure when they disagree
- Try a richer prior and compare it under the same evaluation
The plan before the fit
ReadThe reference's VAE workflow fixes its decisions before training:
- Split into training, validation and a locked test setLocked test setRows held back from fitting and choosing, for one final score on the model you picked.. Fit scaling on training rows only.
- Fix the settings: latent size, widths, observation variance, KL weight, epochs. Each changes the model, so write them down.
- Select a checkpoint on validation rows, with the same bank of code draws every epoch so two epochs differ by the model, not by luck.
- Score once on the test rows, with fresh, larger draw banks.
Selecting many times against one validation bank can fit its noise. That's why the final number uses new draws.
Several numbers, not one
ReadA VAE has at least four numbers worth reporting, and they answer different questions:
- the negative ELBO per row, the training objective;
- its two parts, the KL and the expected rebuild cost;
- the posterior-mean rebuild error, which decodes each row's mean code with no noise, a different number from the ELBO's rebuild term;
- an importance-weighted estimate of the log-likelihood.
None of them looks at new samples. That needs its own check.
Rebuilds versus samples
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,
})
On iris, the posterior-mean rebuild error is 0.133 and the trustworthiness of the map 0.977. Both look fine.
The 150 rows decoded from the prior tell a separate story: their columns differ from the real ones by a mean Kolmogorov–Smirnov distance of 0.160. Open the latent map with the prior overlaid. Real codes form clumps; a standard normal prior also puts mass in the gaps between them, and those draws decode to rows between the species.
The failure the reference kept
ReadThe reference's own run shows this on purpose. Held-out rows sit in tight clusters and their posterior means separate well, yet most prior samples land between clusters. Its rebuild error was low the whole time.
A report with rebuild error alone would have missed the main problem. The fix is not to rerun until the pictures improve, which would hide the evidence. It is to change something specific and score it the same way.
Push β and the decoder noise up until no latent dimension carries information.
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.
Change one thing: the prior
ExploreA variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.154 per standardized column and the mean KL is 1.06 nats; 8 rows with a loss of at least 3.24 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.125. The mixture prior's 3 components hold 2 clusters of rows.
- Mean reconstruction error
- 0.1545
- Mean KL (nats per row)
- 1.060
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.9758
- Anomalies
- 8
Plots
View data
| Component mean | Component | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|---|
| false | 2 | 1.209 | 1.167 |
| false | 2 | 1.255 | 0.8371 |
| false | 2 | 1.298 | 0.9618 |
| false | 2 | 1.296 | 0.8686 |
| false | 2 | 1.210 | 1.208 |
| false | 2 | 1.085 | 1.355 |
| false | 2 | 1.267 | 1.047 |
| false | 2 | 1.220 | 1.090 |
| false | 2 | 1.347 | 0.7337 |
| false | 2 | 1.262 | 0.9096 |
| false | 2 | 1.146 | 1.289 |
| false | 2 | 1.233 | 1.057 |
| false | 2 | 1.292 | 0.8480 |
| false | 2 | 1.402 | 0.8266 |
| false | 2 | 1.101 | 1.483 |
| false | 2 | 1.018 | 1.590 |
| false | 2 | 1.126 | 1.395 |
| false | 2 | 1.198 | 1.159 |
| false | 2 | 1.069 | 1.334 |
| false | 2 | 1.156 | 1.304 |
| false | 2 | 1.135 | 1.100 |
| false | 2 | 1.158 | 1.250 |
| false | 2 | 1.282 | 1.197 |
| false | 2 | 1.128 | 0.9619 |
| false | 2 | 1.198 | 1.024 |
| false | 2 | 1.204 | 0.8165 |
| false | 2 | 1.181 | 1.057 |
| false | 2 | 1.186 | 1.166 |
| false | 2 | 1.203 | 1.120 |
| false | 2 | 1.263 | 0.9292 |
| false | 2 | 1.250 | 0.8752 |
| false | 2 | 1.125 | 1.092 |
| false | 2 | 1.120 | 1.448 |
| false | 2 | 1.087 | 1.519 |
| false | 2 | 1.246 | 0.8946 |
| false | 2 | 1.264 | 1.003 |
| false | 2 | 1.164 | 1.213 |
| false | 2 | 1.227 | 1.200 |
| false | 2 | 1.355 | 0.8076 |
| false | 2 | 1.206 | 1.099 |
| false | 2 | 1.221 | 1.160 |
| false | 2 | 1.162 | 0.1799 |
| false | 2 | 1.335 | 0.9257 |
| false | 2 | 1.145 | 1.092 |
| false | 2 | 1.101 | 1.259 |
| false | 2 | 1.256 | 0.8101 |
| false | 2 | 1.154 | 1.297 |
| false | 2 | 1.300 | 0.9399 |
| false | 2 | 1.157 | 1.280 |
| false | 2 | 1.237 | 1.042 |
| false | 1 | −0.6808 | −0.3430 |
| false | 1 | −0.5544 | −0.3459 |
| false | 1 | −0.6960 | −0.4233 |
| false | 1 | −0.1850 | −0.7979 |
| false | 1 | −0.5467 | −0.5576 |
| false | 1 | −0.3479 | −0.5572 |
| false | 1 | −0.5927 | −0.3249 |
| false | 1 | 0.1240 | −0.6021 |
| false | 1 | −0.5526 | −0.4878 |
| false | 1 | −0.1628 | −0.5936 |
First 60 of 152 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 1.195 |
| false | 1.935 |
| false | 1.521 |
| false | 1.780 |
| false | 1.249 |
| false | 2.179 |
| false | 1.369 |
| false | 1.178 |
| false | 2.656 |
| false | 1.678 |
| false | 1.598 |
| false | 1.214 |
| false | 2.005 |
| false | 2.638 |
| false | 3.121 |
| true | 5.327 |
| false | 2.163 |
| false | 1.194 |
| false | 2.282 |
| false | 1.636 |
| false | 1.469 |
| false | 1.443 |
| false | 1.576 |
| false | 1.436 |
| false | 1.261 |
| false | 1.945 |
| false | 1.216 |
| false | 1.236 |
| false | 1.256 |
| false | 1.484 |
| false | 1.651 |
| false | 1.493 |
| false | 2.882 |
| true | 3.634 |
| false | 1.634 |
| false | 1.462 |
| false | 1.554 |
| false | 1.298 |
| false | 2.342 |
| false | 1.201 |
| false | 1.189 |
| true | 5.689 |
| false | 1.851 |
| false | 1.396 |
| false | 1.748 |
| false | 1.935 |
| false | 1.638 |
| false | 1.582 |
| false | 1.506 |
| false | 1.267 |
| false | 1.758 |
| false | 1.285 |
| false | 1.243 |
| false | 1.979 |
| false | 0.8198 |
| false | 1.066 |
| false | 1.483 |
| false | 2.923 |
| false | 1.095 |
| false | 1.755 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.013 | 1 |
| total | 5.402 | 2 |
| total | 4.861 | 3 |
| total | 4.511 | 4 |
| total | 4.397 | 5 |
| total | 4.070 | 6 |
| total | 4.020 | 7 |
| total | 3.615 | 8 |
| total | 3.467 | 9 |
| total | 3.248 | 10 |
| total | 3.106 | 11 |
| total | 3.234 | 12 |
| total | 3.258 | 13 |
| total | 2.772 | 14 |
| total | 3.227 | 15 |
| total | 2.832 | 16 |
| total | 2.637 | 17 |
| total | 2.430 | 18 |
| total | 2.747 | 19 |
| total | 2.590 | 20 |
| total | 2.379 | 21 |
| total | 2.442 | 22 |
| total | 2.496 | 23 |
| total | 2.364 | 24 |
| total | 2.358 | 25 |
| total | 2.262 | 26 |
| total | 2.246 | 27 |
| total | 2.317 | 28 |
| total | 2.330 | 29 |
| total | 2.227 | 30 |
| total | 2.258 | 31 |
| total | 2.167 | 32 |
| total | 2.302 | 33 |
| total | 2.153 | 34 |
| total | 2.155 | 35 |
| total | 2.140 | 36 |
| total | 2.255 | 37 |
| total | 2.154 | 38 |
| total | 2.161 | 39 |
| total | 2.084 | 40 |
| total | 2.214 | 41 |
| total | 2.136 | 42 |
| total | 2.095 | 43 |
| total | 2.129 | 44 |
| total | 2.209 | 45 |
| total | 2.147 | 46 |
| total | 2.051 | 47 |
| total | 2.069 | 48 |
| total | 2.164 | 49 |
| total | 2.138 | 50 |
| total | 2.233 | 51 |
| total | 2.227 | 52 |
| total | 2.194 | 53 |
| total | 2.042 | 54 |
| total | 2.147 | 55 |
| total | 2.238 | 56 |
| total | 2.099 | 57 |
| total | 2.098 | 58 |
| total | 2.002 | 59 |
| total | 2.250 | 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 | synthetic | 4.480 |
| 0.2222 | synthetic | 4.600 |
| 0.3333 | synthetic | 4.720 |
| 0.3889 | synthetic | 4.840 |
| 0.9444 | synthetic | 4.960 |
| 0.6111 | synthetic | 5.080 |
| 0.3889 | synthetic | 5.200 |
| 0.1111 | synthetic | 5.320 |
| 0.0556 | synthetic | 5.440 |
| 0.1111 | synthetic | 5.560 |
| 0.1667 | synthetic | 5.680 |
| 0.6111 | synthetic | 5.800 |
| 0.3889 | synthetic | 5.920 |
| 0.4444 | synthetic | 6.040 |
| 0.6667 | synthetic | 6.160 |
| 0.5556 | synthetic | 6.280 |
| 0.4444 | synthetic | 6.400 |
| 0.3889 | synthetic | 6.520 |
| 0.5000 | synthetic | 6.640 |
| 0.5556 | synthetic | 6.760 |
| 0.2778 | synthetic | 6.880 |
| 0.1667 | 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 | 42 | 5.689 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.426 | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 16 | 5.327 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 118 | 5.122 | 7.700 | 3.800 | 6.700 | 2.200 |
| 5 | 119 | 4.330 | 7.700 | 2.600 | 6.900 | 2.300 |
| 6 | 61 | 3.958 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.634 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 123 | 3.244 | 7.700 | 2.800 | 6.700 | 2 |
| 9 | 110 | 3.224 | 7.200 | 3.600 | 6.100 | 2.500 |
| 10 | 15 | 3.121 | 5.800 | 4 | 1.200 | 0.2000 |
| 11 | 58 | 2.923 | 4.900 | 2.400 | 3.300 | 1 |
| 12 | 94 | 2.892 | 5 | 2.300 | 3.300 | 1 |
| 13 | 33 | 2.882 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 14 | 107 | 2.715 | 4.900 | 2.500 | 4.500 | 1.700 |
| 15 | 136 | 2.692 | 7.700 | 3 | 6.100 | 2.300 |
| 16 | 9 | 2.656 | 4.400 | 2.900 | 1.400 | 0.2000 |
| 17 | 14 | 2.638 | 4.300 | 3 | 1.100 | 0.1000 |
| 18 | 99 | 2.634 | 5.100 | 2.500 | 3 | 1.100 |
| 19 | 63 | 2.591 | 6 | 2.200 | 4 | 1 |
| 20 | 106 | 2.581 | 7.600 | 3 | 6.600 | 2.100 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.3252 | 0.7428 | yes |
| 2 | 0.0985 | 0.6258 | yes |
Mixture prior components
| Component | Rows | Prior weight | Mean 1 | Mean 2 |
|---|---|---|---|---|
| 1 | 100 | 0.4957 | −0.5351 | −0.5602 |
| 2 | 50 | 0.3373 | 1.176 | 1.058 |
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 a366cea2bf985d25
# 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_vade/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 <- "mixture" # 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_vade/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.154 per standardized column and the mean KL is 1.06 nats; 8 rows with a loss of at least 3.24 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.125. The mixture prior's 3 components hold 2 clusters of rows.
- Mean reconstruction error
- 0.1545
- Mean KL (nats per row)
- 1.060
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.9758
- 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 | 42 | 5.689 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.426 | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 16 | 5.327 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 118 | 5.122 | 7.700 | 3.800 | 6.700 | 2.200 |
| 5 | 119 | 4.330 | 7.700 | 2.600 | 6.900 | 2.300 |
| 6 | 61 | 3.958 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.634 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 123 | 3.244 | 7.700 | 2.800 | 6.700 | 2 |
| 9 | 110 | 3.224 | 7.200 | 3.600 | 6.100 | 2.500 |
| 10 | 15 | 3.121 | 5.800 | 4 | 1.200 | 0.2000 |
| 11 | 58 | 2.923 | 4.900 | 2.400 | 3.300 | 1 |
| 12 | 94 | 2.892 | 5 | 2.300 | 3.300 | 1 |
| 13 | 33 | 2.882 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 14 | 107 | 2.715 | 4.900 | 2.500 | 4.500 | 1.700 |
| 15 | 136 | 2.692 | 7.700 | 3 | 6.100 | 2.300 |
| 16 | 9 | 2.656 | 4.400 | 2.900 | 1.400 | 0.2000 |
| 17 | 14 | 2.638 | 4.300 | 3 | 1.100 | 0.1000 |
| 18 | 99 | 2.634 | 5.100 | 2.500 | 3 | 1.100 |
| 19 | 63 | 2.591 | 6 | 2.200 | 4 | 1 |
| 20 | 106 | 2.581 | 7.600 | 3 | 6.600 | 2.100 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.3252 | 0.7428 | yes |
| 2 | 0.0985 | 0.6258 | yes |
Mixture prior components
| Component | Rows | Prior weight | Mean 1 | Mean 2 |
|---|---|---|---|---|
| 1 | 100 | 0.4957 | −0.5351 | −0.5602 |
| 2 | 50 | 0.3373 | 1.176 | 1.058 |
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 a366cea2bf985d25
# 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_vade/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 = "mixture" # 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_vade/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,
})
Prior: Gaussian mixture gives the code space 3 clusters to fill instead of one round cloud (VaDEVaDEA variational autoencoder whose prior is a learned mixture of Gaussians, so the same model maps, generates and clusters rows.). Same data, same widths, same epochs. The sample distance falls to 0.125, while the rebuild error is 0.154.
One comparison on one seed is a hint, not proof. Repeat across seeds and judge on held-out rows before keeping the change.
Mixed columns and a softer KL
ExploreA variational autoencoder mapped 344 rows into 3 latent coordinates (3 in use); the mean squared reconstruction error is 0.0852 per standardized column and the mean KL is 2.25 nats; 10 rows with a loss of at least 3 are flagged as anomalies. 300 rows generated from the prior differ from the data by a mean KS distance of 0.124.
- Mean reconstruction error
- 0.0852
- Mean KL (nats per row)
- 2.247
- Active latent dimensions
- 3
- Trustworthiness (k = 10)
- 0.9680
- Anomalies
- 10
Plots
View data
| species | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|
| Adelie | −1.141 | −1.179 |
| Adelie | −0.6157 | −0.2508 |
| Adelie | −0.7522 | −0.0108 |
| Adelie | −0.0441 | −0.0663 |
| Adelie | −0.9352 | −0.7223 |
| Adelie | −1.177 | −1.328 |
| Adelie | −0.8850 | −0.2918 |
| Adelie | −0.4266 | −1.230 |
| Adelie | −0.6987 | −1.536 |
| Adelie | −0.9254 | −0.7389 |
| Adelie | −0.7035 | −1.023 |
| Adelie | −0.9433 | −1.083 |
| Adelie | −0.9657 | 0.1200 |
| Adelie | −1.198 | −1.422 |
| Adelie | −0.9448 | −1.842 |
| Adelie | −0.8022 | −0.6920 |
| Adelie | −0.8577 | −0.3698 |
| Adelie | −0.6615 | −0.8828 |
| Adelie | −1.070 | −0.9976 |
| Adelie | −0.9082 | −0.3532 |
| Adelie | −0.9958 | −0.2720 |
| Adelie | −0.9924 | −1.015 |
| Adelie | −0.5905 | −0.8057 |
| Adelie | −0.5908 | −0.9841 |
| Adelie | −0.6853 | −0.8234 |
| Adelie | −0.5853 | −0.8562 |
| Adelie | −0.9062 | −0.5847 |
| Adelie | −0.7418 | 0.1618 |
| Adelie | −1.238 | −0.2067 |
| Adelie | −0.7818 | −0.6975 |
| Adelie | −0.9471 | 0.6034 |
| Adelie | −1.081 | −0.6060 |
| Adelie | −0.8588 | 0.4990 |
| Adelie | −1.026 | −0.2102 |
| Adelie | −0.6944 | 0.0398 |
| Adelie | −1.046 | −0.8257 |
| Adelie | −1.096 | −0.6613 |
| Adelie | −0.9826 | 0.8071 |
| Adelie | −1.255 | 0.1502 |
| Adelie | −0.6624 | −0.5017 |
| Adelie | −1.121 | 0.1228 |
| Adelie | −0.6784 | −0.2780 |
| Adelie | −1.167 | −0.0192 |
| Adelie | −0.6106 | −0.1430 |
| Adelie | −0.9850 | 0.2950 |
| Adelie | −0.5440 | −0.5743 |
| Adelie | −1.339 | −0.1268 |
| Adelie | −1.446 | −0.5116 |
| Adelie | −0.8285 | −0.1580 |
| Adelie | −1.098 | −0.3708 |
| Adelie | −0.5625 | −0.0394 |
| Adelie | −0.4639 | −0.9229 |
| Adelie | −0.5717 | −0.6632 |
| Adelie | −0.4452 | −0.7170 |
| Adelie | −0.9354 | −0.5060 |
| Adelie | −0.6511 | −0.5528 |
| Adelie | −0.4992 | −0.1196 |
| Adelie | −0.6147 | −0.7612 |
| Adelie | −0.9135 | −0.1461 |
| Adelie | −0.7260 | −1.235 |
First 60 of 344 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 2.083 |
| false | 1.841 |
| false | 2.056 |
| false | 2.141 |
| false | 2.384 |
| false | 2.179 |
| false | 2.052 |
| false | 2.262 |
| false | 2.475 |
| false | 2.257 |
| false | 2.158 |
| false | 2.513 |
| false | 2.304 |
| false | 2.547 |
| true | 3.493 |
| false | 1.778 |
| false | 2.255 |
| false | 2.638 |
| false | 2.064 |
| true | 3.217 |
| true | 3.033 |
| false | 2.707 |
| false | 2.562 |
| false | 2.092 |
| false | 2.861 |
| false | 2.496 |
| false | 2.230 |
| false | 1.934 |
| true | 3.485 |
| false | 2.412 |
| false | 1.919 |
| false | 2.775 |
| false | 1.171 |
| false | 1.685 |
| false | 1.582 |
| false | 2.456 |
| false | 1.900 |
| false | 1.928 |
| false | 2.230 |
| false | 2.672 |
| false | 1.759 |
| false | 1.386 |
| false | 1.857 |
| false | 1.386 |
| false | 1.625 |
| false | 2.020 |
| false | 1.744 |
| false | 2.778 |
| false | 1.578 |
| false | 2.409 |
| false | 1.705 |
| false | 1.750 |
| false | 1.894 |
| false | 1.680 |
| false | 2.391 |
| false | 1.637 |
| false | 1.644 |
| false | 1.526 |
| false | 2.440 |
| false | 1.932 |
First 60 of 344 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 16.940 | 1 |
| total | 9.503 | 2 |
| total | 7.461 | 3 |
| total | 5.716 | 4 |
| total | 5.115 | 5 |
| total | 4.720 | 6 |
| total | 4.288 | 7 |
| total | 4.099 | 8 |
| total | 3.867 | 9 |
| total | 3.818 | 10 |
| total | 3.745 | 11 |
| total | 3.701 | 12 |
| total | 3.720 | 13 |
| total | 3.527 | 14 |
| total | 3.513 | 15 |
| total | 3.408 | 16 |
| total | 3.397 | 17 |
| total | 3.332 | 18 |
| total | 3.235 | 19 |
| total | 3.168 | 20 |
| total | 3.118 | 21 |
| total | 3.140 | 22 |
| total | 2.928 | 23 |
| total | 2.975 | 24 |
| total | 2.927 | 25 |
| total | 2.910 | 26 |
| total | 2.837 | 27 |
| total | 2.865 | 28 |
| total | 2.795 | 29 |
| total | 2.740 | 30 |
| total | 2.691 | 31 |
| total | 2.684 | 32 |
| total | 2.658 | 33 |
| total | 2.643 | 34 |
| total | 2.668 | 35 |
| total | 2.663 | 36 |
| total | 2.561 | 37 |
| total | 2.582 | 38 |
| total | 2.537 | 39 |
| total | 2.562 | 40 |
| total | 2.589 | 41 |
| total | 2.522 | 42 |
| total | 2.535 | 43 |
| total | 2.491 | 44 |
| total | 2.461 | 45 |
| total | 2.505 | 46 |
| total | 2.607 | 47 |
| total | 2.571 | 48 |
| total | 2.505 | 49 |
| total | 2.463 | 50 |
| total | 2.516 | 51 |
| total | 2.473 | 52 |
| total | 2.488 | 53 |
| total | 2.452 | 54 |
| total | 2.429 | 55 |
| total | 2.483 | 56 |
| total | 2.455 | 57 |
| total | 2.488 | 58 |
| total | 2.505 | 59 |
| total | 2.539 | 60 |
First 60 of 240 rows.
View data
| Density | Source | bill_len |
|---|---|---|
| 0.0032 | real | 32.558 |
| 0.0064 | real | 33.475 |
| 0.0191 | real | 34.392 |
| 0.0351 | real | 35.308 |
| 0.0510 | real | 36.225 |
| 0.0415 | real | 37.142 |
| 0.0670 | real | 38.058 |
| 0.0542 | real | 38.975 |
| 0.0606 | real | 39.892 |
| 0.0670 | real | 40.808 |
| 0.0415 | real | 41.725 |
| 0.0447 | real | 42.642 |
| 0.0447 | real | 43.558 |
| 0.0255 | real | 44.475 |
| 0.0861 | real | 45.392 |
| 0.0797 | real | 46.308 |
| 0.0574 | real | 47.225 |
| 0.0383 | real | 48.142 |
| 0.0606 | real | 49.058 |
| 0.0670 | real | 49.975 |
| 0.0670 | real | 50.892 |
| 0.0351 | real | 51.808 |
| 0.0096 | real | 52.725 |
| 0.0064 | real | 53.642 |
| 0.0064 | real | 54.558 |
| 0.0096 | real | 55.475 |
| 0 | real | 56.392 |
| 0 | real | 57.308 |
| 0.0032 | real | 58.225 |
| 0.0032 | real | 59.142 |
| 0.0036 | synthetic | 32.558 |
| 0 | synthetic | 33.475 |
| 0.0073 | synthetic | 34.392 |
| 0.0109 | synthetic | 35.308 |
| 0.0255 | synthetic | 36.225 |
| 0.0291 | synthetic | 37.142 |
| 0.0582 | synthetic | 38.058 |
| 0.0764 | synthetic | 38.975 |
| 0.1018 | synthetic | 39.892 |
| 0.0764 | synthetic | 40.808 |
| 0.0291 | synthetic | 41.725 |
| 0.0655 | synthetic | 42.642 |
| 0.0582 | synthetic | 43.558 |
| 0.0691 | synthetic | 44.475 |
| 0.0909 | synthetic | 45.392 |
| 0.0873 | synthetic | 46.308 |
| 0.0436 | synthetic | 47.225 |
| 0.0800 | synthetic | 48.142 |
| 0.0364 | synthetic | 49.058 |
| 0.0473 | synthetic | 49.975 |
| 0.0327 | synthetic | 50.892 |
| 0.0255 | synthetic | 51.808 |
| 0.0036 | synthetic | 52.725 |
| 0.0073 | synthetic | 53.642 |
| 0.0036 | synthetic | 54.558 |
| 0.0145 | synthetic | 55.475 |
| 0 | synthetic | 56.392 |
| 0.0036 | synthetic | 57.308 |
| 0 | synthetic | 58.225 |
| 0.0036 | synthetic | 59.142 |
Assumptions
- Latent dimensions in use — 3 of 3 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | island | bill_len | bill_dep | flipper_len | body_mass | sex |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | 4.851 | Dream | 58 | 17.800 | 181 | 3,700 | female |
| 2 | 186 | 3.874 | Biscoe | 59.600 | 17 | 230 | 6,050 | male |
| 3 | 115 | 3.707 | Biscoe | 39.600 | 20.700 | 191 | 3,900 | female |
| 4 | 15 | 3.493 | Torgersen | 34.600 | 21.100 | 198 | 4,400 | male |
| 5 | 29 | 3.485 | Biscoe | 37.900 | 18.600 | 172 | 3,150 | female |
| 6 | 143 | 3.454 | Dream | 32.100 | 15.500 | 188 | 3,050 | female |
| 7 | 314 | 3.399 | Dream | 52 | 20.700 | 210 | 4,800 | male |
| 8 | 20 | 3.217 | Torgersen | 46 | 21.500 | 194 | 4,200 | male |
| 9 | 99 | 3.171 | Dream | 33.100 | 16.100 | 178 | 2,900 | female |
| 10 | 21 | 3.033 | Biscoe | 37.800 | 18.300 | 174 | 3,400 | female |
| 11 | 25 | 2.861 | Biscoe | 38.800 | 17.200 | 180 | 3,800 | male |
| 12 | 340 | 2.858 | Dream | 55.800 | 19.800 | 207 | 4,000 | male |
| 13 | 123 | 2.851 | Torgersen | 40.200 | 17 | 176 | 3,450 | female |
| 14 | 48 | 2.778 | Dream | 37.500 | 18.900 | 179 | 2,975 | — |
| 15 | 32 | 2.775 | Dream | 37.200 | 18.100 | 178 | 3,900 | male |
| 16 | 325 | 2.769 | Dream | 51.500 | 18.700 | 187 | 3,250 | male |
| 17 | 308 | 2.753 | Dream | 54.200 | 20.800 | 201 | 4,300 | male |
| 18 | 62 | 2.726 | Biscoe | 41.300 | 21.100 | 195 | 4,400 | male |
| 19 | 22 | 2.707 | Biscoe | 37.700 | 18.700 | 180 | 3,600 | male |
| 20 | 315 | 2.700 | Dream | 46.900 | 16.600 | 192 | 2,700 | female |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 1.049 | 0.8742 | yes |
| 2 | 0.4199 | 0.4692 | yes |
| 3 | 0.7780 | 0.7777 | 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 f40446a8353fc58b
# Dataset: ml_penguins (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_penguins.parquet", col_select = c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"))), c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"))
# 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/penguins_mixed_batches/out-r")
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric",
sex = "categorical"
),
levels = list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
),
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_penguins.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(16)))
LATENT <- as.integer(3)
BETA <- 0.5
N_SAMPLES <- as.integer(300)
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 = "relu",
beta = BETA,
epochs = as.integer(80),
lr = 0.005,
batch_size = 64,
weight_decay = 0,
n_samples = N_SAMPLES,
pretrain_epochs = as.integer(100),
seed = 42
)
} else {
cs_deep_fit_vae(
X, HIDDEN, LATENT,
activation = "relu",
beta = BETA,
epochs = as.integer(80),
lr = 0.005,
batch_size = 64,
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 <- "cutoff"
flagged <- cs_ml_flag(scores, RULE, 0.05, 3)
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, "relu", 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/penguins_mixed_batches/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 344 rows into 3 latent coordinates (3 in use); the mean squared reconstruction error is 0.0852 per standardized column and the mean KL is 2.25 nats; 10 rows with a loss of at least 3 are flagged as anomalies. 300 rows generated from the prior differ from the data by a mean KS distance of 0.124.
- Mean reconstruction error
- 0.0852
- Mean KL (nats per row)
- 2.247
- Active latent dimensions
- 3
- Trustworthiness (k = 10)
- 0.9680
- Anomalies
- 10
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Latent dimensions in use — 3 of 3 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | island | bill_len | bill_dep | flipper_len | body_mass | sex |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | 4.851 | Dream | 58 | 17.800 | 181 | 3,700 | female |
| 2 | 186 | 3.874 | Biscoe | 59.600 | 17 | 230 | 6,050 | male |
| 3 | 115 | 3.707 | Biscoe | 39.600 | 20.700 | 191 | 3,900 | female |
| 4 | 15 | 3.493 | Torgersen | 34.600 | 21.100 | 198 | 4,400 | male |
| 5 | 29 | 3.485 | Biscoe | 37.900 | 18.600 | 172 | 3,150 | female |
| 6 | 143 | 3.454 | Dream | 32.100 | 15.500 | 188 | 3,050 | female |
| 7 | 314 | 3.399 | Dream | 52 | 20.700 | 210 | 4,800 | male |
| 8 | 20 | 3.217 | Torgersen | 46 | 21.500 | 194 | 4,200 | male |
| 9 | 99 | 3.171 | Dream | 33.100 | 16.100 | 178 | 2,900 | female |
| 10 | 21 | 3.033 | Biscoe | 37.800 | 18.300 | 174 | 3,400 | female |
| 11 | 25 | 2.861 | Biscoe | 38.800 | 17.200 | 180 | 3,800 | male |
| 12 | 340 | 2.858 | Dream | 55.800 | 19.800 | 207 | 4,000 | male |
| 13 | 123 | 2.851 | Torgersen | 40.200 | 17 | 176 | 3,450 | female |
| 14 | 48 | 2.778 | Dream | 37.500 | 18.900 | 179 | 2,975 | — |
| 15 | 32 | 2.775 | Dream | 37.200 | 18.100 | 178 | 3,900 | male |
| 16 | 325 | 2.769 | Dream | 51.500 | 18.700 | 187 | 3,250 | male |
| 17 | 308 | 2.753 | Dream | 54.200 | 20.800 | 201 | 4,300 | male |
| 18 | 62 | 2.726 | Biscoe | 41.300 | 21.100 | 195 | 4,400 | male |
| 19 | 22 | 2.707 | Biscoe | 37.700 | 18.700 | 180 | 3,600 | male |
| 20 | 315 | 2.700 | Dream | 46.900 | 16.600 | 192 | 2,700 | female |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 1.049 | 0.8742 | yes |
| 2 | 0.4199 | 0.4692 | yes |
| 3 | 0.7780 | 0.7777 | 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 f40446a8353fc58b
# Dataset: ml_penguins (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_penguins.parquet", columns=["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]), ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"])
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/penguins_mixed_batches/out-python",
)
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
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_penguins.parquet", columns=[LABEL])[LABEL]
# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [16]]
LATENT = 3
BETA = 0.5
N_SAMPLES = 300
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="relu",
beta=BETA,
epochs=80,
lr=0.005,
batch_size=64,
weight_decay=0,
n_samples=N_SAMPLES,
pretrain_epochs=100,
seed=42,
)
else:
fit = gen.fit_vae(
X, HIDDEN, LATENT,
activation="relu",
beta=BETA,
epochs=80,
lr=0.005,
batch_size=64,
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 = "cutoff"
flags, threshold = csanom.flag(scores, RULE, 0.05, 3)
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, "relu", 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/penguins_mixed_batches/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,
})
Penguins mixes categories with measurements, and this run uses a KL weight below 1 (a β-VAE tilted toward sharper rebuilds). It uses 3 of 3 dimensions; its 300 samples sit a mean KS distance of 0.124 from the real columns.
The KL weight changed, so this objective is no longer the ELBO. Say so in the report.
For synthetic tables
In the appWhen the goal is a synthetic table, the Synthetic studio's TVAE runs the same idea with a holdout and the full scorecard: fidelity, privacy and utility.
320 synthetic rows over 8 columns from 320 training rows with a tabular variational autoencoder. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.107 and categories by a mean total variation of 0.053.
- Synthetic rows
- 320
- Mean KS distance
- 0.1072
- Mean TV distance
- 0.0533
- Rows copied from the data
- 0
Plots
View data
| Density | Source | age |
|---|---|---|
| 0.0230 | real | 18.950 |
| 0.0016 | real | 20.850 |
| 0.0049 | real | 22.750 |
| 0.0148 | real | 24.650 |
| 0.0148 | real | 26.550 |
| 0.0181 | real | 28.450 |
| 0.0197 | real | 30.350 |
| 0.0296 | real | 32.250 |
| 0.0362 | real | 34.150 |
| 0.0115 | real | 36.050 |
| 0.0362 | real | 37.950 |
| 0.0313 | real | 39.850 |
| 0.0296 | real | 41.750 |
| 0.0280 | real | 43.650 |
| 0.0280 | real | 45.550 |
| 0.0181 | real | 47.450 |
| 0.0164 | real | 49.350 |
| 0.0197 | real | 51.250 |
| 0.0362 | real | 53.150 |
| 0.0148 | real | 55.050 |
| 0.0164 | real | 56.950 |
| 0.0181 | real | 58.850 |
| 0.0082 | real | 60.750 |
| 0.0164 | real | 62.650 |
| 0.0049 | real | 64.550 |
| 0.0115 | real | 66.450 |
| 0.0066 | real | 68.350 |
| 0.0049 | real | 70.250 |
| 0.0016 | real | 72.150 |
| 0.0049 | real | 74.050 |
| 0.0214 | synthetic | 18.950 |
| 0.0016 | synthetic | 20.850 |
| 0.0148 | synthetic | 22.750 |
| 0.0033 | synthetic | 24.650 |
| 0.0164 | synthetic | 26.550 |
| 0.0066 | synthetic | 28.450 |
| 0.0132 | synthetic | 30.350 |
| 0.0362 | synthetic | 32.250 |
| 0.0230 | synthetic | 34.150 |
| 0.0181 | synthetic | 36.050 |
| 0.0197 | synthetic | 37.950 |
| 0.0329 | synthetic | 39.850 |
| 0.0230 | synthetic | 41.750 |
| 0.0345 | synthetic | 43.650 |
| 0.0313 | synthetic | 45.550 |
| 0.0181 | synthetic | 47.450 |
| 0.0164 | synthetic | 49.350 |
| 0.0230 | synthetic | 51.250 |
| 0.0378 | synthetic | 53.150 |
| 0.0197 | synthetic | 55.050 |
| 0.0280 | synthetic | 56.950 |
| 0.0164 | synthetic | 58.850 |
| 0.0148 | synthetic | 60.750 |
| 0.0099 | synthetic | 62.650 |
| 0.0016 | synthetic | 64.550 |
| 0.0099 | synthetic | 66.450 |
| 0.0033 | synthetic | 68.350 |
| 0.0099 | synthetic | 70.250 |
| 0.0016 | synthetic | 72.150 |
| 0.0197 | synthetic | 74.050 |
View data
| Density | Source | annual income |
|---|---|---|
| 3.010e-6 | real | 6851.93 |
| 1.605e-5 | real | 10141.74 |
| 2.107e-5 | real | 13431.55 |
| 2.408e-5 | real | 16721.36 |
| 3.511e-5 | real | 20011.17 |
| 4.113e-5 | real | 23300.98 |
| 2.809e-5 | real | 26590.79 |
| 2.408e-5 | real | 29880.60 |
| 2.508e-5 | real | 33170.41 |
| 1.605e-5 | real | 36460.22 |
| 1.605e-5 | real | 39750.03 |
| 1.505e-5 | real | 43039.84 |
| 1.003e-5 | real | 46329.65 |
| 5.016e-6 | real | 49619.46 |
| 6.019e-6 | real | 52909.27 |
| 4.013e-6 | real | 56199.07 |
| 4.013e-6 | real | 59488.88 |
| 4.013e-6 | real | 62778.69 |
| 1.003e-6 | real | 66068.50 |
| 1.003e-6 | real | 69358.31 |
| 1.003e-6 | real | 72648.12 |
| 0 | real | 75937.93 |
| 1.003e-6 | real | 79227.74 |
| 1.003e-6 | real | 82517.55 |
| 0 | real | 85807.36 |
| 0 | real | 89097.17 |
| 0 | real | 92386.98 |
| 0 | real | 95676.79 |
| 0 | real | 98966.60 |
| 1.003e-6 | real | 102256.41 |
| 1.104e-5 | synthetic | 6851.93 |
| 2.408e-5 | synthetic | 10141.74 |
| 2.207e-5 | synthetic | 13431.55 |
| 4.213e-5 | synthetic | 16721.36 |
| 4.113e-5 | synthetic | 20011.17 |
| 2.809e-5 | synthetic | 23300.98 |
| 3.010e-5 | synthetic | 26590.79 |
| 2.608e-5 | synthetic | 29880.60 |
| 2.207e-5 | synthetic | 33170.41 |
| 7.022e-6 | synthetic | 36460.22 |
| 1.204e-5 | synthetic | 39750.03 |
| 1.204e-5 | synthetic | 43039.84 |
| 5.016e-6 | synthetic | 46329.65 |
| 4.013e-6 | synthetic | 49619.46 |
| 2.006e-6 | synthetic | 52909.27 |
| 2.006e-6 | synthetic | 56199.07 |
| 2.006e-6 | synthetic | 59488.88 |
| 2.006e-6 | synthetic | 62778.69 |
| 2.006e-6 | synthetic | 66068.50 |
| 1.003e-6 | synthetic | 69358.31 |
| 1.003e-6 | synthetic | 72648.12 |
| 2.006e-6 | synthetic | 75937.93 |
| 0 | synthetic | 79227.74 |
| 1.003e-6 | synthetic | 82517.55 |
| 0 | synthetic | 85807.36 |
| 1.003e-6 | synthetic | 89097.17 |
| 0 | synthetic | 92386.98 |
| 0 | synthetic | 95676.79 |
| 0 | synthetic | 98966.60 |
| 1.003e-6 | synthetic | 102256.41 |
View data
| Density | Source | tenure_months |
|---|---|---|
| 0.0938 | real | 0.7667 |
| 0.0224 | real | 2.300 |
| 0.0183 | real | 3.833 |
| 0.0306 | real | 5.367 |
| 0.0204 | real | 6.900 |
| 0.0265 | real | 8.433 |
| 0.0204 | real | 9.967 |
| 0.0530 | real | 11.500 |
| 0.0183 | real | 13.033 |
| 0.0510 | real | 14.567 |
| 0.0183 | real | 16.100 |
| 0.0367 | real | 17.633 |
| 0.0224 | real | 19.167 |
| 0.0448 | real | 20.700 |
| 0.0469 | real | 22.233 |
| 0.0082 | real | 23.767 |
| 0.0306 | real | 25.300 |
| 0.0061 | real | 26.833 |
| 0.0183 | real | 28.367 |
| 0.0041 | real | 29.900 |
| 0.0143 | real | 31.433 |
| 0.0061 | real | 32.967 |
| 0.0183 | real | 34.500 |
| 0.0020 | real | 36.033 |
| 0.0041 | real | 37.567 |
| 0 | real | 39.100 |
| 0.0061 | real | 40.633 |
| 0.0041 | real | 42.167 |
| 0.0020 | real | 43.700 |
| 0.0041 | real | 45.233 |
| 0.1223 | synthetic | 0.7667 |
| 0.0245 | synthetic | 2.300 |
| 0.0306 | synthetic | 3.833 |
| 0.0448 | synthetic | 5.367 |
| 0.0102 | synthetic | 6.900 |
| 0.0387 | synthetic | 8.433 |
| 0.0204 | synthetic | 9.967 |
| 0.0591 | synthetic | 11.500 |
| 0.0245 | synthetic | 13.033 |
| 0.0489 | synthetic | 14.567 |
| 0.0163 | synthetic | 16.100 |
| 0.0428 | synthetic | 17.633 |
| 0.0224 | synthetic | 19.167 |
| 0.0448 | synthetic | 20.700 |
| 0.0265 | synthetic | 22.233 |
| 0.0082 | synthetic | 23.767 |
| 0.0143 | synthetic | 25.300 |
| 0.0061 | synthetic | 26.833 |
| 0.0082 | synthetic | 28.367 |
| 0.0061 | synthetic | 29.900 |
| 0.0082 | synthetic | 31.433 |
| 0.0020 | synthetic | 32.967 |
| 0.0061 | synthetic | 34.500 |
| 0.0041 | synthetic | 36.033 |
| 0.0041 | synthetic | 37.567 |
| 0.0020 | synthetic | 39.100 |
| 0.0041 | synthetic | 40.633 |
| 0 | synthetic | 42.167 |
| 0.0020 | synthetic | 43.700 |
| 0 | synthetic | 45.233 |
View data
| Density | Source | signup |
|---|---|---|
| 0.0005 | real | 17582.23 |
| 0.0007 | real | 17654.70 |
| 0.0005 | real | 17727.17 |
| 0.0005 | real | 17799.63 |
| 0.0004 | real | 17872.10 |
| 0.0005 | real | 17944.57 |
| 0.0006 | real | 18017.03 |
| 0.0004 | real | 18089.50 |
| 0.0005 | real | 18161.97 |
| 0.0005 | real | 18234.43 |
| 0.0001 | real | 18306.90 |
| 0.0009 | real | 18379.37 |
| 0.0006 | real | 18451.83 |
| 0.0003 | real | 18524.30 |
| 0.0005 | real | 18596.77 |
| 0.0004 | real | 18669.23 |
| 0.0002 | real | 18741.70 |
| 0.0005 | real | 18814.17 |
| 0.0006 | real | 18886.63 |
| 0.0005 | real | 18959.10 |
| 0.0005 | real | 19031.57 |
| 0.0005 | real | 19104.03 |
| 0.0003 | real | 19176.50 |
| 0.0006 | real | 19248.97 |
| 0.0004 | real | 19321.43 |
| 0.0003 | real | 19393.90 |
| 0.0002 | real | 19466.37 |
| 0.0005 | real | 19538.83 |
| 0.0003 | real | 19611.30 |
| 0.0004 | real | 19683.77 |
| 0.0006 | synthetic | 17582.23 |
| 0.0004 | synthetic | 17654.70 |
| 0.0005 | synthetic | 17727.17 |
| 0.0002 | synthetic | 17799.63 |
| 0.0004 | synthetic | 17872.10 |
| 0.0006 | synthetic | 17944.57 |
| 0.0003 | synthetic | 18017.03 |
| 0.0004 | synthetic | 18089.50 |
| 0.0004 | synthetic | 18161.97 |
| 0.0004 | synthetic | 18234.43 |
| 0.0005 | synthetic | 18306.90 |
| 0.0004 | synthetic | 18379.37 |
| 0.0004 | synthetic | 18451.83 |
| 0.0003 | synthetic | 18524.30 |
| 0.0005 | synthetic | 18596.77 |
| 0.0003 | synthetic | 18669.23 |
| 0.0004 | synthetic | 18741.70 |
| 0.0003 | synthetic | 18814.17 |
| 0.0003 | synthetic | 18886.63 |
| 0.0003 | synthetic | 18959.10 |
| 0.0004 | synthetic | 19031.57 |
| 0.0008 | synthetic | 19104.03 |
| 0.0003 | synthetic | 19176.50 |
| 0.0005 | synthetic | 19248.97 |
| 0.0003 | synthetic | 19321.43 |
| 0.0002 | synthetic | 19393.90 |
| 0.0004 | synthetic | 19466.37 |
| 0.0007 | synthetic | 19538.83 |
| 0.0012 | synthetic | 19611.30 |
| 0.0009 | synthetic | 19683.77 |
View data
| plan | Share | Source |
|---|---|---|
| basic | 0.3563 | real |
| plus | 0.3969 | real |
| premium | 0.2469 | real |
| basic | 0.3594 | synthetic |
| plus | 0.3844 | synthetic |
| premium | 0.2562 | synthetic |
View data
| region | Share | Source |
|---|---|---|
| east | 0.2848 | real |
| north | 0.2718 | real |
| south | 0.3042 | real |
| west | 0.1392 | real |
| east | 0.3738 | synthetic |
| north | 0.2236 | synthetic |
| south | 0.2300 | synthetic |
| west | 0.1725 | synthetic |
View data
| churned | Share | Source |
|---|---|---|
| false | 0.7688 | real |
| true | 0.2313 | real |
| false | 0.7438 | synthetic |
| true | 0.2562 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| age | age | 0 |
| annual income | age | 0.3306 |
| tenure_months | age | 0.8144 |
| signup | age | 0.0037 |
| visits | age | 0.0790 |
| age | annual income | 0.3306 |
| annual income | annual income | 0 |
| tenure_months | annual income | 0.0613 |
| signup | annual income | −0.1297 |
| visits | annual income | 0.2451 |
| age | tenure_months | 0.8144 |
| annual income | tenure_months | 0.0613 |
| tenure_months | tenure_months | 0 |
| signup | tenure_months | −0.1346 |
| visits | tenure_months | 0.0903 |
| age | signup | 0.0037 |
| annual income | signup | −0.1297 |
| tenure_months | signup | −0.1346 |
| signup | signup | 0 |
| visits | signup | −0.0712 |
| age | visits | 0.0790 |
| annual income | visits | 0.2451 |
| tenure_months | visits | 0.0903 |
| signup | visits | −0.0712 |
| visits | visits | 0 |
Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal.
View data
| Part | Loss | Epoch |
|---|---|---|
| total | 104.75 | 1 |
| total | 86.978 | 2 |
| total | 67.383 | 3 |
| total | 54.894 | 4 |
| total | 49.277 | 5 |
| total | 44.515 | 6 |
| total | 37.980 | 7 |
| total | 32.825 | 8 |
| total | 29.225 | 9 |
| total | 26.194 | 10 |
| total | 24.816 | 11 |
| total | 22.427 | 12 |
| total | 20.767 | 13 |
| total | 19.011 | 14 |
| total | 18.161 | 15 |
| total | 18.254 | 16 |
| total | 16.778 | 17 |
| total | 16.359 | 18 |
| total | 16.371 | 19 |
| total | 14.867 | 20 |
| total | 15.334 | 21 |
| total | 14.416 | 22 |
| total | 14.432 | 23 |
| total | 13.683 | 24 |
| total | 13.563 | 25 |
| total | 13.810 | 26 |
| total | 13.225 | 27 |
| total | 13.096 | 28 |
| total | 13.270 | 29 |
| total | 12.573 | 30 |
| reconstruction | 103.23 | 1 |
| reconstruction | 85.558 | 2 |
| reconstruction | 66.001 | 3 |
| reconstruction | 53.506 | 4 |
| reconstruction | 47.858 | 5 |
| reconstruction | 43.049 | 6 |
| reconstruction | 36.459 | 7 |
| reconstruction | 31.229 | 8 |
| reconstruction | 27.546 | 9 |
| reconstruction | 24.429 | 10 |
| reconstruction | 22.978 | 11 |
| reconstruction | 20.518 | 12 |
| reconstruction | 18.784 | 13 |
| reconstruction | 16.959 | 14 |
| reconstruction | 16.052 | 15 |
| reconstruction | 16.096 | 16 |
| reconstruction | 14.584 | 17 |
| reconstruction | 14.134 | 18 |
| reconstruction | 14.127 | 19 |
| reconstruction | 12.608 | 20 |
| reconstruction | 13.071 | 21 |
| reconstruction | 12.162 | 22 |
| reconstruction | 12.198 | 23 |
| reconstruction | 11.477 | 24 |
| reconstruction | 11.388 | 25 |
| reconstruction | 11.664 | 26 |
| reconstruction | 11.102 | 27 |
| reconstruction | 10.991 | 28 |
| reconstruction | 11.177 | 29 |
| reconstruction | 10.490 | 30 |
First 60 of 90 rows.
Assumptions
- Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
- Training stayed finite — The loss over the last 10% of epochs averaged 13 (reconstruction 10.9, KL 2.09).
- No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
- Synthetic columns match the data — Distance from the training rows: numeric columns 0.107 (mean Kolmogorov–Smirnov distance); categories 0.053 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 45.01 ± 13.8 | 0.0781 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.614e+04 ± 1.46e+04 | 0.1518 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 12.24 ± 9.7 | 0.1250 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 38.4% | 0.0125 | total variation |
| region | categorical | south 30.4% | south 23.0% | 0.1224 | total variation |
| churned | boolean | false 76.9% | false 74.4% | 0.0250 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2021-04-05 ± 684 days | 0.1375 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.212 ± 1.96 | 0.0438 | Kolmogorov–Smirnov D |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| age | 5 |
| annual income | 5 |
| tenure_months | 5 |
| signup | 5 |
| visits | 5 |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — tabular VAE (TVAE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.tvae 1.0.1 · spec c592bbd6d043a651
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
COLUMNS <- c("age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits")
KINDS <- list(
age = "numeric",
`annual income` = "numeric",
tenure_months = "numeric",
plan = "categorical",
region = "categorical",
churned = "boolean",
signup = "temporal",
visits = "numeric"
)
LEVELS <- list(
plan = c("basic", "plus", "premium"),
region = c("east", "north", "south", "west")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
cols <- loaded$cols; n_input <- loaded$n
for (c in cols) if (c$kind == "numeric") cs_check_finite(c$values, c$name) # infinite values stop the run (registry/errors.yaml)
rng <- cs_rng(SEED) # shared stream: the same holdout and the same synthetic rows in Python and R
sp <- cs_synth_split(n_input, 0.2, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- length(train_rows)
warnings <- list()
fit_values <- list()
extra_tables <- list()
extra_charts <- list()
assumptions <- list()
model_note <- ""
if (length(holdout_rows)) {
warnings <- c(warnings, sprintf("%s of %s rows (%.0f%%) were held out of training so privacy and utility can be checked against rows the generator never saw.",
format(length(holdout_rows), big.mark = ","), format(n_input, big.mark = ","), 100 * length(holdout_rows) / n_input))
}
for (c in train) if (mean(cs_synth_missing(c)) == 1) cs_error("CS_E_ALL_MISSING", column = c$name) # no values in the training rows
n_complete <- length(cs_synth_complete(train))
assumptions[[1]] <- list(
key = "enough_rows", label = "Enough rows for a neural generator",
status = if (n_complete >= 1000) "pass" else "warn",
detail = paste0(sprintf("%s complete training rows", format(n_complete, big.mark = ",")),
if (n_complete >= 1000) "." else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.")
)
# %% Generate
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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/synth.tvae/customers_all/out-r")
# Tabular VAE on rows encoded by mode-specific normalization (numbers -> [alpha, mode one-hot], categories one-hot):
# encoder -> N(mu, sigma^2) code of 8 dimensions -> decoder; KL weight beta = 1.
# Twin of codesplash.synth.tvae.fit_tvae (clean-room; no CTGAN/SDV code).
HIDDEN <- as.integer(unlist(c(32, 32)))
fit <- cs_synth_tvae(
train, N_OUT, rng, HIDDEN,
latent_dim = as.integer(8),
epochs = as.integer(30),
batch_size = 100,
lr = 0.001,
beta = 1,
n_modes = as.integer(5),
seed = SEED
)
synth <- fit$cols
hist <- fit$history
history <- data.frame(
epoch = vapply(hist, function(h) as.numeric(h$epoch), numeric(1)),
loss = vapply(hist, function(h) h$loss, numeric(1)),
reconstruction = vapply(hist, function(h) h$reconstruction, numeric(1)),
kl = vapply(hist, function(h) h$kl, numeric(1))
)
last <- max(1L, nrow(history) %/% 10L) # the last 10% of epochs
tail_rows <- (nrow(history) - last + 1L):nrow(history)
fit_values$batch_size <- fit$facts$batch_size
fit_values$latent_dim <- fit$facts$latent_dim
fit_values$final_loss <- mean(history$loss[tail_rows])
fit_values$reconstruction <- mean(history$reconstruction[tail_rows])
fit_values$kl <- mean(history$kl[tail_rows])
if (!is.nan(fit$facts$sigma_mean)) fit_values$sigma_mean <- fit$facts$sigma_mean
for (j in seq_along(COLUMNS)) {
k <- fit$facts$modes[[j]]
if (!is.null(k)) fit_values[[sprintf("modes[%s]", COLUMNS[j])]] <- as.integer(k)
}
model_note <- " with a tabular variational autoencoder"
ne <- nrow(history)
extra_charts[[length(extra_charts) + 1L]] <- cs_chart("training", "training-components", "TVAE loss by epoch", list(
x = cs_col("Epoch", rep(history$epoch, 3), "numeric"),
value = cs_col("Loss", c(history$loss, history$reconstruction, history$kl), "numeric"),
component = cs_col("Part", rep(c("total", "reconstruction", "KL divergence"), each = ne), "categorical",
levels = c("total", "reconstruction", "KL divergence"))
), note = "Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal.")
finite <- all(is.finite(c(history$loss, history$reconstruction, history$kl)))
assumptions[[length(assumptions) + 1L]] <- list(
key = "training_stable", label = "Training stayed finite",
status = if (finite) "pass" else "fail",
detail = if (finite) sprintf("The loss over the last 10%% of epochs averaged %s (reconstruction %s, KL %s).",
format(signif(fit_values$final_loss, 3)), format(signif(fit_values$reconstruction, 3)), format(signif(fit_values$kl, 3)))
else "A loss became infinite or undefined; lower the learning rate."
)
mode_rows <- list()
for (j in seq_along(COLUMNS)) {
k <- fit$facts$modes[[j]]
if (!is.null(k)) mode_rows[[length(mode_rows) + 1L]] <- list(column = COLUMNS[j], modes = as.integer(k))
}
if (length(mode_rows)) {
extra_tables[[length(extra_tables) + 1L]] <- list(
key = "modes", title = "Modes per numeric column (mode-specific normalization)",
columns = list(list(key = "column", label = "Column", type = "string"), list(key = "modes", label = "Mixture modes", type = "integer")),
rows = mode_rows)
}
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate") # each column's missing share, at random
# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-8142/synth.tvae/customers_all/out-r")
path <- cs_synth_write(file.path(out, "synthetic.parquet"), synth)
split <- cs_synth_write_split(file.path(out, "split.parquet"), n_input, train_rows, holdout_rows)
nanoparquet::write_parquet(history, file.path(out, "history.parquet"))
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
assumptions[[length(assumptions) + 1L]] <- list(
key = "no_copies", label = "No synthetic row copies a training row",
status = if (values$exact_matches == 0) "pass" else "warn",
detail = sprintf("%s synthetic row%s identical to a training row; the scorecard's distance to closest record checks near-copies.",
format(values$exact_matches, big.mark = ","), if (values$exact_matches != 1) "s are" else " is")
)
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at >= 0.9 = 1 - 0.1).
fid_d <- numeric(); fid_t <- character()
if (!is.nan(values$fidelity_ks_mean)) {
fid_d <- c(fid_d, values$fidelity_ks_mean)
fid_t <- c(fid_t, sprintf("numeric columns %.3f (mean Kolmogorov–Smirnov distance)", values$fidelity_ks_mean))
}
if (!is.nan(values$fidelity_tv_mean)) {
fid_d <- c(fid_d, values$fidelity_tv_mean)
fid_t <- c(fid_t, sprintf("categories %.3f (mean total variation)", values$fidelity_tv_mean))
}
assumptions[[length(assumptions) + 1L]] <- if (!length(fid_d)) {
list(key = "fidelity", label = "Synthetic columns match the data", status = "info",
detail = "No column could be compared with the data.")
} else {
list(key = "fidelity", label = "Synthetic columns match the data",
status = if (max(fid_d) <= 0.1) "pass" else "warn",
detail = paste0("Distance from the training rows: ", paste(fid_t, collapse = "; "),
if (max(fid_d) <= 0.1) " — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity."
else " — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."))
}
summary <- sprintf("%s synthetic rows over %d column%s from %s training rows%s.",
format(values$n_rows, big.mark = ","), length(COLUMNS), if (length(COLUMNS) != 1) "s" else "",
format(length(train_rows), big.mark = ","), model_note)
if (!is.nan(values$fidelity_ks_mean)) {
summary <- paste0(summary, sprintf(" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of %.3f", values$fidelity_ks_mean),
if (!is.nan(values$fidelity_tv_mean)) sprintf(" and categories by a mean total variation of %.3f.", values$fidelity_tv_mean) else ".")
} else if (!is.nan(values$fidelity_tv_mean)) {
summary <- paste0(summary, sprintf(" Categories differ from the data by a mean total variation of %.3f.", values$fidelity_tv_mean))
}
if (values$exact_matches > 0) {
summary <- paste0(summary, sprintf(" %s synthetic row%s identical to a training row.", format(values$exact_matches, big.mark = ","),
if (values$exact_matches != 1) "s are" else " is"))
}
cs_publish(list(
title = "Synthetic data — tabular VAE (TVAE)",
engine = cs_engine_info("torch", "nanoparquet", "codesplashr", "nanoparquet"),
n = values$n_real, summary = summary,
statistics = list(
list(key = "n_rows", label = "Synthetic rows", value = values$n_rows, format = "integer"),
list(key = "fidelity_ks_mean", label = "Mean KS distance", value = values$fidelity_ks_mean),
list(key = "fidelity_tv_mean", label = "Mean TV distance", value = values$fidelity_tv_mean),
list(key = "exact_matches", label = "Rows copied from the data", value = values$exact_matches, format = "integer")),
tables = c(list(sm$table), extra_tables),
values = values, charts = c(sm$charts, extra_charts), assumptions = assumptions, warnings = warnings,
artifacts = list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
list(key = "split", path = split, format = "parquet", title = "Training and holdout rows"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet", title = "Training history")),
model = list(kind = "generator", columns = I(COLUMNS), params = list(
n_rows = NULL,
hidden_layers = c(32, 32),
latent_dim = 8,
epochs = 30,
batch_size = 100,
learning_rate = 0.001,
beta = 1,
n_modes = 5,
missing = "keep_rate",
holdout = 0.2,
dp_epsilon = NULL,
dp_noise_multiplier = NULL,
dp_max_grad_norm = 1,
dp_delta = NULL,
dp_sampling = "poisson",
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
))
))
320 synthetic rows over 8 columns from 320 training rows with a tabular variational autoencoder. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.107 and categories by a mean total variation of 0.053.
- Synthetic rows
- 320
- Mean KS distance
- 0.1072
- Mean TV distance
- 0.0533
- Rows copied from the data
- 0
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Enough rows for a neural generator — 293 complete training rows — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees.
- Training stayed finite — The loss over the last 10% of epochs averaged 13 (reconstruction 10.9, KL 2.09).
- No synthetic row copies a training row — 0 synthetic rows are identical to a training row; the scorecard's distance to closest record checks near-copies.
- Synthetic columns match the data — Distance from the training rows: numeric columns 0.107 (mean Kolmogorov–Smirnov distance); categories 0.053 (mean total variation) — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 45.01 ± 13.8 | 0.0781 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 2.614e+04 ± 1.46e+04 | 0.1518 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 12.24 ± 9.7 | 0.1250 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 38.4% | 0.0125 | total variation |
| region | categorical | south 30.4% | south 23.0% | 0.1224 | total variation |
| churned | boolean | false 76.9% | false 74.4% | 0.0250 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2021-04-05 ± 684 days | 0.1375 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.212 ± 1.96 | 0.0438 | Kolmogorov–Smirnov D |
Modes per numeric column (mode-specific normalization)
| Column | Mixture modes |
|---|---|
| age | 5 |
| annual income | 5 |
| tenure_months | 5 |
| signup | 5 |
| visits | 5 |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — tabular VAE (TVAE)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.tvae 1.0.1 · spec c592bbd6d043a651
# Dataset: g1_customers (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.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import tvae # twin of codesplashr::cs_synth_tvae (clean-room TVAE; no CTGAN/SDV code)
# %% Data
COLUMNS = ["age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits"]
KINDS = {
"age": "numeric",
"annual income": "numeric",
"tenure_months": "numeric",
"plan": "categorical",
"region": "categorical",
"churned": "boolean",
"signup": "temporal",
"visits": "numeric",
}
LEVELS = {
"plan": ["basic", "plus", "premium"],
"region": ["east", "north", "south", "west"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
for c in cols:
if c.kind == "numeric":
check_finite(c.values, c.name) # infinite values stop the run (registry/errors.yaml)
rng = Rng(SEED) # shared stream: the same holdout and the same synthetic rows in Python and R
train_rows, holdout_rows = sy.split_holdout(n_input, 0.2, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = None or len(train_rows)
warnings = []
fit_values = {}
extra_tables = []
extra_charts = []
assumptions = []
model_note = ""
if len(holdout_rows):
warnings.append(f"{len(holdout_rows):,} of {n_input:,} rows ({len(holdout_rows) / n_input:.0%}) were held out of training so privacy and utility can be checked against rows the generator never saw.")
for c in train:
share = float(np.mean(c.missing()))
if share == 1.0:
cs.cs_error("CS_E_ALL_MISSING", column=c.name) # no values in the training rows
n_complete = len(sy.complete_rows(train))
assumptions.append({
"key": "enough_rows",
"label": "Enough rows for a neural generator",
"status": "pass" if n_complete >= 1000 else "warn",
"detail": f"{n_complete:,} complete training rows"
+ ("." if n_complete >= 1000 else " — neural generators have many weights to learn and can memorize small tables; compare with the copula or sequential trees."),
})
# %% Generate
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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/synth.tvae/customers_all/out-python",
)
# Tabular VAE on rows encoded by mode-specific normalization (numbers → [α, mode one-hot], categories one-hot):
# encoder → N(μ, σ²) code of 8 dimensions → decoder; KL weight β = 1.
HIDDEN = [int(u) for u in [32, 32]]
synth, facts, hist = tvae.fit_tvae(
train, N_OUT, rng, HIDDEN,
latent_dim=8,
epochs=30,
batch_size=100,
lr=0.001,
beta=1,
n_modes=5,
seed=SEED,
)
history = pd.DataFrame(hist)
last = max(1, len(hist) // 10) # the last 10% of epochs
fit_values["batch_size"] = facts["batch_size"]
fit_values["latent_dim"] = facts["latent_dim"]
fit_values["final_loss"] = float(np.mean([h["loss"] for h in hist[-last:]]))
fit_values["reconstruction"] = float(np.mean([h["reconstruction"] for h in hist[-last:]]))
fit_values["kl"] = float(np.mean([h["kl"] for h in hist[-last:]]))
if not np.isnan(facts["sigma_mean"]):
fit_values["sigma_mean"] = facts["sigma_mean"]
for c, k in zip(COLUMNS, facts["modes"]):
if k is not None:
fit_values[f"modes[{c}]"] = int(k)
model_note = " with a tabular variational autoencoder"
ep = history["epoch"].tolist()
extra_charts.append(cs.chart("training", "training-components", "TVAE loss by epoch", {
"x": cs.col("Epoch", ep * 3, "numeric"),
"value": cs.col("Loss", history["loss"].tolist() + history["reconstruction"].tolist() + history["kl"].tolist(), "numeric"),
"component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL divergence"] * len(ep), "categorical",
levels=["total", "reconstruction", "KL divergence"]),
}, note="Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal."))
finite = bool(np.all(np.isfinite(history[["loss", "reconstruction", "kl"]].to_numpy())))
assumptions.append({
"key": "training_stable",
"label": "Training stayed finite",
"status": "pass" if finite else "fail",
"detail": f"The loss over the last 10% of epochs averaged {fit_values['final_loss']:.3g} (reconstruction {fit_values['reconstruction']:.3g}, KL {fit_values['kl']:.3g})." if finite else "A loss became infinite or undefined; lower the learning rate.",
})
mode_rows = [{"column": c, "modes": int(k)} for c, k in zip(COLUMNS, facts["modes"]) if k is not None]
if mode_rows:
extra_tables.append({
"key": "modes",
"title": "Modes per numeric column (mode-specific normalization)",
"columns": [{"key": "column", "label": "Column", "type": "string"}, {"key": "modes", "label": "Mixture modes", "type": "integer"}],
"rows": mode_rows,
})
sy.add_missing(synth, train, rng, "keep_rate") # each column's missing share, at random
# %% Write and compare
out = out_dir("target/academy-parity/run-8142/synth.tvae/customers_all/out-python")
path = sy.write(os.path.join(out, "synthetic.parquet"), synth)
split = sy.write_split(os.path.join(out, "split.parquet"), n_input, train_rows, holdout_rows)
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
assumptions.append({
"key": "no_copies",
"label": "No synthetic row copies a training row",
"status": "pass" if values["exact_matches"] == 0 else "warn",
"detail": f"{values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row; the scorecard's distance to closest record checks near-copies.",
})
# Fidelity (Stage 12.10): judged on the mean column distances, the scorecard's column fidelity (good at ≥ 0.9 = 1 − 0.1).
fid_parts = []
if not np.isnan(values["fidelity_ks_mean"]):
fid_parts.append((values["fidelity_ks_mean"], f"numeric columns {values['fidelity_ks_mean']:.3f} (mean Kolmogorov–Smirnov distance)"))
if not np.isnan(values["fidelity_tv_mean"]):
fid_parts.append((values["fidelity_tv_mean"], f"categories {values['fidelity_tv_mean']:.3f} (mean total variation)"))
fid_worst = max((d for d, _ in fid_parts), default=None)
assumptions.append({
"key": "fidelity",
"label": "Synthetic columns match the data",
"status": "info" if fid_worst is None else ("pass" if fid_worst <= 0.1 else "warn"),
"detail": "No column could be compared with the data." if fid_worst is None else
"Distance from the training rows: " + "; ".join(t for _, t in fid_parts)
+ (" — at most 0.10, which the Synthetic studio's scorecard rates as good column fidelity." if fid_worst <= 0.1 else
" — above 0.10, so some columns' distributions differ visibly from the data; the scorecard shows which columns and pairs."),
})
summary = (
f"{values['n_rows']:,} synthetic rows over {len(COLUMNS)} column{'s' if len(COLUMNS) != 1 else ''} from "
f"{len(train_rows):,} training rows{model_note}."
)
if not np.isnan(values["fidelity_ks_mean"]):
summary += f" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of {values['fidelity_ks_mean']:.3f}"
summary += f" and categories by a mean total variation of {values['fidelity_tv_mean']:.3f}." if not np.isnan(values["fidelity_tv_mean"]) else "."
elif not np.isnan(values["fidelity_tv_mean"]):
summary += f" Categories differ from the data by a mean total variation of {values['fidelity_tv_mean']:.3f}."
if values["exact_matches"]:
summary += f" {values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row."
cs.publish({
"title": "Synthetic data — tabular VAE (TVAE)",
"engine": cs.engine_info("torch", "pyarrow", "codesplash", "numpy", "pyarrow"),
"n": values["n_real"],
"summary": summary,
"statistics": [
{"key": "n_rows", "label": "Synthetic rows", "value": values["n_rows"], "format": "integer"},
{"key": "fidelity_ks_mean", "label": "Mean KS distance", "value": values.get("fidelity_ks_mean")},
{"key": "fidelity_tv_mean", "label": "Mean TV distance", "value": values.get("fidelity_tv_mean")},
{"key": "exact_matches", "label": "Rows copied from the data", "value": values["exact_matches"], "format": "integer"},
],
"tables": [table, *extra_tables],
"values": values,
"charts": charts + extra_charts,
"assumptions": assumptions,
"warnings": warnings,
"artifacts": [
{"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
{"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet", "title": "Training history"},
],
"model": {"kind": "generator", "columns": COLUMNS, "params": {
"n_rows": None,
"hidden_layers": [32, 32],
"latent_dim": 8,
"epochs": 30,
"batch_size": 100,
"learning_rate": 0.001,
"beta": 1,
"n_modes": 5,
"missing": "keep_rate",
"holdout": 0.2,
"dp_epsilon": None,
"dp_noise_multiplier": None,
"dp_max_grad_norm": 1,
"dp_delta": None,
"dp_sampling": "poisson",
"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,
}},
})
Its mean KS distance on the customer table is 0.107, and 0 generated rows copy a real one exactly.
Check: the workflow
CheckpointCheck yourself
Why does the workflow use the same bank of code draws to validate every epoch, then fresh draws for the test score?
Show the answer
Answer: a
With the same draws, two epochs differ only by the model. Choosing the best epoch against them can still fit their noise, so the final estimate uses new, larger banks.
Check yourself
A VAE's held-out rebuild error is low, but its prior samples land between the real clusters. What do you conclude?
Show the answer
Answer: b
Rebuilds test codes the encoder made. Samples test codes drawn from the prior. A round prior over clumpy codes puts draws in the gaps.
Check yourself
How does the posterior-mean rebuild error differ from the rebuild term of the ELBO?
Show the answer
Answer: a
Setting the noise to zero and decoding the mean usually rebuilds better than random codes do. Report them as separate quantities.
Check yourself
A run used a KL weight of 0.5. What must the report say about its loss?
Show the answer
Answer: b
Only a KL weight of 1 gives the ELBO. Any other weight changes the objective, so it can't be compared as a likelihood bound.
Check yourself
Switching from a standard normal prior to a Gaussian mixture prior lowered the samples' KS distance on one seed. What's the next step?
Show the answer
Answer: b
One run on one seed is a hint. A change is kept when it holds up across seeds under the evaluation you fixed in advance.
Recap
Recap- Split first, fix settings, select on validation rows with fixed draws, and score once on locked test rows.
- Report the negative ELBO, its parts, posterior-mean error and samples' fit as separate numbers.
- Good rebuilds don't mean good samples: compare prior samples with real rows.
- Change one thing, such as the prior, and score it the same way.
Concepts in this lesson