Skip to content

CDiscover · discover.vae

Variational autoencoder (latent map, anomalies and generated rows)

What smooth low-dimensional space do the rows come from — which rows does it explain worst, and what would new rows from it look like?

A neural network that encodes every row as a small normal distribution in a latent space and decodes a draw from it back into the row. The loss balances rebuilding the row against keeping the latent space close to a standard normal (β × KL), so the space is smooth and can be sampled: the posterior means form a map, the rows with the largest loss are anomaly candidates, and decoding normal draws generates new rows. With the mixture prior (VaDE) the prior is a learned mixture of Gaussians, so the same model also clusters the rows; the importance-weighted bound estimates the log-likelihood more tightly than the ELBO. Lab tier: trained by Adam on torch in both engines from the same initial weights and the same noise draws.

Experimental Python and R use different algorithms; results agree in substance Seeded Also called VAE, variational auto-encoder, beta-VAE…

A real result

Example “Iris map”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Iris mapml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins mixed batchesml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
  • Pima beta4 no samplesml_pima · features: npreg, glu, bp, skin, bmi, ped, age
  • Iris vademl_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Penguins vade iwae batchesml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex · label: species
  • Pima iwae normalml_pima · features: npreg, glu, bp, skin, bmi, ped, age
  • Degenerate infml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
  • Degenerate vade n3ml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species

In the guides

Where it sits in the decision guides

  • Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
  • Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels
  • Generative models (GMM, VAEs) · DS & ML Decision Guide · Generate

What you need

Featuresnumeric / categorical / boolean · 2–500 columns
Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Color points bycategorical / boolean · 0–1 column
Optional column used only to color the points; it does not affect the model.

Choices you make

model

Latent dimensionsdefault 2

Coordinates per row in the latent space (2 draws directly as a map).

Encoder layers (units)default 32

Units in each encoder layer, input side first; the decoder mirrors them.

Activationdefault tanh

Nonlinearity in the network's hidden layers.

  • tanh(default) — An S-shaped unit with outputs from −1 to 1; a steady choice for small networks on scaled inputs.
  • ReLU — Passes positive signals and zeroes the rest; trains fast and suits most networks.
  • Sigmoid (logistic) — An S-shaped unit with outputs from 0 to 1; trains slowly in deep networks, so keep it for shallow ones.
KL weight (β)default 1

Weight on the KL term. Above 1 gives a smoother, more disentangled space; below 1 rebuilds rows more sharply.

Epochsdefault 300

Training passes over the data.

Learning ratedefault 0.005

Adam's step size.

Batch sizedefault —

Rows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).

Priordefault normal

The latent space's prior: one standard normal, or a mixture of Gaussians learned with the networks (VaDE), which also clusters the rows.

  • Standard normal N(0, I)(default) — The classic VAE prior; the space is smooth and centerd, with no built-in groups.
  • Gaussian mixture (VaDE) — A mixture of K Gaussians learned with the networks; each row also gets its most likely component, so the map doubles as a clustering.
Mixture components (K)default 3

Gaussian components in the learned prior (clusters the model can find).

Pretraining epochsdefault 100

Epochs trained as a plain VAE first; k-means on those codes then places the mixture components, as in the VaDE paper.

Advanced

L2 penalty (λ)default 0

Adds ½·λ·Σw² over the weight matrices to the loss.

Optimizerdefault default

How the weights are updated. The method's own choice is the usual one.

  • Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
  • Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
  • AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
  • SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
Learning-rate scheduledefault none

How the learning rate changes over training.

  • Constant(default) — The same learning rate every epoch (the method's default).
  • Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
  • Step — Divides the learning rate by 10 after each third of the epochs.
  • One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
  • Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
Warm-up epochsdefault 0

Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.

Gradient clippingdefault 0

Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.

Weight average (EMA)default 0

Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.

Weight average from epoch (SWA)default 0

Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.

Record every stepdefault off

Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.

Compute profiledefault parity

Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.

  • Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
  • Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
  • Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
Checkpoint every (epochs)default —

Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.

options

Rows to generatedefault 500

Decodes this many draws from the prior into new rows (0 = none); saved as an artifact.

Importance-weighted bound drawsdefault 0

Draws per row for the importance-weighted bound on log p(x) (0 = skip); more draws give a tighter bound.

Flag anomalies bydefault share

Flag a fixed share of the most unusual rows, or every row whose loss passes a cutoff.

  • Share of rows (the largest losses)(default) — Flags a set share of rows with the largest losses; pick it when you know how many you can review.
  • Loss cutoff — Flags rows whose loss passes the value you set; pick it when you know a meaningful threshold.
Share flaggeddefault 0.05

Share of rows to flag as anomalies (0.05 flags the most unusual 5%).

Loss cutoffdefault 10

Per-row loss: squared reconstruction error summed over the standardized columns plus β × the row's KL.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Latent dimensions in use

    A dimension whose posterior mean never moves (variance < 0.01) collapsed onto the prior and carries no information.

    • If violated → Plain autoencoder — A deterministic bottleneck cannot collapse onto a prior, so every coordinate carries information about the rows. Changes the question: A map and reconstruction errors without a sampleable latent space (no generated rows).

What it reports

n
How many independent units the analysis used; it sets precision and power.
n_features
How many independent units the analysis used; it sets precision and power.
latent_dim
A compact set of coordinates from which a model can rebuild data; every point decodes to something, realistic or not.
recon_mse
A neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.
kl
How many extra nats it costs to describe draws from one distribution with a code built for another; 0 when they match.
elbo_loss
The quantity a VAE maximizes; minus it is the loss — how badly rows are rebuilt plus how far their codes stray from the prior.
active_dims
Latent dimensions that a VAE stops using; their codes equal the prior for every row, so they carry no information.
error_check
An order-sensitive weighted average of a per-row column, Σ(row + 1)·v / Σ(row + 1), used to compare engines row by row.
n_flagged
How many independent units the analysis used; it sets precision and power.
threshold
The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
final_loss
A neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.
epochs_run
Stopping training when a score on held-back rows has stopped improving for a set number of rounds.
trustworthiness
A 0–1 score for whether rows that look close on a map are really close in the data.
n_samples
Generating new rows by drawing latent codes from N(0, I) and decoding them, which a smooth VAE latent space allows.
sample_ks_mean
Generating new rows by drawing latent codes from N(0, I) and decoding them, which a smooth VAE latent space allows.

Per group, level or term: emb_check[<dim>], kl_dim[<dim>], sample_ks[<feature>], top_row[<rank>], top_score[<rank>], components, n_clusters, pi[<cluster>], cluster_size[<cluster>], iwae_samples, iwae_bound, elbo_estimate, iwae_gap

Python and R

Python and R use different algorithms; results agree in substance (relative tolerance 1e-6). Python uses torch, codesplash; R uses torch, codesplashr.

Default traps between the two languages

  • Lab tier. Both engines run the codesplash twin (codesplash.deep.generative.fit_vae ↔ codesplashr::cs_deep_fit_vae): the same network on LibTorch in double precision on one thread, initial weights and the reparameterization noise ε from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic, the same batch order. Python's and R's torch ship different LibTorch builds, so single kernels can differ by an ulp, which training can amplify; on the fixtures every value agrees to about 1e-12 relative (measured), so the stated band leaves room for other builds.
  • R's torch aliases the memory of R matrices with a dimension of size 1 when it builds a tensor; the R twin copies every tensor it creates so no temporary can be freed under it.
  • The mixture prior and the importance-weighted bound run the codesplash twin codesplash.deep.unsupervised.fit_vade / iwae_bound ↔ codesplashr::cs_deep_fit_vade / cs_deep_iwae_bound: plain-VAE pretraining, k-means++ starts on its codes and the importance draws all come from the shared stream; they agree to about 1e-12 relative on the fixtures. A pretrained code exactly between two k-means centers could start a different component in the two engines; none does on the fixtures.
Python

The exact script CodeSplash ran for example “Iris map” · 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,
})
R

The exact script CodeSplash ran for example “Iris map” · 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
))

Sources

  • Kingma DP, Welling M (2014). Auto-encoding variational Bayes. ICLR 2014.
  • Rezende DJ, Mohamed S, Wierstra D (2014). Stochastic backpropagation and approximate inference in deep generative models. ICML 2014.
  • Higgins I, Matthey L, Pal A, et al. (2017). β-VAE: learning basic visual concepts with a constrained variational framework. ICLR 2017.
  • Burda Y, Grosse R, Salakhutdinov R (2016). Importance weighted autoencoders. ICLR 2016 (active units, the importance-weighted bound).
  • Jiang Z, Zheng Y, Tan H, Tang B, Zhou H (2017). Variational deep embedding: an unsupervised and generative approach to clustering. IJCAI 2017:1965–1972.
  • An J, Cho S (2015). Variational autoencoder based anomaly detection using reconstruction probability. SNU Data Mining Center, Special Lecture on IE 2(1).

From the CodeSplash method registry · discover.vae v1.2.0.