Skip to content

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.

Advanced ~14 min9 steps

What runs in CodeSplash

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

Read first

01

The plan before the fit

Read

The reference's VAE workflow fixes its decisions before training:

  1. 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.
  2. Fix the settings: latent size, widths, observation variance, KL weight, epochs. Each changes the model, so write them down.
  3. 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.
  4. 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.

02

Several numbers, not one

Read

A 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.

03

Rebuilds versus samples

Explore
Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 43 values compared
R

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

Plots

Latent means against the N(0, I) priorDoes a variational autoencoder's latent space fill its N(0, I) prior, or leave holes and collapse?
View data
speciesLatent 1 (μ)Latent 2 (μ)
setosa1.1760.3987
setosa1.151−0.3919
setosa1.291−0.1713
setosa1.287−0.3178
setosa1.2160.4858
setosa0.99571.062
setosa1.3260.0476
setosa1.1960.2171
setosa1.299−0.6013
setosa1.195−0.2248
setosa1.0620.8139
setosa1.2610.1357
setosa1.212−0.3913
setosa1.401−0.4933
setosa0.95431.329
setosa0.87561.628
setosa1.0381.057
setosa1.1570.3926
setosa0.91391.076
setosa1.1470.7914
setosa1.0120.3939
setosa1.1320.6660
setosa1.3760.2936
setosa1.0530.0777
setosa1.2320.1401
setosa1.090−0.3562
setosa1.1450.2015
setosa1.1290.4465
setosa1.1260.2994
setosa1.267−0.1591
setosa1.205−0.2643
setosa0.98700.3600
setosa1.1131.155
setosa1.0051.393
setosa1.175−0.2433
setosa1.187−0.0832
setosa1.0250.5760
setosa1.2680.4352
setosa1.340−0.4887
setosa1.1570.2596
setosa1.2030.3455
setosa0.9491−1.270
setosa1.387−0.2521
setosa1.1090.3276
setosa1.0840.7959
setosa1.170−0.4365
setosa1.1550.7866
setosa1.318−0.1957
setosa1.0990.7653
setosa1.1910.0722
versicolor−0.78220.5444
versicolor−0.54930.3661
versicolor−0.84500.3862
versicolor−0.0362−1.121
versicolor−0.6487−0.1629
versicolor−0.1764−0.4722
versicolor−0.57480.4935
versicolor0.4366−1.172
versicolor−0.59920.0041
versicolor0.1325−0.8017

First 60 of 150 rows.

Per-row loss (reconstruction + β·KL) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyPer-row loss
false1.315
false1.521
false1.439
false1.607
false1.447
false2.103
false1.513
false1.256
false2.173
false1.447
false1.670
false1.346
false1.629
false2.195
false3.030
true4.902
false2.189
false1.291
false2.056
false1.816
false1.316
false1.577
false1.776
false1.197
false1.390
false1.463
false1.235
false1.315
false1.268
false1.437
false1.440
false1.268
false3.056
true3.605
false1.389
false1.322
false1.514
false1.527
false1.994
false1.245
false1.321
true4.088
false1.772
false1.399
false1.808
false1.546
false1.840
false1.524
false1.625
false1.251
false1.800
false1.094
false1.385
false1.944
false0.9980
false0.8023
false1.252
false2.226
false1.176
false1.287

First 60 of 150 rows.

Training loss and its parts by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total5.2891
total4.9312
total4.9073
total4.5974
total4.3595
total4.2546
total4.0137
total4.1768
total3.9259
total3.80310
total3.69511
total3.66612
total3.49813
total3.50814
total3.28815
total3.40516
total3.28917
total3.09918
total3.07719
total2.74120
total2.69521
total2.85722
total2.83123
total2.77724
total2.93625
total3.03126
total2.90427
total2.75628
total2.76229
total2.67830
total2.71831
total2.73032
total2.48533
total2.56434
total2.60735
total2.52736
total2.67437
total2.59738
total2.68039
total2.47440
total2.68541
total2.62342
total2.75043
total2.71244
total2.49745
total2.56446
total2.44647
total2.57748
total2.51649
total2.45250
total2.50751
total2.41052
total2.43353
total2.33254
total2.36955
total2.49656
total2.52057
total2.47458
total2.65659
total2.40560

First 60 of 600 rows.

sepal_length: data vs rows generated from the priorDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2222real4.360
0.0556real4.480
0.2222real4.600
0.1111real4.720
0.2778real4.840
0.8889real4.960
0.5000real5.080
0.2222real5.200
0.0556real5.320
0.3333real5.440
0.7222real5.560
0.4444real5.680
0.3889real5.800
0.1667real5.920
0.6667real6.040
0.2222real6.160
0.5000real6.280
0.3889real6.400
0.2778real6.520
0.1111real6.640
0.6111real6.760
0.2222real6.880
0.0556real7
0.0556real7.120
0.2222real7.240
0.0556real7.360
0real7.480
0.0556real7.600
0.2222real7.720
0.0556real7.840
0synthetic4.360
0.0556synthetic4.480
0.1111synthetic4.600
0.2778synthetic4.720
0.4444synthetic4.840
0.3333synthetic4.960
0.3889synthetic5.080
0.3333synthetic5.200
0.6111synthetic5.320
0.2778synthetic5.440
0.5000synthetic5.560
0.5000synthetic5.680
0.6111synthetic5.800
0.3889synthetic5.920
0.3333synthetic6.040
0.4444synthetic6.160
0.6111synthetic6.280
0.5000synthetic6.400
0.4444synthetic6.520
0.4444synthetic6.640
0.4444synthetic6.760
0.1667synthetic6.880
0.1111synthetic7
0synthetic7.120
0synthetic7.240
0synthetic7.360
0synthetic7.480
0synthetic7.600
0synthetic7.720
0synthetic7.840

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
11325.8707.9003.8006.4002
21185.5507.7003.8006.7002.200
3164.9025.7004.4001.5000.4000
41194.3427.7002.6006.9002.300
5424.0884.5002.3001.3000.3000
6613.918523.5001
7343.6055.5004.2001.4000.2000
81103.5307.2003.6006.1002.500
91233.2797.7002.8006.7002
10333.0565.2004.1001.5000.1000
11153.0305.80041.2000.2000
121362.7547.70036.1002.300
13632.68862.20041
141062.6617.60036.6002.100
15692.6166.2002.2004.5001.500
161202.55562.20051.500
171072.4914.9002.5004.5001.700
18942.42652.3003.3001
191372.3336.3003.4005.6002.400
201012.3246.3003.30062.500

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.86340.8815yes
20.24680.3660yes
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
))
Python

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

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
11325.8707.9003.8006.4002
21185.5507.7003.8006.7002.200
3164.9025.7004.4001.5000.4000
41194.3427.7002.6006.9002.300
5424.0884.5002.3001.3000.3000
6613.918523.5001
7343.6055.5004.2001.4000.2000
81103.5307.2003.6006.1002.500
91233.2797.7002.8006.7002
10333.0565.2004.1001.5000.1000
11153.0305.80041.2000.2000
121362.7547.70036.1002.300
13632.68862.20041
141062.6617.60036.6002.100
15692.6166.2002.2004.5001.500
161202.55562.20051.500
171072.4914.9002.5004.5001.700
18942.42652.3003.3001
191372.3336.3003.4005.6002.400
201012.3246.3003.30062.500

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.86340.8815yes
20.24680.3660yes
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.

04

The failure the reference kept

Read

The 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?

How sure?
8.0

1 is the ELBO; above 1 is a β-VAE.

1.00

How noisy the decoder says the data are.

2
600
0.050
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

05

Change one thing: the prior

Explore
Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 49 values compared
R

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

Plots

Latent means by mixture component (component means marked)Which rows group together, and how well separated are the groups?
View data
Component meanComponentLatent 1 (μ)Latent 2 (μ)
false21.2091.167
false21.2550.8371
false21.2980.9618
false21.2960.8686
false21.2101.208
false21.0851.355
false21.2671.047
false21.2201.090
false21.3470.7337
false21.2620.9096
false21.1461.289
false21.2331.057
false21.2920.8480
false21.4020.8266
false21.1011.483
false21.0181.590
false21.1261.395
false21.1981.159
false21.0691.334
false21.1561.304
false21.1351.100
false21.1581.250
false21.2821.197
false21.1280.9619
false21.1981.024
false21.2040.8165
false21.1811.057
false21.1861.166
false21.2031.120
false21.2630.9292
false21.2500.8752
false21.1251.092
false21.1201.448
false21.0871.519
false21.2460.8946
false21.2641.003
false21.1641.213
false21.2271.200
false21.3550.8076
false21.2061.099
false21.2211.160
false21.1620.1799
false21.3350.9257
false21.1451.092
false21.1011.259
false21.2560.8101
false21.1541.297
false21.3000.9399
false21.1571.280
false21.2371.042
false1−0.6808−0.3430
false1−0.5544−0.3459
false1−0.6960−0.4233
false1−0.1850−0.7979
false1−0.5467−0.5576
false1−0.3479−0.5572
false1−0.5927−0.3249
false10.1240−0.6021
false1−0.5526−0.4878
false1−0.1628−0.5936

First 60 of 152 rows.

Per-row loss (reconstruction + β·KL) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyPer-row loss
false1.195
false1.935
false1.521
false1.780
false1.249
false2.179
false1.369
false1.178
false2.656
false1.678
false1.598
false1.214
false2.005
false2.638
false3.121
true5.327
false2.163
false1.194
false2.282
false1.636
false1.469
false1.443
false1.576
false1.436
false1.261
false1.945
false1.216
false1.236
false1.256
false1.484
false1.651
false1.493
false2.882
true3.634
false1.634
false1.462
false1.554
false1.298
false2.342
false1.201
false1.189
true5.689
false1.851
false1.396
false1.748
false1.935
false1.638
false1.582
false1.506
false1.267
false1.758
false1.285
false1.243
false1.979
false0.8198
false1.066
false1.483
false2.923
false1.095
false1.755

First 60 of 150 rows.

Training loss and its parts by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total5.0131
total5.4022
total4.8613
total4.5114
total4.3975
total4.0706
total4.0207
total3.6158
total3.4679
total3.24810
total3.10611
total3.23412
total3.25813
total2.77214
total3.22715
total2.83216
total2.63717
total2.43018
total2.74719
total2.59020
total2.37921
total2.44222
total2.49623
total2.36424
total2.35825
total2.26226
total2.24627
total2.31728
total2.33029
total2.22730
total2.25831
total2.16732
total2.30233
total2.15334
total2.15535
total2.14036
total2.25537
total2.15438
total2.16139
total2.08440
total2.21441
total2.13642
total2.09543
total2.12944
total2.20945
total2.14746
total2.05147
total2.06948
total2.16449
total2.13850
total2.23351
total2.22752
total2.19453
total2.04254
total2.14755
total2.23856
total2.09957
total2.09858
total2.00259
total2.25060

First 60 of 600 rows.

sepal_length: data vs rows generated from the priorDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesepal_length
0.2222real4.360
0.0556real4.480
0.2222real4.600
0.1111real4.720
0.2778real4.840
0.8889real4.960
0.5000real5.080
0.2222real5.200
0.0556real5.320
0.3333real5.440
0.7222real5.560
0.4444real5.680
0.3889real5.800
0.1667real5.920
0.6667real6.040
0.2222real6.160
0.5000real6.280
0.3889real6.400
0.2778real6.520
0.1111real6.640
0.6111real6.760
0.2222real6.880
0.0556real7
0.0556real7.120
0.2222real7.240
0.0556real7.360
0real7.480
0.0556real7.600
0.2222real7.720
0.0556real7.840
0synthetic4.360
0synthetic4.480
0.2222synthetic4.600
0.3333synthetic4.720
0.3889synthetic4.840
0.9444synthetic4.960
0.6111synthetic5.080
0.3889synthetic5.200
0.1111synthetic5.320
0.0556synthetic5.440
0.1111synthetic5.560
0.1667synthetic5.680
0.6111synthetic5.800
0.3889synthetic5.920
0.4444synthetic6.040
0.6667synthetic6.160
0.5556synthetic6.280
0.4444synthetic6.400
0.3889synthetic6.520
0.5000synthetic6.640
0.5556synthetic6.760
0.2778synthetic6.880
0.1667synthetic7
0synthetic7.120
0synthetic7.240
0synthetic7.360
0synthetic7.480
0synthetic7.600
0synthetic7.720
0synthetic7.840

Assumptions

  • Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
1425.6894.5002.3001.3000.3000
21325.4267.9003.8006.4002
3165.3275.7004.4001.5000.4000
41185.1227.7003.8006.7002.200
51194.3307.7002.6006.9002.300
6613.958523.5001
7343.6345.5004.2001.4000.2000
81233.2447.7002.8006.7002
91103.2247.2003.6006.1002.500
10153.1215.80041.2000.2000
11582.9234.9002.4003.3001
12942.89252.3003.3001
13332.8825.2004.1001.5000.1000
141072.7154.9002.5004.5001.700
151362.6927.70036.1002.300
1692.6564.4002.9001.4000.2000
17142.6384.30031.1000.1000
18992.6345.1002.50031.100
19632.59162.20041
201062.5817.60036.6002.100

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.32520.7428yes
20.09850.6258yes

Mixture prior components

ComponentRowsPrior weightMean 1Mean 2
11000.4957−0.5351−0.5602
2500.33731.1761.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
))
Python

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

RankRowPer-row losssepal_lengthsepal_widthpetal_lengthpetal_width
1425.6894.5002.3001.3000.3000
21325.4267.9003.8006.4002
3165.3275.7004.4001.5000.4000
41185.1227.7003.8006.7002.200
51194.3307.7002.6006.9002.300
6613.958523.5001
7343.6345.5004.2001.4000.2000
81233.2447.7002.8006.7002
91103.2247.2003.6006.1002.500
10153.1215.80041.2000.2000
11582.9234.9002.4003.3001
12942.89252.3003.3001
13332.8825.2004.1001.5000.1000
141072.7154.9002.5004.5001.700
151362.6927.70036.1002.300
1692.6564.4002.9001.4000.2000
17142.6384.30031.1000.1000
18992.6345.1002.50031.100
19632.59162.20041
201062.5817.60036.6002.100

Latent dimensions

DimensionMean KL (nats)Variance of μActive
10.32520.7428yes
20.09850.6258yes

Mixture prior components

ComponentRowsPrior weightMean 1Mean 2
11000.4957−0.5351−0.5602
2500.33731.1761.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.

06

Mixed columns and a softer KL

Explore
Variational autoencoder (latent map, anomalies and generated rows)Recorded · Python and R agreeRecorded 2026-11-25 · 45 values compared
R

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

Plots

Latent means against the N(0, I) priorDoes a variational autoencoder's latent space fill its N(0, I) prior, or leave holes and collapse?
View data
speciesLatent 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.96570.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.74180.1618
Adelie−1.238−0.2067
Adelie−0.7818−0.6975
Adelie−0.94710.6034
Adelie−1.081−0.6060
Adelie−0.85880.4990
Adelie−1.026−0.2102
Adelie−0.69440.0398
Adelie−1.046−0.8257
Adelie−1.096−0.6613
Adelie−0.98260.8071
Adelie−1.2550.1502
Adelie−0.6624−0.5017
Adelie−1.1210.1228
Adelie−0.6784−0.2780
Adelie−1.167−0.0192
Adelie−0.6106−0.1430
Adelie−0.98500.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.

Per-row loss (reconstruction + β·KL) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyPer-row loss
false2.083
false1.841
false2.056
false2.141
false2.384
false2.179
false2.052
false2.262
false2.475
false2.257
false2.158
false2.513
false2.304
false2.547
true3.493
false1.778
false2.255
false2.638
false2.064
true3.217
true3.033
false2.707
false2.562
false2.092
false2.861
false2.496
false2.230
false1.934
true3.485
false2.412
false1.919
false2.775
false1.171
false1.685
false1.582
false2.456
false1.900
false1.928
false2.230
false2.672
false1.759
false1.386
false1.857
false1.386
false1.625
false2.020
false1.744
false2.778
false1.578
false2.409
false1.705
false1.750
false1.894
false1.680
false2.391
false1.637
false1.644
false1.526
false2.440
false1.932

First 60 of 344 rows.

Training loss and its parts by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total16.9401
total9.5032
total7.4613
total5.7164
total5.1155
total4.7206
total4.2887
total4.0998
total3.8679
total3.81810
total3.74511
total3.70112
total3.72013
total3.52714
total3.51315
total3.40816
total3.39717
total3.33218
total3.23519
total3.16820
total3.11821
total3.14022
total2.92823
total2.97524
total2.92725
total2.91026
total2.83727
total2.86528
total2.79529
total2.74030
total2.69131
total2.68432
total2.65833
total2.64334
total2.66835
total2.66336
total2.56137
total2.58238
total2.53739
total2.56240
total2.58941
total2.52242
total2.53543
total2.49144
total2.46145
total2.50546
total2.60747
total2.57148
total2.50549
total2.46350
total2.51651
total2.47352
total2.48853
total2.45254
total2.42955
total2.48356
total2.45557
total2.48858
total2.50559
total2.53960

First 60 of 240 rows.

bill_len: data vs rows generated from the priorDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcebill_len
0.0032real32.558
0.0064real33.475
0.0191real34.392
0.0351real35.308
0.0510real36.225
0.0415real37.142
0.0670real38.058
0.0542real38.975
0.0606real39.892
0.0670real40.808
0.0415real41.725
0.0447real42.642
0.0447real43.558
0.0255real44.475
0.0861real45.392
0.0797real46.308
0.0574real47.225
0.0383real48.142
0.0606real49.058
0.0670real49.975
0.0670real50.892
0.0351real51.808
0.0096real52.725
0.0064real53.642
0.0064real54.558
0.0096real55.475
0real56.392
0real57.308
0.0032real58.225
0.0032real59.142
0.0036synthetic32.558
0synthetic33.475
0.0073synthetic34.392
0.0109synthetic35.308
0.0255synthetic36.225
0.0291synthetic37.142
0.0582synthetic38.058
0.0764synthetic38.975
0.1018synthetic39.892
0.0764synthetic40.808
0.0291synthetic41.725
0.0655synthetic42.642
0.0582synthetic43.558
0.0691synthetic44.475
0.0909synthetic45.392
0.0873synthetic46.308
0.0436synthetic47.225
0.0800synthetic48.142
0.0364synthetic49.058
0.0473synthetic49.975
0.0327synthetic50.892
0.0255synthetic51.808
0.0036synthetic52.725
0.0073synthetic53.642
0.0036synthetic54.558
0.0145synthetic55.475
0synthetic56.392
0.0036synthetic57.308
0synthetic58.225
0.0036synthetic59.142

Assumptions

  • Latent dimensions in use — 3 of 3 latent dimensions vary across rows (variance of μ > 0.01).

Rows the model finds least typical

RankRowPer-row lossislandbill_lenbill_depflipper_lenbody_masssex
12944.851Dream5817.8001813,700female
21863.874Biscoe59.600172306,050male
31153.707Biscoe39.60020.7001913,900female
4153.493Torgersen34.60021.1001984,400male
5293.485Biscoe37.90018.6001723,150female
61433.454Dream32.10015.5001883,050female
73143.399Dream5220.7002104,800male
8203.217Torgersen4621.5001944,200male
9993.171Dream33.10016.1001782,900female
10213.033Biscoe37.80018.3001743,400female
11252.861Biscoe38.80017.2001803,800male
123402.858Dream55.80019.8002074,000male
131232.851Torgersen40.200171763,450female
14482.778Dream37.50018.9001792,975—
15322.775Dream37.20018.1001783,900male
163252.769Dream51.50018.7001873,250male
173082.753Dream54.20020.8002014,300male
18622.726Biscoe41.30021.1001954,400male
19222.707Biscoe37.70018.7001803,600male
203152.700Dream46.90016.6001922,700female

Latent dimensions

DimensionMean KL (nats)Variance of μActive
11.0490.8742yes
20.41990.4692yes
30.77800.7777yes
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
))
Python

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

RankRowPer-row lossislandbill_lenbill_depflipper_lenbody_masssex
12944.851Dream5817.8001813,700female
21863.874Biscoe59.600172306,050male
31153.707Biscoe39.60020.7001913,900female
4153.493Torgersen34.60021.1001984,400male
5293.485Biscoe37.90018.6001723,150female
61433.454Dream32.10015.5001883,050female
73143.399Dream5220.7002104,800male
8203.217Torgersen4621.5001944,200male
9993.171Dream33.10016.1001782,900female
10213.033Biscoe37.80018.3001743,400female
11252.861Biscoe38.80017.2001803,800male
123402.858Dream55.80019.8002074,000male
131232.851Torgersen40.200171763,450female
14482.778Dream37.50018.9001792,975—
15322.775Dream37.20018.1001783,900male
163252.769Dream51.50018.7001873,250male
173082.753Dream54.20020.8002014,300male
18622.726Biscoe41.30021.1001954,400male
19222.707Biscoe37.70018.7001803,600male
203152.700Dream46.90016.6001922,700female

Latent dimensions

DimensionMean KL (nats)Variance of μActive
11.0490.8742yes
20.41990.4692yes
30.77800.7777yes
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.

07

For synthetic tables

In the app

When 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.

Synthetic data — tabular VAE (TVAE)Recorded · Python and R agreeRecorded 2026-11-25 · 57 values compared · largest relative difference 3.6e-15
R

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

age: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceage
0.0230real18.950
0.0016real20.850
0.0049real22.750
0.0148real24.650
0.0148real26.550
0.0181real28.450
0.0197real30.350
0.0296real32.250
0.0362real34.150
0.0115real36.050
0.0362real37.950
0.0313real39.850
0.0296real41.750
0.0280real43.650
0.0280real45.550
0.0181real47.450
0.0164real49.350
0.0197real51.250
0.0362real53.150
0.0148real55.050
0.0164real56.950
0.0181real58.850
0.0082real60.750
0.0164real62.650
0.0049real64.550
0.0115real66.450
0.0066real68.350
0.0049real70.250
0.0016real72.150
0.0049real74.050
0.0214synthetic18.950
0.0016synthetic20.850
0.0148synthetic22.750
0.0033synthetic24.650
0.0164synthetic26.550
0.0066synthetic28.450
0.0132synthetic30.350
0.0362synthetic32.250
0.0230synthetic34.150
0.0181synthetic36.050
0.0197synthetic37.950
0.0329synthetic39.850
0.0230synthetic41.750
0.0345synthetic43.650
0.0313synthetic45.550
0.0181synthetic47.450
0.0164synthetic49.350
0.0230synthetic51.250
0.0378synthetic53.150
0.0197synthetic55.050
0.0280synthetic56.950
0.0164synthetic58.850
0.0148synthetic60.750
0.0099synthetic62.650
0.0016synthetic64.550
0.0099synthetic66.450
0.0033synthetic68.350
0.0099synthetic70.250
0.0016synthetic72.150
0.0197synthetic74.050
annual income: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceannual income
3.010e-6real6851.93
1.605e-5real10141.74
2.107e-5real13431.55
2.408e-5real16721.36
3.511e-5real20011.17
4.113e-5real23300.98
2.809e-5real26590.79
2.408e-5real29880.60
2.508e-5real33170.41
1.605e-5real36460.22
1.605e-5real39750.03
1.505e-5real43039.84
1.003e-5real46329.65
5.016e-6real49619.46
6.019e-6real52909.27
4.013e-6real56199.07
4.013e-6real59488.88
4.013e-6real62778.69
1.003e-6real66068.50
1.003e-6real69358.31
1.003e-6real72648.12
0real75937.93
1.003e-6real79227.74
1.003e-6real82517.55
0real85807.36
0real89097.17
0real92386.98
0real95676.79
0real98966.60
1.003e-6real102256.41
1.104e-5synthetic6851.93
2.408e-5synthetic10141.74
2.207e-5synthetic13431.55
4.213e-5synthetic16721.36
4.113e-5synthetic20011.17
2.809e-5synthetic23300.98
3.010e-5synthetic26590.79
2.608e-5synthetic29880.60
2.207e-5synthetic33170.41
7.022e-6synthetic36460.22
1.204e-5synthetic39750.03
1.204e-5synthetic43039.84
5.016e-6synthetic46329.65
4.013e-6synthetic49619.46
2.006e-6synthetic52909.27
2.006e-6synthetic56199.07
2.006e-6synthetic59488.88
2.006e-6synthetic62778.69
2.006e-6synthetic66068.50
1.003e-6synthetic69358.31
1.003e-6synthetic72648.12
2.006e-6synthetic75937.93
0synthetic79227.74
1.003e-6synthetic82517.55
0synthetic85807.36
1.003e-6synthetic89097.17
0synthetic92386.98
0synthetic95676.79
0synthetic98966.60
1.003e-6synthetic102256.41
tenure_months: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcetenure_months
0.0938real0.7667
0.0224real2.300
0.0183real3.833
0.0306real5.367
0.0204real6.900
0.0265real8.433
0.0204real9.967
0.0530real11.500
0.0183real13.033
0.0510real14.567
0.0183real16.100
0.0367real17.633
0.0224real19.167
0.0448real20.700
0.0469real22.233
0.0082real23.767
0.0306real25.300
0.0061real26.833
0.0183real28.367
0.0041real29.900
0.0143real31.433
0.0061real32.967
0.0183real34.500
0.0020real36.033
0.0041real37.567
0real39.100
0.0061real40.633
0.0041real42.167
0.0020real43.700
0.0041real45.233
0.1223synthetic0.7667
0.0245synthetic2.300
0.0306synthetic3.833
0.0448synthetic5.367
0.0102synthetic6.900
0.0387synthetic8.433
0.0204synthetic9.967
0.0591synthetic11.500
0.0245synthetic13.033
0.0489synthetic14.567
0.0163synthetic16.100
0.0428synthetic17.633
0.0224synthetic19.167
0.0448synthetic20.700
0.0265synthetic22.233
0.0082synthetic23.767
0.0143synthetic25.300
0.0061synthetic26.833
0.0082synthetic28.367
0.0061synthetic29.900
0.0082synthetic31.433
0.0020synthetic32.967
0.0061synthetic34.500
0.0041synthetic36.033
0.0041synthetic37.567
0.0020synthetic39.100
0.0041synthetic40.633
0synthetic42.167
0.0020synthetic43.700
0synthetic45.233
signup: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesignup
0.0005real17582.23
0.0007real17654.70
0.0005real17727.17
0.0005real17799.63
0.0004real17872.10
0.0005real17944.57
0.0006real18017.03
0.0004real18089.50
0.0005real18161.97
0.0005real18234.43
0.0001real18306.90
0.0009real18379.37
0.0006real18451.83
0.0003real18524.30
0.0005real18596.77
0.0004real18669.23
0.0002real18741.70
0.0005real18814.17
0.0006real18886.63
0.0005real18959.10
0.0005real19031.57
0.0005real19104.03
0.0003real19176.50
0.0006real19248.97
0.0004real19321.43
0.0003real19393.90
0.0002real19466.37
0.0005real19538.83
0.0003real19611.30
0.0004real19683.77
0.0006synthetic17582.23
0.0004synthetic17654.70
0.0005synthetic17727.17
0.0002synthetic17799.63
0.0004synthetic17872.10
0.0006synthetic17944.57
0.0003synthetic18017.03
0.0004synthetic18089.50
0.0004synthetic18161.97
0.0004synthetic18234.43
0.0005synthetic18306.90
0.0004synthetic18379.37
0.0004synthetic18451.83
0.0003synthetic18524.30
0.0005synthetic18596.77
0.0003synthetic18669.23
0.0004synthetic18741.70
0.0003synthetic18814.17
0.0003synthetic18886.63
0.0003synthetic18959.10
0.0004synthetic19031.57
0.0008synthetic19104.03
0.0003synthetic19176.50
0.0005synthetic19248.97
0.0003synthetic19321.43
0.0002synthetic19393.90
0.0004synthetic19466.37
0.0007synthetic19538.83
0.0012synthetic19611.30
0.0009synthetic19683.77
plan: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
planShareSource
basic0.3563real
plus0.3969real
premium0.2469real
basic0.3594synthetic
plus0.3844synthetic
premium0.2562synthetic
region: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
regionShareSource
east0.2848real
north0.2718real
south0.3042real
west0.1392real
east0.3738synthetic
north0.2236synthetic
south0.2300synthetic
west0.1725synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.7438synthetic
true0.2562synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
ageage0
annual incomeage0.3306
tenure_monthsage0.8144
signupage0.0037
visitsage0.0790
ageannual income0.3306
annual incomeannual income0
tenure_monthsannual income0.0613
signupannual income−0.1297
visitsannual income0.2451
agetenure_months0.8144
annual incometenure_months0.0613
tenure_monthstenure_months0
signuptenure_months−0.1346
visitstenure_months0.0903
agesignup0.0037
annual incomesignup−0.1297
tenure_monthssignup−0.1346
signupsignup0
visitssignup−0.0712
agevisits0.0790
annual incomevisits0.2451
tenure_monthsvisits0.0903
signupvisits−0.0712
visitsvisits0
TVAE loss by epochIs the network still learning, and which part of its loss moves?

Reconstruction measures how well rows are rebuilt from their codes; the KL divergence keeps the codes close to a standard normal.

View data
PartLossEpoch
total104.751
total86.9782
total67.3833
total54.8944
total49.2775
total44.5156
total37.9807
total32.8258
total29.2259
total26.19410
total24.81611
total22.42712
total20.76713
total19.01114
total18.16115
total18.25416
total16.77817
total16.35918
total16.37119
total14.86720
total15.33421
total14.41622
total14.43223
total13.68324
total13.56325
total13.81026
total13.22527
total13.09628
total13.27029
total12.57330
reconstruction103.231
reconstruction85.5582
reconstruction66.0013
reconstruction53.5064
reconstruction47.8585
reconstruction43.0496
reconstruction36.4597
reconstruction31.2298
reconstruction27.5469
reconstruction24.42910
reconstruction22.97811
reconstruction20.51812
reconstruction18.78413
reconstruction16.95914
reconstruction16.05215
reconstruction16.09616
reconstruction14.58417
reconstruction14.13418
reconstruction14.12719
reconstruction12.60820
reconstruction13.07121
reconstruction12.16222
reconstruction12.19823
reconstruction11.47724
reconstruction11.38825
reconstruction11.66426
reconstruction11.10227
reconstruction10.99128
reconstruction11.17729
reconstruction10.49030

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

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.145.01 ± 13.80.0781Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.614e+04 ± 1.46e+040.1518Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.712.24 ± 9.70.1250Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 38.4%0.0125total variation
regioncategoricalsouth 30.4%south 23.0%0.1224total variation
churnedbooleanfalse 76.9%false 74.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2021-04-05 ± 684 days0.1375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.212 ± 1.960.0438Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 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
  ))
))
Python

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

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.145.01 ± 13.80.0781Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+042.614e+04 ± 1.46e+040.1518Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.712.24 ± 9.70.1250Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 38.4%0.0125total variation
regioncategoricalsouth 30.4%south 23.0%0.1224total variation
churnedbooleanfalse 76.9%false 74.4%0.0250total variation
signuptemporal2020-11-05 ± 621 days2021-04-05 ± 684 days0.1375Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.212 ± 1.960.0438Kolmogorov–Smirnov D

Modes per numeric column (mode-specific normalization)

ColumnMixture modes
age5
annual income5
tenure_months5
signup5
visits5
  • 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.

08

Check: the workflow

Checkpoint

Check 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.

09

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