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.
A real result
Example “Iris map”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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
View data
| species | Latent 1 (μ) | Latent 2 (μ) |
|---|---|---|
| setosa | 1.176 | 0.3987 |
| setosa | 1.151 | −0.3919 |
| setosa | 1.291 | −0.1713 |
| setosa | 1.287 | −0.3178 |
| setosa | 1.216 | 0.4858 |
| setosa | 0.9957 | 1.062 |
| setosa | 1.326 | 0.0476 |
| setosa | 1.196 | 0.2171 |
| setosa | 1.299 | −0.6013 |
| setosa | 1.195 | −0.2248 |
| setosa | 1.062 | 0.8139 |
| setosa | 1.261 | 0.1357 |
| setosa | 1.212 | −0.3913 |
| setosa | 1.401 | −0.4933 |
| setosa | 0.9543 | 1.329 |
| setosa | 0.8756 | 1.628 |
| setosa | 1.038 | 1.057 |
| setosa | 1.157 | 0.3926 |
| setosa | 0.9139 | 1.076 |
| setosa | 1.147 | 0.7914 |
| setosa | 1.012 | 0.3939 |
| setosa | 1.132 | 0.6660 |
| setosa | 1.376 | 0.2936 |
| setosa | 1.053 | 0.0777 |
| setosa | 1.232 | 0.1401 |
| setosa | 1.090 | −0.3562 |
| setosa | 1.145 | 0.2015 |
| setosa | 1.129 | 0.4465 |
| setosa | 1.126 | 0.2994 |
| setosa | 1.267 | −0.1591 |
| setosa | 1.205 | −0.2643 |
| setosa | 0.9870 | 0.3600 |
| setosa | 1.113 | 1.155 |
| setosa | 1.005 | 1.393 |
| setosa | 1.175 | −0.2433 |
| setosa | 1.187 | −0.0832 |
| setosa | 1.025 | 0.5760 |
| setosa | 1.268 | 0.4352 |
| setosa | 1.340 | −0.4887 |
| setosa | 1.157 | 0.2596 |
| setosa | 1.203 | 0.3455 |
| setosa | 0.9491 | −1.270 |
| setosa | 1.387 | −0.2521 |
| setosa | 1.109 | 0.3276 |
| setosa | 1.084 | 0.7959 |
| setosa | 1.170 | −0.4365 |
| setosa | 1.155 | 0.7866 |
| setosa | 1.318 | −0.1957 |
| setosa | 1.099 | 0.7653 |
| setosa | 1.191 | 0.0722 |
| versicolor | −0.7822 | 0.5444 |
| versicolor | −0.5493 | 0.3661 |
| versicolor | −0.8450 | 0.3862 |
| versicolor | −0.0362 | −1.121 |
| versicolor | −0.6487 | −0.1629 |
| versicolor | −0.1764 | −0.4722 |
| versicolor | −0.5748 | 0.4935 |
| versicolor | 0.4366 | −1.172 |
| versicolor | −0.5992 | 0.0041 |
| versicolor | 0.1325 | −0.8017 |
First 60 of 150 rows.
View data
| Anomaly | Per-row loss |
|---|---|
| false | 1.315 |
| false | 1.521 |
| false | 1.439 |
| false | 1.607 |
| false | 1.447 |
| false | 2.103 |
| false | 1.513 |
| false | 1.256 |
| false | 2.173 |
| false | 1.447 |
| false | 1.670 |
| false | 1.346 |
| false | 1.629 |
| false | 2.195 |
| false | 3.030 |
| true | 4.902 |
| false | 2.189 |
| false | 1.291 |
| false | 2.056 |
| false | 1.816 |
| false | 1.316 |
| false | 1.577 |
| false | 1.776 |
| false | 1.197 |
| false | 1.390 |
| false | 1.463 |
| false | 1.235 |
| false | 1.315 |
| false | 1.268 |
| false | 1.437 |
| false | 1.440 |
| false | 1.268 |
| false | 3.056 |
| true | 3.605 |
| false | 1.389 |
| false | 1.322 |
| false | 1.514 |
| false | 1.527 |
| false | 1.994 |
| false | 1.245 |
| false | 1.321 |
| true | 4.088 |
| false | 1.772 |
| false | 1.399 |
| false | 1.808 |
| false | 1.546 |
| false | 1.840 |
| false | 1.524 |
| false | 1.625 |
| false | 1.251 |
| false | 1.800 |
| false | 1.094 |
| false | 1.385 |
| false | 1.944 |
| false | 0.9980 |
| false | 0.8023 |
| false | 1.252 |
| false | 2.226 |
| false | 1.176 |
| false | 1.287 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.289 | 1 |
| total | 4.931 | 2 |
| total | 4.907 | 3 |
| total | 4.597 | 4 |
| total | 4.359 | 5 |
| total | 4.254 | 6 |
| total | 4.013 | 7 |
| total | 4.176 | 8 |
| total | 3.925 | 9 |
| total | 3.803 | 10 |
| total | 3.695 | 11 |
| total | 3.666 | 12 |
| total | 3.498 | 13 |
| total | 3.508 | 14 |
| total | 3.288 | 15 |
| total | 3.405 | 16 |
| total | 3.289 | 17 |
| total | 3.099 | 18 |
| total | 3.077 | 19 |
| total | 2.741 | 20 |
| total | 2.695 | 21 |
| total | 2.857 | 22 |
| total | 2.831 | 23 |
| total | 2.777 | 24 |
| total | 2.936 | 25 |
| total | 3.031 | 26 |
| total | 2.904 | 27 |
| total | 2.756 | 28 |
| total | 2.762 | 29 |
| total | 2.678 | 30 |
| total | 2.718 | 31 |
| total | 2.730 | 32 |
| total | 2.485 | 33 |
| total | 2.564 | 34 |
| total | 2.607 | 35 |
| total | 2.527 | 36 |
| total | 2.674 | 37 |
| total | 2.597 | 38 |
| total | 2.680 | 39 |
| total | 2.474 | 40 |
| total | 2.685 | 41 |
| total | 2.623 | 42 |
| total | 2.750 | 43 |
| total | 2.712 | 44 |
| total | 2.497 | 45 |
| total | 2.564 | 46 |
| total | 2.446 | 47 |
| total | 2.577 | 48 |
| total | 2.516 | 49 |
| total | 2.452 | 50 |
| total | 2.507 | 51 |
| total | 2.410 | 52 |
| total | 2.433 | 53 |
| total | 2.332 | 54 |
| total | 2.369 | 55 |
| total | 2.496 | 56 |
| total | 2.520 | 57 |
| total | 2.474 | 58 |
| total | 2.656 | 59 |
| total | 2.405 | 60 |
First 60 of 600 rows.
View data
| Density | Source | sepal_length |
|---|---|---|
| 0.2222 | real | 4.360 |
| 0.0556 | real | 4.480 |
| 0.2222 | real | 4.600 |
| 0.1111 | real | 4.720 |
| 0.2778 | real | 4.840 |
| 0.8889 | real | 4.960 |
| 0.5000 | real | 5.080 |
| 0.2222 | real | 5.200 |
| 0.0556 | real | 5.320 |
| 0.3333 | real | 5.440 |
| 0.7222 | real | 5.560 |
| 0.4444 | real | 5.680 |
| 0.3889 | real | 5.800 |
| 0.1667 | real | 5.920 |
| 0.6667 | real | 6.040 |
| 0.2222 | real | 6.160 |
| 0.5000 | real | 6.280 |
| 0.3889 | real | 6.400 |
| 0.2778 | real | 6.520 |
| 0.1111 | real | 6.640 |
| 0.6111 | real | 6.760 |
| 0.2222 | real | 6.880 |
| 0.0556 | real | 7 |
| 0.0556 | real | 7.120 |
| 0.2222 | real | 7.240 |
| 0.0556 | real | 7.360 |
| 0 | real | 7.480 |
| 0.0556 | real | 7.600 |
| 0.2222 | real | 7.720 |
| 0.0556 | real | 7.840 |
| 0 | synthetic | 4.360 |
| 0.0556 | synthetic | 4.480 |
| 0.1111 | synthetic | 4.600 |
| 0.2778 | synthetic | 4.720 |
| 0.4444 | synthetic | 4.840 |
| 0.3333 | synthetic | 4.960 |
| 0.3889 | synthetic | 5.080 |
| 0.3333 | synthetic | 5.200 |
| 0.6111 | synthetic | 5.320 |
| 0.2778 | synthetic | 5.440 |
| 0.5000 | synthetic | 5.560 |
| 0.5000 | synthetic | 5.680 |
| 0.6111 | synthetic | 5.800 |
| 0.3889 | synthetic | 5.920 |
| 0.3333 | synthetic | 6.040 |
| 0.4444 | synthetic | 6.160 |
| 0.6111 | synthetic | 6.280 |
| 0.5000 | synthetic | 6.400 |
| 0.4444 | synthetic | 6.520 |
| 0.4444 | synthetic | 6.640 |
| 0.4444 | synthetic | 6.760 |
| 0.1667 | synthetic | 6.880 |
| 0.1111 | synthetic | 7 |
| 0 | synthetic | 7.120 |
| 0 | synthetic | 7.240 |
| 0 | synthetic | 7.360 |
| 0 | synthetic | 7.480 |
| 0 | synthetic | 7.600 |
| 0 | synthetic | 7.720 |
| 0 | synthetic | 7.840 |
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
A variational autoencoder mapped 150 rows into 2 latent coordinates (2 in use); the mean squared reconstruction error is 0.133 per standardized column and the mean KL is 1.11 nats; 8 rows with a loss of at least 3.53 are flagged as anomalies. 150 rows generated from the prior differ from the data by a mean KS distance of 0.160.
- Mean reconstruction error
- 0.1330
- Mean KL (nats per row)
- 1.110
- Active latent dimensions
- 2
- Trustworthiness (k = 10)
- 0.9773
- Anomalies
- 8
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Latent dimensions in use — 2 of 2 latent dimensions vary across rows (variance of μ > 0.01).
Rows the model finds least typical
| Rank | Row | Per-row loss | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|
| 1 | 132 | 5.870 | 7.900 | 3.800 | 6.400 | 2 |
| 2 | 118 | 5.550 | 7.700 | 3.800 | 6.700 | 2.200 |
| 3 | 16 | 4.902 | 5.700 | 4.400 | 1.500 | 0.4000 |
| 4 | 119 | 4.342 | 7.700 | 2.600 | 6.900 | 2.300 |
| 5 | 42 | 4.088 | 4.500 | 2.300 | 1.300 | 0.3000 |
| 6 | 61 | 3.918 | 5 | 2 | 3.500 | 1 |
| 7 | 34 | 3.605 | 5.500 | 4.200 | 1.400 | 0.2000 |
| 8 | 110 | 3.530 | 7.200 | 3.600 | 6.100 | 2.500 |
| 9 | 123 | 3.279 | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 33 | 3.056 | 5.200 | 4.100 | 1.500 | 0.1000 |
| 11 | 15 | 3.030 | 5.800 | 4 | 1.200 | 0.2000 |
| 12 | 136 | 2.754 | 7.700 | 3 | 6.100 | 2.300 |
| 13 | 63 | 2.688 | 6 | 2.200 | 4 | 1 |
| 14 | 106 | 2.661 | 7.600 | 3 | 6.600 | 2.100 |
| 15 | 69 | 2.616 | 6.200 | 2.200 | 4.500 | 1.500 |
| 16 | 120 | 2.555 | 6 | 2.200 | 5 | 1.500 |
| 17 | 107 | 2.491 | 4.900 | 2.500 | 4.500 | 1.700 |
| 18 | 94 | 2.426 | 5 | 2.300 | 3.300 | 1 |
| 19 | 137 | 2.333 | 6.300 | 3.400 | 5.600 | 2.400 |
| 20 | 101 | 2.324 | 6.300 | 3.300 | 6 | 2.500 |
Latent dimensions
| Dimension | Mean KL (nats) | Variance of μ | Active |
|---|---|---|---|
| 1 | 0.8634 | 0.8815 | yes |
| 2 | 0.2468 | 0.3660 | yes |
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.
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,
})
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.