CDiscover · discover.dagmm
Deep autoencoding Gaussian mixture (DAGMM)
Which rows are either rebuilt badly by a compressing network or unlikely under the density it learns?
DAGMM trains three parts together: an autoencoder that compresses each row to a few latent coordinates, two features that measure how well the row is rebuilt (relative distance and cosine similarity), and an estimation network that assigns the row softly to K Gaussian components fitted in that space. Each row's anomaly score is its sample energy, the negative log density of the mixture, so a row scores high when it is poorly reconstructed, lands where the mixture is thin, or both. A penalty on small covariance diagonals keeps components from collapsing. Lab tier: trained by Adam on torch in both engines from the same initial weights and batch order.
A real result
Example “Iris defaults”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
8 of 150 rows (5.3%) are flagged as anomalies (Sample energy ≥ 3.64). DAGMM compressed 4 design columns to 2 latent coordinates plus two reconstruction features and fitted 3 mixture components; the mean energy is 1.05.
- Anomalies
- 8
- Threshold
- 3.637
- Mean energy
- 1.046
- Mean reconstruction error
- 0.5835
Plots
View data
| Anomaly | Sample energy |
|---|---|
| false | 1.355 |
| false | 0.3882 |
| false | 0.5838 |
| false | 0.5362 |
| false | 1.090 |
| false | 1.018 |
| false | 0.5500 |
| false | 0.9782 |
| false | 0.8322 |
| false | 0.3850 |
| false | 0.8010 |
| false | 0.7156 |
| false | 0.4746 |
| false | 0.7779 |
| false | 2.471 |
| true | 4.406 |
| false | 1.025 |
| false | 1.267 |
| false | 1.268 |
| false | 0.7262 |
| false | 0.3315 |
| false | 0.7034 |
| false | 0.6394 |
| false | 0.3079 |
| false | 0.4346 |
| false | 0.2830 |
| false | 0.4231 |
| false | 0.8658 |
| false | 0.5744 |
| false | 0.4979 |
| false | 0.4360 |
| false | 0.2826 |
| false | 1.978 |
| false | 2.880 |
| false | 0.3790 |
| false | 0.4072 |
| false | 0.5265 |
| false | 0.8515 |
| false | 0.7052 |
| false | 0.7788 |
| false | 1.330 |
| false | 2.007 |
| false | 0.5829 |
| false | 0.3804 |
| false | 0.6820 |
| false | 0.4555 |
| false | 0.7482 |
| false | 0.5520 |
| false | 0.8150 |
| false | 0.6555 |
| false | 1.212 |
| false | −0.0453 |
| false | 0.3946 |
| false | 1.423 |
| false | −0.1731 |
| false | 0.5870 |
| false | 0.3561 |
| false | 1.884 |
| false | 1.034 |
| false | 2.139 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 5.753 | 1 |
| total | 5.292 | 2 |
| total | 4.986 | 3 |
| total | 4.779 | 4 |
| total | 4.630 | 5 |
| total | 4.515 | 6 |
| total | 4.420 | 7 |
| total | 4.337 | 8 |
| total | 4.260 | 9 |
| total | 4.187 | 10 |
| total | 4.115 | 11 |
| total | 4.045 | 12 |
| total | 3.974 | 13 |
| total | 3.902 | 14 |
| total | 3.829 | 15 |
| total | 3.756 | 16 |
| total | 3.680 | 17 |
| total | 3.604 | 18 |
| total | 3.526 | 19 |
| total | 3.447 | 20 |
| total | 3.366 | 21 |
| total | 3.285 | 22 |
| total | 3.202 | 23 |
| total | 3.119 | 24 |
| total | 3.035 | 25 |
| total | 2.951 | 26 |
| total | 2.866 | 27 |
| total | 2.782 | 28 |
| total | 2.699 | 29 |
| total | 2.616 | 30 |
| total | 2.535 | 31 |
| total | 2.456 | 32 |
| total | 2.379 | 33 |
| total | 2.305 | 34 |
| total | 2.234 | 35 |
| total | 2.166 | 36 |
| total | 2.101 | 37 |
| total | 2.040 | 38 |
| total | 1.982 | 39 |
| total | 1.928 | 40 |
| total | 1.878 | 41 |
| total | 1.831 | 42 |
| total | 1.787 | 43 |
| total | 1.747 | 44 |
| total | 1.709 | 45 |
| total | 1.674 | 46 |
| total | 1.641 | 47 |
| total | 1.611 | 48 |
| total | 1.582 | 49 |
| total | 1.556 | 50 |
| total | 1.530 | 51 |
| total | 1.507 | 52 |
| total | 1.484 | 53 |
| total | 1.463 | 54 |
| total | 1.442 | 55 |
| total | 1.423 | 56 |
| total | 1.404 | 57 |
| total | 1.385 | 58 |
| total | 1.367 | 59 |
| total | 1.350 | 60 |
First 60 of 320 rows.
Assumptions
- Mixture covariances well conditioned — The smallest eigenvalue of the component covariances is 0.00497.
Most anomalous rows
| Rank | Row | Sample energy | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 67 | 9.532 | sepal_length = 5.6 (robust z -0.2); 28% of its tail score | sepal_length: falls 6.86 at its median | 5.600 | 3 | 4.500 | 1.500 |
| 2 | 65 | 9.305 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 5.51 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 3 | 89 | 8.195 | sepal_length = 5.6 (robust z -0.2); 29% of its tail score | petal_length: falls 1.85 at its median | 5.600 | 3 | 4.100 | 1.300 |
| 4 | 96 | 8.128 | sepal_length = 5.7 (robust z -0.1); 25% of its tail score | petal_length: falls 1.84 at its median | 5.700 | 3 | 4.200 | 1.200 |
| 5 | 85 | 6.855 | sepal_length = 5.4 (robust z -0.4); 33% of its tail score | sepal_length: falls 4.18 at its median | 5.400 | 3 | 4.500 | 1.500 |
| 6 | 16 | 4.406 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | sepal_width: falls 3.38 at its median | 5.700 | 4.400 | 1.500 | 0.4000 |
| 7 | 132 | 3.720 | sepal_length = 7.9 (robust z +2.0); 40% of its tail score | sepal_width: falls 2.93 at its median | 7.900 | 3.800 | 6.400 | 2 |
| 8 | 97 | 3.637 | sepal_width = 2.9 (robust z -0.2); 32% of its tail score | sepal_length: falls 0.929 at its median | 5.700 | 2.900 | 4.200 | 1.300 |
| 9 | 118 | 3.386 | sepal_length = 7.7 (robust z +1.8); 28% of its tail score | sepal_width: falls 2.7 at its median | 7.700 | 3.800 | 6.700 | 2.200 |
| 10 | 34 | 2.880 | sepal_width = 4.2 (robust z +2.7); 50% of its tail score | sepal_width: falls 2.55 at its median | 5.500 | 4.200 | 1.400 | 0.2000 |
| 11 | 61 | 2.766 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.574 at its median | 5 | 2 | 3.500 | 1 |
| 12 | 113 | 2.561 | sepal_length = 6.8 (robust z +1.0); 33% of its tail score | sepal_length: falls 2.48 at its median | 6.800 | 3 | 5.500 | 2.100 |
| 13 | 15 | 2.471 | sepal_width = 4 (robust z +2.2); 39% of its tail score | sepal_width: falls 1.58 at its median | 5.800 | 4 | 1.200 | 0.2000 |
| 14 | 140 | 2.351 | sepal_length = 6.9 (robust z +1.1); 34% of its tail score | sepal_length: falls 2.18 at its median | 6.900 | 3.100 | 5.400 | 2.100 |
| 15 | 107 | 2.282 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 1.69 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 16 | 60 | 2.139 | sepal_width = 2.7 (robust z -0.7); 35% of its tail score | sepal_length: falls 2.11 at its median | 5.200 | 2.700 | 3.900 | 1.400 |
| 17 | 94 | 2.010 | sepal_width = 2.3 (robust z -1.6); 45% of its tail score | sepal_length: falls 0.882 at its median | 5 | 2.300 | 3.300 | 1 |
| 18 | 42 | 2.007 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 1.36 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 19 | 33 | 1.978 | sepal_width = 4.1 (robust z +2.5); 39% of its tail score | sepal_width: falls 1.85 at its median | 5.200 | 4.100 | 1.500 | 0.1000 |
| 20 | 58 | 1.884 | sepal_width = 2.4 (robust z -1.3); 40% of its tail score | sepal_length: falls 1.11 at its median | 4.900 | 2.400 | 3.300 | 1 |
8 of 150 rows (5.3%) are flagged as anomalies (Sample energy ≥ 3.64). DAGMM compressed 4 design columns to 2 latent coordinates plus two reconstruction features and fitted 3 mixture components; the mean energy is 1.05.
- Anomalies
- 8
- Threshold
- 3.637
- Mean energy
- 1.046
- Mean reconstruction error
- 0.5835
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Mixture covariances well conditioned — The smallest eigenvalue of the component covariances is 0.00497.
Most anomalous rows
| Rank | Row | Sample energy | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 67 | 9.532 | sepal_length = 5.6 (robust z -0.2); 28% of its tail score | sepal_length: falls 6.86 at its median | 5.600 | 3 | 4.500 | 1.500 |
| 2 | 65 | 9.305 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 5.51 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 3 | 89 | 8.195 | sepal_length = 5.6 (robust z -0.2); 29% of its tail score | petal_length: falls 1.85 at its median | 5.600 | 3 | 4.100 | 1.300 |
| 4 | 96 | 8.128 | sepal_length = 5.7 (robust z -0.1); 25% of its tail score | petal_length: falls 1.84 at its median | 5.700 | 3 | 4.200 | 1.200 |
| 5 | 85 | 6.855 | sepal_length = 5.4 (robust z -0.4); 33% of its tail score | sepal_length: falls 4.18 at its median | 5.400 | 3 | 4.500 | 1.500 |
| 6 | 16 | 4.406 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | sepal_width: falls 3.38 at its median | 5.700 | 4.400 | 1.500 | 0.4000 |
| 7 | 132 | 3.720 | sepal_length = 7.9 (robust z +2.0); 40% of its tail score | sepal_width: falls 2.93 at its median | 7.900 | 3.800 | 6.400 | 2 |
| 8 | 97 | 3.637 | sepal_width = 2.9 (robust z -0.2); 32% of its tail score | sepal_length: falls 0.929 at its median | 5.700 | 2.900 | 4.200 | 1.300 |
| 9 | 118 | 3.386 | sepal_length = 7.7 (robust z +1.8); 28% of its tail score | sepal_width: falls 2.7 at its median | 7.700 | 3.800 | 6.700 | 2.200 |
| 10 | 34 | 2.880 | sepal_width = 4.2 (robust z +2.7); 50% of its tail score | sepal_width: falls 2.55 at its median | 5.500 | 4.200 | 1.400 | 0.2000 |
| 11 | 61 | 2.766 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.574 at its median | 5 | 2 | 3.500 | 1 |
| 12 | 113 | 2.561 | sepal_length = 6.8 (robust z +1.0); 33% of its tail score | sepal_length: falls 2.48 at its median | 6.800 | 3 | 5.500 | 2.100 |
| 13 | 15 | 2.471 | sepal_width = 4 (robust z +2.2); 39% of its tail score | sepal_width: falls 1.58 at its median | 5.800 | 4 | 1.200 | 0.2000 |
| 14 | 140 | 2.351 | sepal_length = 6.9 (robust z +1.1); 34% of its tail score | sepal_length: falls 2.18 at its median | 6.900 | 3.100 | 5.400 | 2.100 |
| 15 | 107 | 2.282 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 1.69 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 16 | 60 | 2.139 | sepal_width = 2.7 (robust z -0.7); 35% of its tail score | sepal_length: falls 2.11 at its median | 5.200 | 2.700 | 3.900 | 1.400 |
| 17 | 94 | 2.010 | sepal_width = 2.3 (robust z -1.6); 45% of its tail score | sepal_length: falls 0.882 at its median | 5 | 2.300 | 3.300 | 1 |
| 18 | 42 | 2.007 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 1.36 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 19 | 33 | 1.978 | sepal_width = 4.1 (robust z +2.5); 39% of its tail score | sepal_width: falls 1.85 at its median | 5.200 | 4.100 | 1.500 | 0.1000 |
| 20 | 58 | 1.884 | sepal_width = 2.4 (robust z -1.3); 40% of its tail score | sepal_length: falls 1.11 at its median | 4.900 | 2.400 | 3.300 | 1 |
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 defaultsml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Penguins mixed batchesml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex
- Pima relu k2ml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Degenerate n3ml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Degenerate infml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Invalid batch one row leftml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex
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
What you need
- Featuresnumeric / categorical / boolean · 2–500 columns
- Columns used to describe each row. Numbers are standardized (median-filled); categories become indicator columns.
Choices you make
model
- Encoder layers (units)default 16
Units in each encoder layer, input side first; the decoder mirrors them.
- Latent dimensionsdefault 2
Coordinates the autoencoder compresses each row to (the paper used 1 to 3).
- Mixture components (K)default 3
Gaussian components the estimation network assigns rows to.
- Activationdefault tanh
Nonlinearity in the autoencoder's hidden layers.
- tanh(default) — An S-shaped unit with outputs from −1 to 1; the paper's choice and steady 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.
- Energy weight (λ₁)default 0.1
Weight on the mean sample energy in the loss (the paper's 0.1).
- Covariance penalty (λ₂)default 0.005
Weight on the sum of inverse covariance diagonals; raise it if a component collapses.
- Epochsdefault 200
Training passes over the data.
- Learning ratedefault 0.005
Adam's step size.
- Batch sizedefault —
Rows per gradient step; the mixture is estimated from each batch, so keep batches large. Batches follow a seeded shuffle (the same in Python and R).
Advanced
- Estimation network unitsdefault 10
Units in the estimation network's one tanh hidden layer.
- L2 penalty (λ)default 0
Adds ½·λ·Σw² over the autoencoder's 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
- Flag anomalies bydefault share
Flag a fixed share of the most unusual rows, or every row whose energy passes a cutoff.
- Share of rows (the largest energies)(default) — Flags a set share of rows with the largest energies; pick it when you know how many you can review.
- Energy cutoff — Flags rows whose energy 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%).
- Energy cutoffdefault 10
Sample energy (negative log density of the mixture) at which a row is flagged.
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.
Mixture covariances well conditioned
Smallest eigenvalue of the component covariances; near 0 means a component collapsed and its energies are unstable.
- If violated → Variational autoencoder — The VAE scores rows by reconstruction plus a KL term against a fixed prior, with no mixture covariance to collapse. Changes the question: A per-row loss under a single N(0, I) prior instead of a mixture energy.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- 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.
- score_check
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_max
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_mean
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- 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.
- components
- An autoencoder and a Gaussian mixture trained together; a row's anomaly score is its energy under the mixture.
- recon_mean
- An autoencoder and a Gaussian mixture trained together; a row's anomaly score is its energy under the mixture.
- energy_mean
- Minus the log density of a row under the fitted Gaussian mixture; higher means the row is less likely.
- cov_penalty
- How far a mixture component's covariance is from flat; a smallest eigenvalue near 0 means it collapsed onto a line or point.
- min_eigenvalue
- How far a mixture component's covariance is from flat; a smallest eigenvalue near 0 means it collapsed onto a line or point.
- 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.
Per group, level or term: weight[<component>], top_row[<rank>], top_score[<rank>], why_feature[<rank>], why_z[<rank>], why_share[<rank>], drop_feature[<rank>], drop_score[<rank>]
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-5). Python uses torch, codesplash; R uses torch, codesplashr.
Default traps between the two languages
- Lab tier. Both engines run the codesplash twin (codesplash.deep.unsupervised.fit_dagmm ↔ codesplashr::cs_deep_fit_dagmm): the same networks on LibTorch in double precision on one thread, initial weights from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic and the same batch order. The energy inverts each component's covariance, so an ulp of difference in a covariance entry (the two torch builds sum in different orders) is multiplied by the covariance's condition number, hence the looser band. On the fixtures the engines agree to about 2e-14 relative (since 2.0.0; before it, R rounded each component's log-determinant term to single precision, which left the energies about 1e-8 apart after one epoch and the values within about 2e-6 at the end).
- The paper's dropout in the estimation network is left out so both engines stay deterministic.
The exact script CodeSplash ran for example “Iris defaults” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep autoencoding Gaussian mixture (DAGMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dagmm 2.0.1 · spec 32a0c79b6e88b61c
# 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 unsupervised as du # twin of codesplashr::cs_deep_fit_dagmm (shared initial weights, Adam written out)
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed
# %% 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.dagmm/iris_defaults/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))
LATENT = 2
K = 3
MIN_ROWS = K + LATENT + 3 # each component's covariance over latent + 2 features needs rows to spread over
if len(rows) < MIN_ROWS:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="DAGMM", min=MIN_ROWS, n=len(rows))
# %% DAGMM (PyTorch, float64, one thread): compression autoencoder + estimation network + Gaussian-mixture energy
fit = du.fit_dagmm(
X, [int(u) for u in [8]], LATENT, K,
est_hidden=10,
activation="tanh",
lambda_energy=0.1,
lambda_cov=0.005,
epochs=80,
lr=0.005,
batch_size=None,
weight_decay=0,
seed=42,
)
scores = fit["score"] # sample energy under the mixture re-estimated from every row
if not np.all(np.isfinite(scores)):
cs.cs_error("CS_E_NO_CONVERGENCE", what="DAGMM training")
SCORE_LABEL = "Sample energy"
ENGINE_PACKAGES = ("torch", "numpy", "pandas")
rescore = lambda Q, where, col: du.dagmm_score(fit, Q) # the trained networks and mixture, no refit
# %% Checks and values
phi = fit["phi"]
by_weight = np.lexsort((np.arange(K), -phi)) # components numbered by weight, largest first
extra_values = {
"n_features": int(X.shape[1]),
"latent_dim": LATENT,
"components": K,
"recon_mean": float(np.mean(fit["recon_row"])),
"energy_mean": float(np.mean(scores)),
"cov_penalty": float(fit["cov_penalty"]),
"min_eigenvalue": float(fit["min_eig"]),
"final_loss": float(fit["history"][-1]["loss"]),
"epochs_run": int(fit["epochs_run"]),
}
for rank, j in enumerate(by_weight, start=1):
extra_values[f"weight[{rank}]"] = float(phi[j])
extra_stats = [
{"key": "energy_mean", "label": "Mean energy", "value": float(np.mean(scores))},
{"key": "recon_mean", "label": "Mean reconstruction error", "value": float(np.mean(fit["recon_row"]))},
]
ev = float(fit["min_eig"])
status = "pass" if ev >= 1e-4 else ("fail" if ev < 2e-6 else "warn")
assumptions = [{
"key": "covariance_conditioning",
"label": "Mixture covariances well conditioned",
"status": status,
"detail": f"The smallest eigenvalue of the component covariances is {ev:.3g}"
+ ("." if status == "pass" else "; a component has nearly collapsed onto a line or point, so its energies are unstable."),
}]
if status != "pass":
warnings.append("A mixture component nearly collapsed. Raise the covariance penalty (λ₂), use fewer components or train for fewer epochs.")
EPOCHS = [h["epoch"] for h in fit["history"]]
PARTS = [
("total", [h["loss"] for h in fit["history"]]),
("reconstruction", [h["recon"] for h in fit["history"]]),
("energy", [h["energy"] for h in fit["history"]]),
("covariance penalty", [h["cov_penalty"] for h in fit["history"]]),
]
summary_tail = (
f" DAGMM compressed {int(X.shape[1])} design columns to {LATENT} latent coordinate{'s' if LATENT != 1 else ''} plus two reconstruction "
f"features and fitted {K} mixture components; the mean energy is {np.mean(scores):.3g}."
)
# %% Flag anomalies
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 10)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.dagmm/iris_defaults/out-python")
pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags}).to_parquet(os.path.join(out, "labels.parquet"), index=False)
pd.DataFrame({"epoch": np.asarray(EPOCHS, dtype=np.int64), **{part: np.asarray(v, dtype=np.float64) for part, v in PARTS}}).to_parquet(
os.path.join(out, "history.parquet"), index=False
)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
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])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share, as the other detectors)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["sepal_length", "sepal_width", "petal_length", "petal_width", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
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)
_names = [part for part, _ in PARTS]
charts = [
cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)}),
cs.chart("training", "training-components", "Training loss by epoch", {
"x": cs.col("Epoch", list(EPOCHS) * len(PARTS), "numeric"),
"value": cs.col("Loss per row", [float(x) for _, v in PARTS for x in v], "numeric"),
"component": cs.col("Part", [part for part, v in PARTS for _ in v], "categorical", levels=_names),
}),
]
cs.publish({
"title": "Deep autoencoding Gaussian mixture (DAGMM)",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({flags.mean():.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g})." + summary_tail,
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
] + extra_stats,
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": charts,
"assumptions": assumptions,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"},
{"key": "history", "path": os.path.join(out, "history.parquet"), "format": "parquet"},
],
})
The exact script CodeSplash ran for example “Iris defaults” · R version 4.5.1 (2025-06-13)
# Deep autoencoding Gaussian mixture (DAGMM)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.dagmm 2.0.1 · spec 32a0c79b6e88b61c
# 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_dagmm: torch DAGMM with shared initial weights (twin of codesplash.deep.unsupervised)
# %% 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.dagmm/iris_defaults/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
LATENT <- as.integer(2)
K <- as.integer(3)
MIN_ROWS <- K + LATENT + 3L # each component's covariance over latent + 2 features needs rows to spread over
if (length(rows) < MIN_ROWS) cs_error("CS_E_TOO_FEW_ROWS", what = "DAGMM", min = MIN_ROWS, n = length(rows))
# %% DAGMM (torch for R, float64, one thread): compression autoencoder + estimation network + Gaussian-mixture energy
fit <- cs_deep_fit_dagmm(
X, as.integer(unlist(c(8))), LATENT, K,
est_hidden = as.integer(10),
activation = "tanh",
lambda_energy = 0.1,
lambda_cov = 0.005,
epochs = as.integer(80),
lr = 0.005,
batch_size = NULL,
weight_decay = 0,
seed = 42
)
scores <- fit$score # sample energy under the mixture re-estimated from every row
if (any(!is.finite(scores))) cs_error("CS_E_NO_CONVERGENCE", what = "DAGMM training")
SCORE_LABEL <- "Sample energy"
ENGINE_PACKAGES <- c("torch", "nanoparquet")
rescore <- function(Q, where0, col0) cs_deep_dagmm_score(fit, Q) # the trained networks and mixture, no refit
# %% Checks and values
phi <- fit$phi
by_weight <- order(-phi, seq_len(K)) # components numbered by weight, largest first
extra_values <- list(
n_features = ncol(X), latent_dim = LATENT, components = K, recon_mean = mean(fit$recon_row), energy_mean = mean(scores),
cov_penalty = fit$cov_penalty, min_eigenvalue = fit$min_eig, final_loss = fit$history[[length(fit$history)]]$loss,
epochs_run = fit$epochs_run
)
for (rank in seq_along(by_weight)) extra_values[[sprintf("weight[%d]", rank)]] <- phi[by_weight[rank]]
extra_stats <- list(list(key = "energy_mean", label = "Mean energy", value = mean(scores)),
list(key = "recon_mean", label = "Mean reconstruction error", value = mean(fit$recon_row)))
ev <- fit$min_eig
status <- if (ev >= 1e-4) "pass" else if (ev < 2e-6) "fail" else "warn"
assumptions <- list(list(
key = "covariance_conditioning", label = "Mixture covariances well conditioned", status = status,
detail = paste0(sprintf("The smallest eigenvalue of the component covariances is %s", format(signif(ev, 3))),
if (status == "pass") "." else "; a component has nearly collapsed onto a line or point, so its energies are unstable.")
))
if (status != "pass") {
warnings <- c(warnings, "A mixture component nearly collapsed. Raise the covariance penalty (λ₂), use fewer components or train for fewer epochs.")
}
EPOCHS <- vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1))
PARTS <- list(
total = vapply(fit$history, function(h) h$loss, numeric(1)),
reconstruction = vapply(fit$history, function(h) h$recon, numeric(1)),
energy = vapply(fit$history, function(h) h$energy, numeric(1)),
`covariance penalty` = vapply(fit$history, function(h) h$cov_penalty, numeric(1))
)
summary_tail <- sprintf(" DAGMM compressed %d design columns to %d latent coordinate%s plus two reconstruction features and fitted %d mixture components; the mean energy is %s.",
ncol(X), LATENT, if (LATENT != 1L) "s" else "", K, format(signif(mean(scores), 3)))
# %% Flag anomalies
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 10)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.dagmm/iris_defaults/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
hist_ <- data.frame(epoch = as.integer(EPOCHS))
for (part in names(PARTS)) hist_[[part]] <- as.numeric(PARTS[[part]])
nanoparquet::write_parquet(hist_, file.path(out, "history.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
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)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share, as the other detectors)
NUMERIC <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
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
})
ne_ <- length(EPOCHS)
charts <- list(
cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold)),
cs_chart("training", "training-components", "Training loss by epoch", list(
x = cs_col("Epoch", rep(as.numeric(EPOCHS), length(PARTS)), "numeric"),
value = cs_col("Loss per row", unlist(lapply(PARTS, as.numeric), use.names = FALSE), "numeric"),
component = cs_col("Part", rep(names(PARTS), each = ne_), "categorical", levels = names(PARTS))
))
)
cs_publish(list(
title = "Deep autoencoding Gaussian mixture (DAGMM)",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = paste0(sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))), summary_tail),
statistics = c(list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)), extra_stats),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = charts,
assumptions = assumptions,
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"),
list(key = "history", path = file.path(out, "history.parquet"), format = "parquet"))
))
Sources
- Zong B, Song Q, Min MR, Cheng W, Lumezanu C, Cho D, Chen H (2018). Deep autoencoding Gaussian mixture model for unsupervised anomaly detection. ICLR 2018.
From the CodeSplash method registry · discover.dagmm v2.0.1.