Beyond two modalities, and when one is missing: ImageBind and MVAE
Bind many modalities to one through images (ImageBind), then handle rows where an input is absent: a product of Gaussian experts combines whatever is present, and the uncertainty shows what's missing (MVAE).
What runs in CodeSplash
- MM017ImageBind Explained here
- SEQ011MVAE: product-of-experts multimodal variational autoencoder Partly runs in CodeSplash (Experimental)
- Variational autoencoder (latent map, anomalies and generated rows) Experimental
You will be able to
- Explain how image-anchored training aligns modalities never paired with each other
- Name the policies for rows with a missing modality and their risks
- Combine Gaussian experts by adding precisions
- Report results for each pattern of available inputs
One hub for many modalities
ReadPaired data is easy to find for images: captions, the audio of a video, depth from a sensor. Pairs of audio and text, or depth and sound, are rare. ImageBind aligns six modalities (images, text, audio, depth, thermal and motion sensors) to one shared hubShared embedding hubAligning several modalities to one, such as images, so audio and text become comparable without paired audio–text data., the image embedding, using only image-paired data.
Because everything lands near its images, audio and text end up comparable although no audio–text pair was ever seen. In the program an audio embedding is compared with three images: cosine scores 0.22, 0.98 and 0.91, so image 1 is retrieved.
Indirect alignment needs testing
ReadAlignment through a hub is indirect. Audio–text similarity is only as good as both alignments to images, and concepts that images rarely show (a sound with no typical picture) align poorly. Test any never-paired combination on real pairs before relying on it.
ImageBind's code and weights are released for non-commercial use only, so it stays an Academy concept here.
When a modality is missing
ReadReal multimodal tables have holes: products without photos, patients without a scan, clips without a transcript. A missing modalityMissing modalityA row where one input type, say the image, is absent. A model needs a stated policy for it, not a silent zero vector. needs a policy, recorded in the data contract:
- Drop the rows: simple, but the rows that remain may differ systematically.
- Fill in a stand-in (zeros, a mean embedding): the model may treat the stand-in as real evidence.
- Use a model that accepts any subset of inputs and says how sure it is.
MVAE: multiply the experts
ReadMVAE gives each modality its own encoder, which outputs a Gaussian belief about a shared latent variable. A product of expertsProduct of expertsCombining Gaussian beliefs by multiplying them: precisions add and the mean is precision-weighted, so any subset still works. combines them with a standard-normal prior expert: precisions (one over variances) add, and the mean is precision-weighted. A missing modality drops its expert.
In the program two experts with different means and variances combine to a posterior mean of 0.80 and variance 0.143. With only the first expert the variance is 0.20: less evidence, wider belief, as it should be.
import numpy as np
mu = np.array([0.8, 1.2]) # each modality's mean for the latent
var = np.array([0.25, 0.5]) # and its variance
prec = 1 / var
post_var = 1 / (1 + prec.sum()) # the 1 is the standard-normal prior expert
post_mean = post_var * np.sum(prec * mu)
one_var = 1 / (1 + prec[0]) # second modality missing
print(post_mean, post_var, one_var)mu <- c(0.8, 1.2) # each modality's mean for the latent
var <- c(0.25, 0.5) # and its variance
prec <- 1 / var
post_var <- 1 / (1 + sum(prec)) # the 1 is the standard-normal prior expert
post_mean <- post_var * sum(prec * mu)
one_var <- 1 / (1 + prec[1]) # second modality missing
print(c(post_mean, post_var, one_var))The same rule as a Bayesian update
ExploreCombining Gaussian beliefs by adding precisions is the normal prior-to-posterior update. Make the evidence sharper or weaker and watch the posterior move toward the more certain source:
EExplorable · From prior to posterior
How does evidence update what you believed, and how much does the prior matter?
What is the posterior mean?
Dashed: prior. Second line: what the data alone say. Solid: posterior, a compromise weighted 83% toward the data.
Commit your prediction above to see the result
Make your prediction to see the result.
Training for every subset
PredictPredict first
An MVAE will often see rows with only the text. During training, which inputs should its ELBO terms use?
Reveal
Each modality alone as well as together. If training only ever combines all experts, a single expert's belief is never asked to stand on its own and can be poor. MVAE adds ELBO terms for single modalities (and sampled subsets) so every pattern of inputs works.
In CodeSplash
In the appThe CodeSplash variational autoencoder learns one latent space for table columns of mixed types:
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
View data
| species | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|
| Adelie | −1.141 | −1.179 |
| Adelie | −0.6157 | −0.2508 |
| Adelie | −0.7522 | −0.0108 |
| Adelie | −0.0441 | −0.0663 |
| Adelie | −0.9352 | −0.7223 |
| Adelie | −1.177 | −1.328 |
| Adelie | −0.8850 | −0.2918 |
| Adelie | −0.4266 | −1.230 |
| Adelie | −0.6987 | −1.536 |
| Adelie | −0.9254 | −0.7389 |
| Adelie | −0.7035 | −1.023 |
| Adelie | −0.9433 | −1.083 |
| Adelie | −0.9657 | 0.1200 |
| Adelie | −1.198 | −1.422 |
| Adelie | −0.9448 | −1.842 |
| Adelie | −0.8022 | −0.6920 |
| Adelie | −0.8577 | −0.3698 |
| Adelie | −0.6615 | −0.8828 |
| Adelie | −1.070 | −0.9976 |
| Adelie | −0.9082 | −0.3532 |
| Adelie | −0.9958 | −0.2720 |
| Adelie | −0.9924 | −1.015 |
| Adelie | −0.5905 | −0.8057 |
| Adelie | −0.5908 | −0.9841 |
| Adelie | −0.6853 | −0.8234 |
| Adelie | −0.5853 | −0.8562 |
| Adelie | −0.9062 | −0.5847 |
| Adelie | −0.7418 | 0.1618 |
| Adelie | −1.238 | −0.2067 |
| Adelie | −0.7818 | −0.6975 |
| Adelie | −0.9471 | 0.6034 |
| Adelie | −1.081 | −0.6060 |
| Adelie | −0.8588 | 0.4990 |
| Adelie | −1.026 | −0.2102 |
| Adelie | −0.6944 | 0.0398 |
| Adelie | −1.046 | −0.8257 |
| Adelie | −1.096 | −0.6613 |
| Adelie | −0.9826 | 0.8071 |
| Adelie | −1.255 | 0.1502 |
| Adelie | −0.6624 | −0.5017 |
| Adelie | −1.121 | 0.1228 |
| Adelie | −0.6784 | −0.2780 |
| Adelie | −1.167 | −0.0192 |
| Adelie | −0.6106 | −0.1430 |
| Adelie | −0.9850 | 0.2950 |
| Adelie | −0.5440 | −0.5743 |
| Adelie | −1.339 | −0.1268 |
| Adelie | −1.446 | −0.5116 |
| Adelie | −0.8285 | −0.1580 |
| Adelie | −1.098 | −0.3708 |
| Adelie | −0.5625 | −0.0394 |
| Adelie | −0.4639 | −0.9229 |
| Adelie | −0.5717 | −0.6632 |
| Adelie | −0.4452 | −0.7170 |
| Adelie | −0.9354 | −0.5060 |
| Adelie | −0.6511 | −0.5528 |
| Adelie | −0.4992 | −0.1196 |
| Adelie | −0.6147 | −0.7612 |
| Adelie | −0.9135 | −0.1461 |
| Adelie | −0.7260 | −1.235 |
First 60 of 344 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 2.083 |
| false | 1.841 |
| false | 2.056 |
| false | 2.141 |
| false | 2.384 |
| false | 2.179 |
| false | 2.052 |
| false | 2.262 |
| false | 2.475 |
| false | 2.257 |
| false | 2.158 |
| false | 2.513 |
| false | 2.304 |
| false | 2.547 |
| true | 3.493 |
| false | 1.778 |
| false | 2.255 |
| false | 2.638 |
| false | 2.064 |
| true | 3.217 |
| true | 3.033 |
| false | 2.707 |
| false | 2.562 |
| false | 2.092 |
| false | 2.861 |
| false | 2.496 |
| false | 2.230 |
| false | 1.934 |
| true | 3.485 |
| false | 2.412 |
| false | 1.919 |
| false | 2.775 |
| false | 1.171 |
| false | 1.685 |
| false | 1.582 |
| false | 2.456 |
| false | 1.900 |
| false | 1.928 |
| false | 2.230 |
| false | 2.672 |
| false | 1.759 |
| false | 1.386 |
| false | 1.857 |
| false | 1.386 |
| false | 1.625 |
| false | 2.020 |
| false | 1.744 |
| false | 2.778 |
| false | 1.578 |
| false | 2.409 |
| false | 1.705 |
| false | 1.750 |
| false | 1.894 |
| false | 1.680 |
| false | 2.391 |
| false | 1.637 |
| false | 1.644 |
| false | 1.526 |
| false | 2.440 |
| false | 1.932 |
First 60 of 344 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 16.940 | 1 |
| total | 9.503 | 2 |
| total | 7.461 | 3 |
| total | 5.716 | 4 |
| total | 5.115 | 5 |
| total | 4.720 | 6 |
| total | 4.288 | 7 |
| total | 4.099 | 8 |
| total | 3.867 | 9 |
| total | 3.818 | 10 |
| total | 3.745 | 11 |
| total | 3.701 | 12 |
| total | 3.720 | 13 |
| total | 3.527 | 14 |
| total | 3.513 | 15 |
| total | 3.408 | 16 |
| total | 3.397 | 17 |
| total | 3.332 | 18 |
| total | 3.235 | 19 |
| total | 3.168 | 20 |
| total | 3.118 | 21 |
| total | 3.140 | 22 |
| total | 2.928 | 23 |
| total | 2.975 | 24 |
| total | 2.927 | 25 |
| total | 2.910 | 26 |
| total | 2.837 | 27 |
| total | 2.865 | 28 |
| total | 2.795 | 29 |
| total | 2.740 | 30 |
| total | 2.691 | 31 |
| total | 2.684 | 32 |
| total | 2.658 | 33 |
| total | 2.643 | 34 |
| total | 2.668 | 35 |
| total | 2.663 | 36 |
| total | 2.561 | 37 |
| total | 2.582 | 38 |
| total | 2.537 | 39 |
| total | 2.562 | 40 |
| total | 2.589 | 41 |
| total | 2.522 | 42 |
| total | 2.535 | 43 |
| total | 2.491 | 44 |
| total | 2.461 | 45 |
| total | 2.505 | 46 |
| total | 2.607 | 47 |
| total | 2.571 | 48 |
| total | 2.505 | 49 |
| total | 2.463 | 50 |
| total | 2.516 | 51 |
| total | 2.473 | 52 |
| total | 2.488 | 53 |
| total | 2.452 | 54 |
| total | 2.429 | 55 |
| total | 2.483 | 56 |
| total | 2.455 | 57 |
| total | 2.488 | 58 |
| total | 2.505 | 59 |
| total | 2.539 | 60 |
First 60 of 240 rows.
View data
| Density | Source | bill_len |
|---|---|---|
| 0.0032 | real | 32.558 |
| 0.0064 | real | 33.475 |
| 0.0191 | real | 34.392 |
| 0.0351 | real | 35.308 |
| 0.0510 | real | 36.225 |
| 0.0415 | real | 37.142 |
| 0.0670 | real | 38.058 |
| 0.0542 | real | 38.975 |
| 0.0606 | real | 39.892 |
| 0.0670 | real | 40.808 |
| 0.0415 | real | 41.725 |
| 0.0447 | real | 42.642 |
| 0.0447 | real | 43.558 |
| 0.0255 | real | 44.475 |
| 0.0861 | real | 45.392 |
| 0.0797 | real | 46.308 |
| 0.0574 | real | 47.225 |
| 0.0383 | real | 48.142 |
| 0.0606 | real | 49.058 |
| 0.0670 | real | 49.975 |
| 0.0670 | real | 50.892 |
| 0.0351 | real | 51.808 |
| 0.0096 | real | 52.725 |
| 0.0064 | real | 53.642 |
| 0.0064 | real | 54.558 |
| 0.0096 | real | 55.475 |
| 0 | real | 56.392 |
| 0 | real | 57.308 |
| 0.0032 | real | 58.225 |
| 0.0032 | real | 59.142 |
| 0.0036 | synthetic | 32.558 |
| 0 | synthetic | 33.475 |
| 0.0073 | synthetic | 34.392 |
| 0.0109 | synthetic | 35.308 |
| 0.0255 | synthetic | 36.225 |
| 0.0291 | synthetic | 37.142 |
| 0.0582 | synthetic | 38.058 |
| 0.0764 | synthetic | 38.975 |
| 0.1018 | synthetic | 39.892 |
| 0.0764 | synthetic | 40.808 |
| 0.0291 | synthetic | 41.725 |
| 0.0655 | synthetic | 42.642 |
| 0.0582 | synthetic | 43.558 |
| 0.0691 | synthetic | 44.475 |
| 0.0909 | synthetic | 45.392 |
| 0.0873 | synthetic | 46.308 |
| 0.0436 | synthetic | 47.225 |
| 0.0800 | synthetic | 48.142 |
| 0.0364 | synthetic | 49.058 |
| 0.0473 | synthetic | 49.975 |
| 0.0327 | synthetic | 50.892 |
| 0.0255 | synthetic | 51.808 |
| 0.0036 | synthetic | 52.725 |
| 0.0073 | synthetic | 53.642 |
| 0.0036 | synthetic | 54.558 |
| 0.0145 | synthetic | 55.475 |
| 0 | synthetic | 56.392 |
| 0.0036 | synthetic | 57.308 |
| 0 | synthetic | 58.225 |
| 0.0036 | synthetic | 59.142 |
Assumptions
- Latent dimensions in use — 3 of 3 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | island | bill_len | bill_dep | flipper_len | body_mass | sex |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | 4.851 | Dream | 58 | 17.800 | 181 | 3,700 | female |
| 2 | 186 | 3.874 | Biscoe | 59.600 | 17 | 230 | 6,050 | male |
| 3 | 115 | 3.707 | Biscoe | 39.600 | 20.700 | 191 | 3,900 | female |
| 4 | 15 | 3.493 | Torgersen | 34.600 | 21.100 | 198 | 4,400 | male |
| 5 | 29 | 3.485 | Biscoe | 37.900 | 18.600 | 172 | 3,150 | female |
| 6 | 143 | 3.454 | Dream | 32.100 | 15.500 | 188 | 3,050 | female |
| 7 | 314 | 3.399 | Dream | 52 | 20.700 | 210 | 4,800 | male |
| 8 | 20 | 3.217 | Torgersen | 46 | 21.500 | 194 | 4,200 | male |
| 9 | 99 | 3.171 | Dream | 33.100 | 16.100 | 178 | 2,900 | female |
| 10 | 21 | 3.033 | Biscoe | 37.800 | 18.300 | 174 | 3,400 | female |
| 11 | 25 | 2.861 | Biscoe | 38.800 | 17.200 | 180 | 3,800 | male |
| 12 | 340 | 2.858 | Dream | 55.800 | 19.800 | 207 | 4,000 | male |
| 13 | 123 | 2.851 | Torgersen | 40.200 | 17 | 176 | 3,450 | female |
| 14 | 48 | 2.778 | Dream | 37.500 | 18.900 | 179 | 2,975 | — |
| 15 | 32 | 2.775 | Dream | 37.200 | 18.100 | 178 | 3,900 | male |
| 16 | 325 | 2.769 | Dream | 51.500 | 18.700 | 187 | 3,250 | male |
| 17 | 308 | 2.753 | Dream | 54.200 | 20.800 | 201 | 4,300 | male |
| 18 | 62 | 2.726 | Biscoe | 41.300 | 21.100 | 195 | 4,400 | male |
| 19 | 22 | 2.707 | Biscoe | 37.700 | 18.700 | 180 | 3,600 | male |
| 20 | 315 | 2.700 | Dream | 46.900 | 16.600 | 192 | 2,700 | female |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 1.049 | 0.8742 | yes |
| 2 | 0.4199 | 0.4692 | yes |
| 3 | 0.7780 | 0.7777 | yes |
The exact R script · R R version 4.5.1 (2025-06-13)
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec f40446a8353fc58b
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_deep_fit_vae: torch VAE with shared initial weights (twin of codesplash.deep.generative)
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE <- "median"
SCALE <- "standard"
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"))), c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"))
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
optimizer = "default",
lr_schedule = "none",
warmup_epochs = 0,
grad_clip = 0,
ema_decay = 0,
swa_start = 0,
history_every_step = FALSE,
profile = "parity",
checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/discover.vae/penguins_mixed_batches/out-r")
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric",
sex = "categorical"
),
levels = list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
LABEL <- "species"
if (!is.null(LABEL)) df[[LABEL]] <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = LABEL))[[LABEL]]
# %% Variational autoencoder (torch for R, float64, one thread): encoder -> (mu, log sigma^2) -> z = mu + sigma * eps -> decoder
HIDDEN <- as.integer(unlist(c(16)))
LATENT <- as.integer(3)
BETA <- 0.5
N_SAMPLES <- as.integer(300)
PRIOR <- "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE <- as.integer(0)
if (PRIOR == "mixture" && length(rows) <= 3) {
cs_error("CS_E_TOO_FEW_ROWS", what = "A 3-component mixture prior", min = 3 + 1, n = length(rows))
}
fit <- if (PRIOR == "mixture") {
cs_deep_fit_vade(
X, HIDDEN, LATENT, as.integer(3),
activation = "relu",
beta = BETA,
epochs = as.integer(80),
lr = 0.005,
batch_size = 64,
weight_decay = 0,
n_samples = N_SAMPLES,
pretrain_epochs = as.integer(100),
seed = 42
)
} else {
cs_deep_fit_vae(
X, HIDDEN, LATENT,
activation = "relu",
beta = BETA,
epochs = as.integer(80),
lr = 0.005,
batch_size = 64,
weight_decay = 0,
n_samples = N_SAMPLES,
seed = 42
)
}
if (any(!is.finite(fit$score))) cs_error("CS_E_NO_CONVERGENCE", what = "Variational autoencoder training")
Z <- fit$embedding # posterior means mu (n x LATENT)
scores <- fit$score # squared reconstruction error at z = mu plus beta x KL, per row
errors <- fit$error # mean squared reconstruction error per standardized column
# %% Anomalies by the per-row loss
RULE <- "cutoff"
flagged <- cs_ml_flag(scores, RULE, 0.05, 3)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # largest loss first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample <- cs_ml_sample_rows(length(rows))
k_eval <- min(10L, length(sample) - 2L)
trust <- if (k_eval >= 1L) cs_ml_trustworthiness(X[sample, , drop = FALSE], Z[sample, , drop = FALSE], k_eval) else NaN # undefined with fewer than 3 rows
# %% Mixture prior: each row's component at z = mu (canonical ids 1..k by size)
clusters <- NULL
if (PRIOR == "mixture") {
clusters <- cs_ml_canonical(fit$cluster)
comp_of <- integer(0)
for (j in seq_along(fit$pi)) {
members <- which(fit$cluster == j - 1L)
if (length(members)) comp_of[as.character(j)] <- clusters[members[1]]
}
}
# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound <- if (IWAE > 0L) cs_deep_iwae_bound(X, fit, LATENT, "relu", IWAE, 42) else NULL
# %% Generated rows: decode prior draws back to the columns' units
gen_cols <- if (N_SAMPLES > 0L) cs_deep_decode_design(fitted, fit$samples) else list()
NUMERIC <- Filter(function(f) identical(design$kinds[[f]], "numeric"), FEATURES)
sample_ks <- list()
if (N_SAMPLES > 0L) for (f in NUMERIC) sample_ks[[f]] <- cs_deep_ks(suppressWarnings(as.numeric(df[[f]])), gen_cols[[f]])
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.vae/penguins_mixed_batches/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(LATENT)) emb[[paste0("dim_", j)]] <- Z[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
labels_df <- data.frame(row = as.integer(rows), score = scores, anomaly = flags)
if (!is.null(clusters)) labels_df$cluster <- as.integer(clusters)
nanoparquet::write_parquet(labels_df, file.path(out, "labels.parquet"))
hist <- data.frame(
epoch = vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1)),
loss = vapply(fit$history, function(h) h$loss, numeric(1)),
reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
kl = vapply(fit$history, function(h) h$kl, numeric(1))
)
nanoparquet::write_parquet(hist, file.path(out, "history.parquet"))
artifacts <- list(
list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet")
)
if (N_SAMPLES > 0L) {
nanoparquet::write_parquet(as.data.frame(gen_cols[FEATURES], check.names = FALSE), file.path(out, "samples.parquet"))
artifacts[[length(artifacts) + 1L]] <- list(key = "samples", path = file.path(out, "samples.parquet"), format = "parquet",
title = "Rows generated from the prior")
}
# %% Result
active <- as.integer(fit$active)
values <- list(
n = length(rows), n_features = ncol(X), latent_dim = LATENT, recon_mse = mean(errors), kl = mean(fit$kl_row),
elbo_loss = mean(scores), active_dims = active, error_check = cs_ml_checksum(scores, rows), n_flagged = sum(flags),
threshold = threshold, final_loss = hist$loss[nrow(hist)], epochs_run = fit$epochs_run, trustworthiness = trust,
n_samples = N_SAMPLES, sample_ks_mean = if (length(sample_ks)) mean(unlist(sample_ks)) else NaN
)
for (j in seq_len(LATENT)) {
values[[sprintf("emb_check[%d]", j)]] <- cs_ml_checksum(Z[, j], rows)
values[[sprintf("kl_dim[%d]", j)]] <- fit$kl_dim[j]
}
for (f in names(sample_ks)) values[[sprintf("sample_ks[%s]", f)]] <- sample_ks[[f]]
if (!is.null(clusters)) {
values$components <- length(fit$pi)
values$n_clusters <- length(comp_of)
for (j in names(comp_of)) {
values[[sprintf("pi[%d]", comp_of[[j]])]] <- fit$pi[as.integer(j)]
values[[sprintf("cluster_size[%d]", comp_of[[j]])]] <- sum(clusters == comp_of[[j]])
}
}
if (!is.null(bound)) {
values$iwae_samples <- IWAE
values$iwae_bound <- mean(bound$iwae)
values$elbo_estimate <- mean(bound$elbo)
values$iwae_gap <- values$iwae_bound - values$elbo_estimate
}
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
dim_rows <- lapply(seq_len(LATENT), function(j) list(dim = j, kl = fit$kl_dim[j], var_mu = fit$mu_var[j], active = fit$mu_var[j] > 0.01))
pick <- cs_ml_sample_rows(length(rows), 5000)
groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
g <- df[[LABEL]][rows[pick] + 1L]
ifelse(is.na(g), "(missing)", as.character(g))
}
charts <- list()
if (LATENT >= 2L && !is.null(clusters)) {
cent_ <- as.integer(names(comp_of))[order(comp_of)]
charts[[length(charts) + 1L]] <- cs_chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", list(
x = cs_col("Latent 1 (μ)", c(Z[pick, 1], fit$mu_c[cent_, 1]), "numeric"),
y = cs_col("Latent 2 (μ)", c(Z[pick, 2], fit$mu_c[cent_, 2]), "numeric"),
cluster = cs_col("Component", c(as.character(clusters[pick]), as.character(comp_of[as.character(cent_)])), "categorical",
levels = as.character(sort(as.integer(comp_of)))),
centroid = cs_col("Component mean", c(rep(FALSE, length(pick)), rep(TRUE, length(cent_))), "boolean")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
} else if (LATENT >= 2L) {
charts[[length(charts) + 1L]] <- cs_chart("latent", "latent-prior", "Latent means against the N(0, I) prior", list(
x = cs_col("Latent 1 (μ)", Z[pick, 1], "numeric"),
y = cs_col("Latent 2 (μ)", Z[pick, 2], "numeric"),
group = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
), note = if (length(pick) == length(rows)) NULL else sprintf("%s of %s rows shown.", format(length(pick), big.mark = ","), format(length(rows), big.mark = ",")))
}
charts[[length(charts) + 1L]] <- cs_chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", list(
score = cs_col("Per-row loss", scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))
ne <- nrow(hist)
charts[[length(charts) + 1L]] <- cs_chart("training", "training-components", "Training loss and its parts by epoch", list(
x = cs_col("Epoch", rep(hist$epoch, 3), "numeric"),
value = cs_col("Loss per row", c(hist$loss, hist$reconstruction, hist$kl), "numeric"),
component = cs_col("Part", rep(c("total", "reconstruction", "KL"), each = ne), "categorical", levels = c("total", "reconstruction", "KL"))
))
if (length(sample_ks)) {
f0 <- NUMERIC[1]
d <- cs_synth_density_rows(suppressWarnings(as.numeric(df[[f0]])), as.numeric(gen_cols[[f0]]))
if (!is.null(d)) {
charts[[length(charts) + 1L]] <- cs_chart("samples", "density-compare", sprintf("%s: data vs rows generated from the prior", f0), list(
x = cs_col(f0, d$x, "numeric"), density = cs_col("Density", d$density, "numeric"),
source = cs_col("Source", d$source, "categorical", levels = c("real", "synthetic"))))
}
}
assumptions <- list(list(
key = "active_units", label = "Latent dimensions in use",
status = if (active == LATENT) "pass" else if (active == 0L) "fail" else "warn",
detail = paste0(sprintf("%d of %d latent dimension%s vary across rows (variance of μ > 0.01)", active, LATENT, if (LATENT != 1L) "s" else ""),
if (active == LATENT) "." else "; the rest collapsed onto the prior and carry no information about the rows.")
))
if (active < LATENT) {
warnings <- c(warnings, sprintf("Posterior collapse: %d latent dimension%s carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.",
LATENT - active, if (LATENT - active != 1L) "s" else ""))
}
summary <- sprintf("A variational autoencoder mapped %d rows into %d latent coordinate%s (%d in use); the mean squared reconstruction error is %s per standardized column and the mean KL is %s nats; %d rows with a loss of at least %s are flagged as anomalies.",
length(rows), LATENT, if (LATENT != 1L) "s" else "", active, format(signif(mean(errors), 3)), format(signif(mean(fit$kl_row), 3)),
sum(flags), format(signif(threshold, 3)))
if (length(sample_ks)) summary <- paste0(summary, sprintf(" %d rows generated from the prior differ from the data by a mean KS distance of %.3f.", N_SAMPLES, values$sample_ks_mean))
if (!is.null(clusters)) summary <- paste0(summary, sprintf(" The mixture prior's %d components hold %d cluster%s of rows.", length(fit$pi), length(comp_of), if (length(comp_of) != 1L) "s" else ""))
if (!is.null(bound)) summary <- paste0(summary, sprintf(" The importance-weighted bound with %d draws is %s nats per row (%s above the ELBO estimate).", IWAE,
format(signif(values$iwae_bound, 4)), format(signif(values$iwae_gap, 3))))
extra_stats <- list()
if (!is.null(bound)) extra_stats[[1]] <- list(key = "iwae_bound", label = sprintf("Log-likelihood bound (IWAE, %d draws)", IWAE), value = values$iwae_bound)
extra_tables <- list()
if (!is.null(clusters)) {
ordj <- as.integer(names(comp_of))[order(comp_of)]
extra_tables[[1]] <- list(
key = "components", title = "Mixture prior components",
columns = c(list(list(key = "cluster", label = "Component", type = "integer"), list(key = "size", label = "Rows", type = "integer"),
list(key = "weight", label = "Prior weight", type = "number")),
lapply(seq_len(LATENT), function(d) list(key = sprintf("mu_%d", d), label = sprintf("Mean %d", d), type = "number"))),
rows = lapply(ordj, function(j) {
cc <- comp_of[[as.character(j)]]
r <- list(cluster = cc, size = sum(clusters == cc), weight = fit$pi[j])
for (d in seq_len(LATENT)) r[[sprintf("mu_%d", d)]] <- fit$mu_c[j, d]
r
})
)
}
cs_publish(list(
title = "Variational autoencoder (latent map, anomalies and generated rows)",
engine = cs_engine_info("torch", "nanoparquet"),
n = length(rows),
summary = summary,
statistics = c(list(
list(key = "recon_mse", label = "Mean reconstruction error", value = mean(errors)),
list(key = "kl", label = "Mean KL (nats per row)", value = mean(fit$kl_row)),
list(key = "active_dims", label = "Active latent dimensions", value = active, format = "integer"),
list(key = "trustworthiness", label = sprintf("Trustworthiness (k = %d)", k_eval), value = trust),
list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer")
), extra_stats),
tables = c(list(
list(
key = "top", title = "Rows the model finds least typical",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = "Per-row loss", type = "number")),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
),
list(
key = "latent", title = "Latent dimensions",
columns = list(list(key = "dim", label = "Dimension", type = "integer"), list(key = "kl", label = "Mean KL (nats)", type = "number"),
list(key = "var_mu", label = "Variance of μ", type = "number"), list(key = "active", label = "Active", type = "boolean")),
rows = dim_rows
)
), extra_tables),
charts = charts,
assumptions = assumptions,
values = values,
warnings = warnings,
artifacts = artifacts
))
A variational autoencoder mapped 344 rows into 3 latent coordinates (3 in use); the mean squared reconstruction error is 0.0852 per standardized column and the mean KL is 2.25 nats; 10 rows with a loss of at least 3 are flagged as anomalies. 300 rows generated from the prior differ from the data by a mean KS distance of 0.124.
- Mean reconstruction error
- 0.0852
- Mean KL (nats per row)
- 2.247
- Active latent dimensions
- 3
- Trustworthiness (k = 10)
- 0.9680
- Anomalies
- 10
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Latent dimensions in use — 3 of 3 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | island | bill_len | bill_dep | flipper_len | body_mass | sex |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | 4.851 | Dream | 58 | 17.800 | 181 | 3,700 | female |
| 2 | 186 | 3.874 | Biscoe | 59.600 | 17 | 230 | 6,050 | male |
| 3 | 115 | 3.707 | Biscoe | 39.600 | 20.700 | 191 | 3,900 | female |
| 4 | 15 | 3.493 | Torgersen | 34.600 | 21.100 | 198 | 4,400 | male |
| 5 | 29 | 3.485 | Biscoe | 37.900 | 18.600 | 172 | 3,150 | female |
| 6 | 143 | 3.454 | Dream | 32.100 | 15.500 | 188 | 3,050 | female |
| 7 | 314 | 3.399 | Dream | 52 | 20.700 | 210 | 4,800 | male |
| 8 | 20 | 3.217 | Torgersen | 46 | 21.500 | 194 | 4,200 | male |
| 9 | 99 | 3.171 | Dream | 33.100 | 16.100 | 178 | 2,900 | female |
| 10 | 21 | 3.033 | Biscoe | 37.800 | 18.300 | 174 | 3,400 | female |
| 11 | 25 | 2.861 | Biscoe | 38.800 | 17.200 | 180 | 3,800 | male |
| 12 | 340 | 2.858 | Dream | 55.800 | 19.800 | 207 | 4,000 | male |
| 13 | 123 | 2.851 | Torgersen | 40.200 | 17 | 176 | 3,450 | female |
| 14 | 48 | 2.778 | Dream | 37.500 | 18.900 | 179 | 2,975 | — |
| 15 | 32 | 2.775 | Dream | 37.200 | 18.100 | 178 | 3,900 | male |
| 16 | 325 | 2.769 | Dream | 51.500 | 18.700 | 187 | 3,250 | male |
| 17 | 308 | 2.753 | Dream | 54.200 | 20.800 | 201 | 4,300 | male |
| 18 | 62 | 2.726 | Biscoe | 41.300 | 21.100 | 195 | 4,400 | male |
| 19 | 22 | 2.707 | Biscoe | 37.700 | 18.700 | 180 | 3,600 | male |
| 20 | 315 | 2.700 | Dream | 46.900 | 16.600 | 192 | 2,700 | female |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 1.049 | 0.8742 | yes |
| 2 | 0.4199 | 0.4692 | yes |
| 3 | 0.7780 | 0.7777 | yes |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Variational autoencoder (latent map, anomalies and generated rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.vae 1.2.0 · spec f40446a8353fc58b
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.deep import generative as gen # twin of codesplashr::cs_deep_fit_vae (shared initial weights, Adam written out)
from codesplash.deep import unsupervised as du # VaDE prior and the importance-weighted bound (twin of codesplashr::cs_deep_fit_vade)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
from codesplash.synth import common as sy
# %% Data — standardized numbers (median-imputed), one-hot categories
IMPUTE = "median"
SCALE = "standard"
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]), ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"])
from codesplash.deep import trainer as deep_trainer # training options, live progress, checkpoints (twin: cs_deep_trainer_*)
deep_trainer.configure(
{
"optimizer": "default",
"lr_schedule": "none",
"warmup_epochs": 0,
"grad_clip": 0,
"ema_decay": 0,
"swa_start": 0,
"history_every_step": False,
"profile": "parity",
"checkpoint_every": None,
},
out_dir="target/academy-parity/run-8142/discover.vae/penguins_mixed_batches/out-python",
)
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "body_mass", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
LABEL = "species"
if LABEL:
df[LABEL] = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=[LABEL])[LABEL]
# %% Variational autoencoder (PyTorch, float64, one thread): encoder → (μ, log σ²) → z = μ + σ·ε → decoder
HIDDEN = [int(u) for u in [16]]
LATENT = 3
BETA = 0.5
N_SAMPLES = 300
PRIOR = "normal" # N(0, I), or a learned Gaussian mixture (VaDE)
IWAE = 0
if PRIOR == "mixture" and len(rows) <= 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="A 3-component mixture prior", min=3 + 1, n=len(rows))
if PRIOR == "mixture":
fit = du.fit_vade(
X, HIDDEN, LATENT, 3,
activation="relu",
beta=BETA,
epochs=80,
lr=0.005,
batch_size=64,
weight_decay=0,
n_samples=N_SAMPLES,
pretrain_epochs=100,
seed=42,
)
else:
fit = gen.fit_vae(
X, HIDDEN, LATENT,
activation="relu",
beta=BETA,
epochs=80,
lr=0.005,
batch_size=64,
weight_decay=0,
n_samples=N_SAMPLES,
seed=42,
)
if not np.all(np.isfinite(fit["score"])):
cs.cs_error("CS_E_NO_CONVERGENCE", what="Variational autoencoder training")
Z = fit["embedding"] # posterior means μ (n × LATENT)
scores = fit["score"] # squared reconstruction error at z = μ plus β × KL, per row
errors = fit["error"] # mean squared reconstruction error per standardized column
# %% Anomalies by the per-row loss
RULE = "cutoff"
flags, threshold = csanom.flag(scores, RULE, 0.05, 3)
order = np.lexsort((rows, -scores)) # largest loss first, ties by row
# %% Neighborhood preservation of the map (same rows in both engines)
sample = csembed.sample_rows(len(rows))
k_eval = min(10, len(sample) - 2)
trust = csembed.trustworthiness(X[sample], Z[sample], k_eval) if k_eval >= 1 else float("nan") # undefined with fewer than 3 rows
# %% Mixture prior: each row's component at z = μ (canonical ids 1…k by size)
clusters = None
if PRIOR == "mixture":
from codesplash.ml import cluster as csc
clusters = csc.canonical(fit["cluster"])
comp_of = {}
for j in range(len(fit["pi"])):
members = np.flatnonzero(fit["cluster"] == j)
if len(members):
comp_of[j] = int(clusters[members[0]])
# %% Importance-weighted bound on log p(x) (and the ELBO from the same draws)
bound = du.iwae_bound(X, fit, LATENT, "relu", IWAE, 42) if IWAE > 0 else None
# %% Generated rows: decode prior draws back to the columns' units
gen_cols = gen.decode_design(fitted, fit["samples"]) if N_SAMPLES > 0 else {}
NUMERIC = [f for f in FEATURES if design.kinds[f] == "numeric"]
sample_ks = {}
for f in NUMERIC if N_SAMPLES > 0 else []:
real = pd.to_numeric(df[f], errors="coerce").to_numpy(dtype=np.float64)
sample_ks[f] = gen.ks_distance(real, gen_cols[f])
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.vae/penguins_mixed_batches/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64), **{f"dim_{j + 1}": Z[:, j] for j in range(LATENT)}})
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags, **({"cluster": clusters} if clusters is not None else {})}).to_parquet(
os.path.join(out, "labels.parquet"), index=False
)
history = pd.DataFrame({
"epoch": [h["epoch"] for h in fit["history"]],
"loss": [h["loss"] for h in fit["history"]],
"reconstruction": [h["recon"] for h in fit["history"]],
"kl": [h["kl"] for h in fit["history"]],
})
history.to_parquet(os.path.join(out, "history.parquet"), index=False)
artifacts = [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
]
if N_SAMPLES > 0:
pd.DataFrame({f: gen_cols[f] for f in FEATURES}).to_parquet(os.path.join(out, "samples.parquet"), index=False)
artifacts.append({"key": "samples", "path": os.path.join(out, "samples.parquet"), "format": "parquet", "title": "Rows generated from the prior"})
# %% Result
active = int(fit["active"])
values = {
"n": len(rows),
"n_features": int(X.shape[1]),
"latent_dim": LATENT,
"recon_mse": float(np.mean(errors)),
"kl": float(np.mean(fit["kl_row"])),
"elbo_loss": float(np.mean(scores)),
"active_dims": active,
"error_check": csembed.checksum(scores, rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"final_loss": float(fit["history"][-1]["loss"]),
"epochs_run": int(fit["epochs_run"]),
"trustworthiness": trust,
"n_samples": N_SAMPLES,
"sample_ks_mean": float(np.mean(list(sample_ks.values()))) if sample_ks else float("nan"),
}
for j in range(LATENT):
values[f"emb_check[{j + 1}]"] = csembed.checksum(Z[:, j], rows)
values[f"kl_dim[{j + 1}]"] = float(fit["kl_dim"][j])
for f, v in sample_ks.items():
values[f"sample_ks[{f}]"] = v
if clusters is not None:
values["components"] = int(len(fit["pi"]))
values["n_clusters"] = len(comp_of)
for j, c in comp_of.items():
values[f"pi[{c}]"] = float(fit["pi"][j])
values[f"cluster_size[{c}]"] = int(np.sum(clusters == c))
if bound is not None:
values["iwae_samples"] = IWAE
values["iwae_bound"] = float(np.mean(bound["iwae"]))
values["elbo_estimate"] = float(np.mean(bound["elbo"]))
values["iwae_gap"] = values["iwae_bound"] - values["elbo_estimate"]
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
table_rows = []
for rank, i in enumerate(order[:20], start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
for f in FEATURES:
v = df[f].iloc[rows[i]]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
dim_rows = [{"dim": j + 1, "kl": float(fit["kl_dim"][j]), "var_mu": float(fit["mu_var"][j]), "active": bool(fit["mu_var"][j] > 0.01)} for j in range(LATENT)]
pick = csembed.sample_rows(len(rows), 5000)
groups = [("All rows" if LABEL is None else ("(missing)" if pd.isna(v) else str(v))) for v in (df[LABEL].iloc[rows[pick]] if LABEL else [None] * len(pick))]
charts = []
if LATENT >= 2 and clusters is not None:
_cent = sorted(comp_of, key=lambda j: comp_of[j])
charts.append(cs.chart("latent", "cluster-scatter", "Latent means by mixture component (component means marked)", {
"x": cs.col("Latent 1 (μ)", list(Z[pick, 0]) + [float(fit["mu_c"][j, 0]) for j in _cent], "numeric"),
"y": cs.col("Latent 2 (μ)", list(Z[pick, 1]) + [float(fit["mu_c"][j, 1]) for j in _cent], "numeric"),
"cluster": cs.col("Component", [str(c) for c in clusters[pick]] + [str(comp_of[j]) for j in _cent], "categorical",
levels=[str(c) for c in sorted(comp_of.values())]),
"centroid": cs.col("Component mean", [False] * len(pick) + [True] * len(_cent), "boolean"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
elif LATENT >= 2:
charts.append(cs.chart("latent", "latent-prior", "Latent means against the N(0, I) prior", {
"x": cs.col("Latent 1 (μ)", Z[pick, 0], "numeric"),
"y": cs.col("Latent 2 (μ)", Z[pick, 1], "numeric"),
"group": cs.col(LABEL or "Group", groups, "categorical"),
}, note=None if len(pick) == len(rows) else f"{len(pick):,} of {len(rows):,} rows shown."))
charts.append(cs.chart("errors", "anomaly-scores", "Per-row loss (reconstruction + β·KL) distribution", {
"score": cs.col("Per-row loss", scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}))
ep = [h["epoch"] for h in fit["history"]]
charts.append(cs.chart("training", "training-components", "Training loss and its parts by epoch", {
"x": cs.col("Epoch", ep * 3, "numeric"),
"value": cs.col("Loss per row", [h["loss"] for h in fit["history"]] + [h["recon"] for h in fit["history"]] + [h["kl"] for h in fit["history"]], "numeric"),
"component": cs.col("Part", ["total"] * len(ep) + ["reconstruction"] * len(ep) + ["KL"] * len(ep), "categorical", levels=["total", "reconstruction", "KL"]),
}))
if sample_ks:
f0 = NUMERIC[0]
xs, dens, src = sy.density_rows(pd.to_numeric(df[f0], errors="coerce").to_numpy(dtype=np.float64), np.asarray(gen_cols[f0], dtype=np.float64))
if xs:
charts.append(cs.chart("samples", "density-compare", f"{f0}: data vs rows generated from the prior", {
"x": cs.col(f0, xs, "numeric"),
"density": cs.col("Density", dens, "numeric"),
"source": cs.col("Source", src, "categorical", levels=["real", "synthetic"]),
}))
assumptions = [{
"key": "active_units",
"label": "Latent dimensions in use",
"status": "pass" if active == LATENT else ("fail" if active == 0 else "warn"),
"detail": f"{active} of {LATENT} latent dimension{'s' if LATENT != 1 else ''} vary across rows (variance of μ > 0.01)"
+ ("." if active == LATENT else "; the rest collapsed onto the prior and carry no information about the rows."),
}]
if active < LATENT:
warnings.append(f"Posterior collapse: {LATENT - active} latent dimension{'s' if LATENT - active != 1 else ''} carry no information (KL ≈ 0). Lower β, shrink the bottleneck, or train longer.")
summary = (
f"A variational autoencoder mapped {len(rows)} rows into {LATENT} latent coordinate{'s' if LATENT != 1 else ''} "
f"({active} in use); the mean squared reconstruction error is {np.mean(errors):.3g} per standardized column and the mean KL is "
f"{np.mean(fit['kl_row']):.3g} nats; {int(flags.sum())} rows with a loss of at least {threshold:.3g} are flagged as anomalies."
)
if sample_ks:
summary += f" {N_SAMPLES} rows generated from the prior differ from the data by a mean KS distance of {values['sample_ks_mean']:.3f}."
if clusters is not None:
summary += f" The mixture prior's {len(fit['pi'])} components hold {len(comp_of)} cluster{'s' if len(comp_of) != 1 else ''} of rows."
if bound is not None:
summary += f" The importance-weighted bound with {IWAE} draws is {values['iwae_bound']:.4g} nats per row ({values['iwae_gap']:.3g} above the ELBO estimate)."
extra_stats = []
if bound is not None:
extra_stats.append({"key": "iwae_bound", "label": f"Log-likelihood bound (IWAE, {IWAE} draws)", "value": values["iwae_bound"]})
extra_tables = []
if clusters is not None:
extra_tables.append({
"key": "components",
"title": "Mixture prior components",
"columns": [{"key": "cluster", "label": "Component", "type": "integer"}, {"key": "size", "label": "Rows", "type": "integer"},
{"key": "weight", "label": "Prior weight", "type": "number"}]
+ [{"key": f"mu_{d + 1}", "label": f"Mean {d + 1}", "type": "number"} for d in range(LATENT)],
"rows": [{"cluster": comp_of[j], "size": int(np.sum(clusters == comp_of[j])), "weight": float(fit["pi"][j]),
**{f"mu_{d + 1}": float(fit["mu_c"][j, d]) for d in range(LATENT)}} for j in sorted(comp_of, key=lambda j: comp_of[j])],
})
cs.publish({
"title": "Variational autoencoder (latent map, anomalies and generated rows)",
"engine": cs.engine_info("torch", "numpy", "pandas"),
"n": len(rows),
"summary": summary,
"statistics": [
{"key": "recon_mse", "label": "Mean reconstruction error", "value": float(np.mean(errors))},
{"key": "kl", "label": "Mean KL (nats per row)", "value": float(np.mean(fit["kl_row"]))},
{"key": "active_dims", "label": "Active latent dimensions", "value": active, "format": "integer"},
{"key": "trustworthiness", "label": f"Trustworthiness (k = {k_eval})", "value": trust},
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
] + extra_stats,
"tables": [
{
"key": "top",
"title": "Rows the model finds least typical",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": "Per-row loss", "type": "number"}] + [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
},
{
"key": "latent",
"title": "Latent dimensions",
"columns": [{"key": "dim", "label": "Dimension", "type": "integer"}, {"key": "kl", "label": "Mean KL (nats)", "type": "number"},
{"key": "var_mu", "label": "Variance of μ", "type": "number"}, {"key": "active", "label": "Active", "type": "boolean"}],
"rows": dim_rows,
},
] + extra_tables,
"charts": charts,
"assumptions": assumptions,
"values": values,
"warnings": warnings,
"artifacts": artifacts,
})
Here 344 penguins with numeric and categorical columns share a 3-dimensional latent space.
Check: many and missing modalities
CheckpointCheck yourself
How does ImageBind make audio and text comparable without audio–text training pairs?
Show the answer
Answer: a
Images are the hub. The audio–text alignment is a side effect, which is why it must be tested directly.
Check yourself
You want to search sound effects by text with a hub-aligned model. What should you do before trusting it?
Show the answer
Answer: b
Indirect alignment can be weak for concepts with no typical picture. Measure the pairing you'll use.
Check yourself
Two modality experts have variances 0.5 and 0.25. Combined with a standard-normal prior expert (variance 1), what is the posterior variance?
Show the answer
Answer: 0.1429
Precisions add: 1 + 1/0.5 + 1/0.25 = 1 + 2 + 4 = 7, so the variance is 1/7 = 0.143, smaller than either expert's alone.
Check yourself
In a product-of-experts MVAE, the image is missing for a row. What happens?
Show the answer
Answer: a
Dropping an expert removes its precision, so the belief widens honestly instead of pretending the image was seen.
Check yourself
One expert is very sure (small variance) and another is vague (large variance). Where does the product-of-experts mean land?
Show the answer
Answer: a
The mean is precision-weighted, so the confident expert dominates, as in any Gaussian update.
Check yourself
30% of test rows lack an image. How should you report your multimodal model's accuracy?
Show the answer
Answer: b
An average hides how the model behaves on each input pattern, and the mix in deployment may differ from the test set.
Recap
Recap- ImageBind aligns many modalities to images; pairs never seen together are comparable only indirectly, so test them.
- A missing modality needs a stated policy: dropping rows and stand-in values both carry risks.
- A product of Gaussian experts adds precisions; a missing modality drops its expert and the belief widens.
- Train with each modality alone and report results for every pattern of available inputs.
Concepts in this lesson