Skip to content

Deep anomaly detectors: Deep SVDD and DAGMM

Two Experimental detectors learn what typical rows look like. Deep SVDD pulls them toward one point; DAGMM scores rows by a mixture density over a compressed space. What each optimizes, how each fails, how to check it.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Explain why Deep SVDD's network has no bias terms and what collapse looks like
  • Explain the three parts of DAGMM's loss and what its energy measures
  • Check a deep detector against a shallow baseline before trusting its alerts

Read first

01

Learning what "typical" means

Read

Isolation forest and LOF score rows with fixed rules. A deep detector instead trains a network on the rows and lets it decide which differences matter. That buys flexibility on wide data, and it costs you a model that can fail quietly. Both methods here are Experimental: trained the same way in Python and R, but newer and less tested than the classic detectors.

02

Deep SVDD: pull everything toward one point

Read

Deep SVDDDeep SVDDA network trained to map typical rows close to one fixed center; a row's squared distance to it is its anomaly score. trains a network φ to map every row close to a fixed center c. The rows the network can't bring close are the unusual ones, and the score is the squared distance ‖φ(x) − c‖².

Deep SVDD (one-class neural anomaly detection)Recorded · Python and R agreeRecorded 2026-11-25 · 84 values compared
R

8 of 150 rows (5.3%) are flagged as anomalies (Squared distance to the center ≥ 0.644). Deep SVDD (one-class) mapped 4 design columns to 4 coordinates; the median squared distance to the center is 0.0457.

Anomalies
8
Threshold
0.6437
Spread kept by the representation
0.0638

Plots

Squared distance to the center distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalySquared distance to the center
false0.0036
false0.0275
false0.0009
false0.0053
false0.0119
false0.0358
false0.0045
false0.0016
false0.0547
false0.0100
false0.0073
false0.0007
false0.0112
false0.0301
false0.0155
false0.1022
false0.0071
false0.0038
false0.0318
false0.0072
false0.0164
false0.0075
false0.0757
false0.0467
false0.0071
false0.0570
false0.0120
false0.0031
false0.0032
false0.0044
false0.0165
false0.0204
false0.0077
false0.0157
false0.0152
false0.0009
false0.0036
false0.0209
false0.0080
false0.0032
false0.0050
false0.3751
false0.0078
false0.0186
false0.0258
false0.0217
false0.0108
false0.0011
false0.0113
false0.0016
false0.2019
false0.4550
false0.2097
false0.0230
false0.1838
false0.2621
false0.4600
false0.1245
false0.3448
false0.0263

First 60 of 150 rows.

Training loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total2.1971
total1.9362
total1.7033
total1.4984
total1.3195
total1.1656
total1.0327
total0.91958
total0.82479
total0.745110
total0.679111
total0.624412
total0.578913
total0.540914
total0.509215
total0.481716
total0.457517
total0.435718
total0.415919
total0.397820
total0.381221
total0.365822
total0.351823
total0.339124
total0.327625
total0.317326
total0.308027
total0.299528
total0.291929
total0.284830
total0.278231
total0.272032
total0.266133
total0.260634
total0.255435
total0.250636
total0.246037
total0.241938
total0.238139
total0.234740
total0.231641
total0.228842
total0.226343
total0.223944
total0.221645
total0.219446
total0.217247
total0.215148
total0.213049
total0.210850
total0.208751
total0.206652
total0.204553
total0.202454
total0.200455
total0.198456
total0.196557
total0.194658
total0.192859
total0.191160

First 60 of 100 rows.

Assumptions

  • Representation keeps its spread — The representation keeps 0.0638 of its starting spread across rows.

Most anomalous rows

RankRowSquared distance to the centerMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
11191.232sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.84 at its median7.7002.6006.9002.300
2960.8214sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_width: falls 0.114 at its median5.70034.2001.200
3860.7867sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.364 at its median63.4004.5001.600
4890.7487sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 0.152 at its median5.60034.1001.300
5720.7372sepal_width = 2.8 (robust z -0.4); 33% of its tail scorepetal_length: falls 0.305 at its median6.1002.80041.300
6710.7050petal_width = 1.8 (robust z +0.5); 30% of its tail scoresepal_width: falls 0.505 at its median5.9003.2004.8001.800
7650.6442petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.26 at its median5.6002.9003.6001.300
8620.6437petal_width = 1.5 (robust z +0.2); 29% of its tail scorepetal_length: falls 0.117 at its median5.90034.2001.500
9610.6316sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.61 at its median523.5001
10760.6112sepal_length = 6.6 (robust z +0.8); 44% of its tail scoresepal_length: falls 0.0852 at its median6.60034.4001.400
11970.5335sepal_width = 2.9 (robust z -0.2); 32% of its tail scorepetal_length: falls 0.0996 at its median5.7002.9004.2001.300
12750.5309sepal_length = 6.4 (robust z +0.6); 35% of its tail scorepetal_length: falls 0.0379 at its median6.4002.9004.3001.300
13980.5077sepal_length = 6.2 (robust z +0.4); 30% of its tail scorepetal_length: falls 0.036 at its median6.2002.9004.3001.300
141230.4815sepal_length = 7.7 (robust z +1.8); 34% of its tail scoresepal_width: falls 0.256 at its median7.7002.8006.7002
15660.4673sepal_length = 6.7 (robust z +0.9); 43% of its tail scoreno single feature lowers it6.7003.1004.4001.400
16570.4600sepal_width = 3.3 (robust z +0.7); 29% of its tail scoresepal_width: falls 0.136 at its median6.3003.3004.7001.600
17520.4550sepal_length = 6.4 (robust z +0.6); 33% of its tail scoreno single feature lowers it6.4003.2004.5001.500
181000.4543sepal_width = 2.8 (robust z -0.4); 35% of its tail scorepetal_length: falls 0.113 at its median5.7002.8004.1001.300
19830.4527sepal_width = 2.7 (robust z -0.7); 39% of its tail scorepetal_length: falls 0.101 at its median5.8002.7003.9001.200
20920.4350sepal_length = 6.1 (robust z +0.3); 29% of its tail scoresepal_length: falls 0.0209 at its median6.10034.6001.400
The exact R script · R R version 4.5.1 (2025-06-13)
# Deep SVDD (one-class neural anomaly detection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.deep_svdd 1.1.0 · spec a3a7e8a388ec63db
# 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_svdd: torch Deep SVDD 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.deep_svdd/iris_one_class/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

# %% Deep SVDD (torch for R, float64, one thread): a bias-free network phi pulls the rows toward a fixed center c
OBJECTIVE <- "one_class"
fit <- cs_deep_fit_svdd(
  X, as.integer(unlist(c(8))), 4,
  activation = "relu",
  objective = OBJECTIVE,
  nu = 0.1,
  epochs = as.integer(100),
  lr = 0.01,
  batch_size = NULL,
  weight_decay = 1e-6,
  seed = 42
)
scores <- fit$score  # |phi(x) - c|^2 (one-class) or |phi(x) - c|^2 - R^2 (soft boundary)
SCORE_LABEL <- if (OBJECTIVE == "one_class") "Squared distance to the center" else "Squared distance beyond the radius"
ENGINE_PACKAGES <- c("torch", "nanoparquet")
rescore <- function(Q, where0, col0) cs_deep_svdd_score(fit, Q)  # the trained network, no refit

# %% Checks and values
spread <- if (fit$var0 > 0) fit$var / fit$var0 else NaN
extra_values <- list(
  n_features = ncol(X), rep_dim = 4, final_loss = fit$history[[length(fit$history)]]$loss,
  epochs_run = fit$epochs_run, center_norm = sqrt(sum(fit$center^2)),
  radius = if (OBJECTIVE == "soft_boundary") fit$radius else NaN, dist_median = stats::median(fit$dist), spread_ratio = spread
)
extra_stats <- list(list(key = "spread_ratio", label = "Spread kept by the representation", value = spread))
if (is.nan(spread)) {
  status <- "info"
  detail <- "The rows all start at the same representation (no spread to keep), so collapse can't be judged."
} else {
  status <- if (spread >= 0.01) "pass" else if (spread < 1e-6) "fail" else "warn"
  detail <- paste0(sprintf("The representation keeps %s of its starting spread across rows", format(signif(spread, 3))),
                   if (status == "pass") "." else "; the network has nearly collapsed the rows onto the center, so scores may reflect that rather than the data.")
}
assumptions <- list(list(key = "representation_spread", label = "Representation keeps its spread", status = status, detail = detail))
if (status %in% c("warn", "fail")) {
  warnings <- c(warnings, "The representation has nearly collapsed onto the center. Train for fewer epochs, lower the learning rate or widen the network.")
}
EPOCHS <- vapply(fit$history, function(h) as.numeric(h$epoch), numeric(1))
PARTS <- list(total = vapply(fit$history, function(h) h$loss, numeric(1)))
summary_tail <- sprintf(" Deep SVDD (%s) mapped %d design columns to %d coordinates; the median squared distance to the center is %s.",
                        if (OBJECTIVE == "soft_boundary") paste0("soft boundary, ν = ", format(0.1)) else "one-class",
                        ncol(X), as.integer(4), format(signif(stats::median(fit$dist), 3)))

# %% Flag anomalies
RULE <- "share"
flagged <- cs_ml_flag(scores, RULE, 0.05, 1)
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.deep_svdd/iris_one_class/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 SVDD (one-class neural anomaly detection)",
  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"))
))
Python

8 of 150 rows (5.3%) are flagged as anomalies (Squared distance to the center ≥ 0.644). Deep SVDD (one-class) mapped 4 design columns to 4 coordinates; the median squared distance to the center is 0.0457.

Anomalies
8
Threshold
0.6437
Spread kept by the representation
0.0638

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Representation keeps its spread — The representation keeps 0.0638 of its starting spread across rows.

Most anomalous rows

RankRowSquared distance to the centerMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
11191.232sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.84 at its median7.7002.6006.9002.300
2960.8214sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_width: falls 0.114 at its median5.70034.2001.200
3860.7867sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.364 at its median63.4004.5001.600
4890.7487sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 0.152 at its median5.60034.1001.300
5720.7372sepal_width = 2.8 (robust z -0.4); 33% of its tail scorepetal_length: falls 0.305 at its median6.1002.80041.300
6710.7050petal_width = 1.8 (robust z +0.5); 30% of its tail scoresepal_width: falls 0.505 at its median5.9003.2004.8001.800
7650.6442petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.26 at its median5.6002.9003.6001.300
8620.6437petal_width = 1.5 (robust z +0.2); 29% of its tail scorepetal_length: falls 0.117 at its median5.90034.2001.500
9610.6316sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.61 at its median523.5001
10760.6112sepal_length = 6.6 (robust z +0.8); 44% of its tail scoresepal_length: falls 0.0852 at its median6.60034.4001.400
11970.5335sepal_width = 2.9 (robust z -0.2); 32% of its tail scorepetal_length: falls 0.0996 at its median5.7002.9004.2001.300
12750.5309sepal_length = 6.4 (robust z +0.6); 35% of its tail scorepetal_length: falls 0.0379 at its median6.4002.9004.3001.300
13980.5077sepal_length = 6.2 (robust z +0.4); 30% of its tail scorepetal_length: falls 0.036 at its median6.2002.9004.3001.300
141230.4815sepal_length = 7.7 (robust z +1.8); 34% of its tail scoresepal_width: falls 0.256 at its median7.7002.8006.7002
15660.4673sepal_length = 6.7 (robust z +0.9); 43% of its tail scoreno single feature lowers it6.7003.1004.4001.400
16570.4600sepal_width = 3.3 (robust z +0.7); 29% of its tail scoresepal_width: falls 0.136 at its median6.3003.3004.7001.600
17520.4550sepal_length = 6.4 (robust z +0.6); 33% of its tail scoreno single feature lowers it6.4003.2004.5001.500
181000.4543sepal_width = 2.8 (robust z -0.4); 35% of its tail scorepetal_length: falls 0.113 at its median5.7002.8004.1001.300
19830.4527sepal_width = 2.7 (robust z -0.7); 39% of its tail scorepetal_length: falls 0.101 at its median5.8002.7003.9001.200
20920.4350sepal_length = 6.1 (robust z +0.3); 29% of its tail scoresepal_length: falls 0.0209 at its median6.10034.6001.400
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Deep SVDD (one-class neural anomaly detection)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.deep_svdd 1.1.0 · spec a3a7e8a388ec63db
# 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_svdd (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.deep_svdd/iris_one_class/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))

# %% Deep SVDD (PyTorch, float64, one thread): a bias-free network φ pulls the rows toward a fixed center c
OBJECTIVE = "one_class"
fit = du.fit_deep_svdd(
    X, [int(u) for u in [8]], 4,
    activation="relu",
    objective=OBJECTIVE,
    nu=0.1,
    epochs=100,
    lr=0.01,
    batch_size=None,
    weight_decay=1e-6,
    seed=42,
)
scores = fit["score"]  # ‖φ(x) − c‖² (one-class) or ‖φ(x) − c‖² − R² (soft boundary)
SCORE_LABEL = "Squared distance to the center" if OBJECTIVE == "one_class" else "Squared distance beyond the radius"
ENGINE_PACKAGES = ("torch", "numpy", "pandas")
rescore = lambda Q, where, col: du.svdd_score(fit, Q)  # the trained network, no refit

# %% Checks and values
spread = float(fit["var"] / fit["var0"]) if fit["var0"] > 0 else float("nan")
extra_values = {
    "n_features": int(X.shape[1]),
    "rep_dim": 4,
    "final_loss": float(fit["history"][-1]["loss"]),
    "epochs_run": int(fit["epochs_run"]),
    "center_norm": float(np.sqrt(np.sum(fit["center"] ** 2))),
    "radius": float(fit["radius"]) if OBJECTIVE == "soft_boundary" else float("nan"),
    "dist_median": float(np.median(fit["dist"])),
    "spread_ratio": spread,
}
extra_stats = [{"key": "spread_ratio", "label": "Spread kept by the representation", "value": spread}]
if spread != spread:
    status, detail = "info", "The rows all start at the same representation (no spread to keep), so collapse can't be judged."
else:
    status = "pass" if spread >= 0.01 else ("fail" if spread < 1e-6 else "warn")
    detail = f"The representation keeps {spread:.3g} of its starting spread across rows" + (
        "." if status == "pass" else "; the network has nearly collapsed the rows onto the center, so scores may reflect that rather than the data."
    )
assumptions = [{"key": "representation_spread", "label": "Representation keeps its spread", "status": status, "detail": detail}]
if status in ("warn", "fail"):
    warnings.append("The representation has nearly collapsed onto the center. Train for fewer epochs, lower the learning rate or widen the network.")
EPOCHS = [h["epoch"] for h in fit["history"]]
PARTS = [("total", [h["loss"] for h in fit["history"]])]
summary_tail = (
    f" Deep SVDD ({'soft boundary, ν = ' + format(0.1, 'g') if OBJECTIVE == 'soft_boundary' else 'one-class'}) mapped "
    f"{int(X.shape[1])} design columns to 4 coordinates; the median squared distance to the center is {np.median(fit['dist']):.3g}."
)

# %% Flag anomalies
RULE = "share"
flags, threshold = csanom.flag(scores, RULE, 0.05, 1)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.deep_svdd/iris_one_class/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 SVDD (one-class neural anomaly detection)",
    "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"},
    ],
})

On iris the median squared distance after training is 0.046, and the most unusual 5% of rows score at least 0.644.

Why no bias terms? A network with biases can set every weight to 0 and output c for every row. The loss is then 0 and the model has learned nothing. Without biases, and with c fixed before training, that shortcut is gone.

03

Watch for collapse

Predict

Predict first

You train Deep SVDD for many more epochs and the training loss keeps falling. Is the detector getting better?

BetterWorseCan't tell from the loss alone
Reveal

Can't tell from the loss alone. The loss also falls when the network squeezes every row together, which makes scores tiny and fragile. CodeSplash reports how much of the starting spread the representation keeps: 0.06 here. Below 0.01 the check warns.

The soft-boundary objective learns a radius that leaves a share ν of training rows outside it. Use it when you expect some anomalies in the training data. Its score is the squared distance beyond the radius, so rows inside score below 0. On the penguins with ν = 0.1 the learned radius is 0.266.

04

DAGMM: reconstruction and density together

Read

DAGMMDAGMMAn autoencoder and a Gaussian mixture trained together; a row's anomaly score is its energy under the mixture. trains three parts at once:

  1. an autoencoder that compresses each row to a few latent coordinates;
  2. two features of how well the row is rebuilt: relative distance and cosine similarity;
  3. an estimation network that assigns each row softly to K Gaussian components in that space.

The score is the row's sample energySample energyMinus the log density of a row under the fitted Gaussian mixture; higher means the row is less likely., minus its log density under the mixture. A row scores high if it's rebuilt badly, lands where the mixture is thin, or both.

05

Read the training curve

Read
Deep autoencoding Gaussian mixture (DAGMM)Recorded · Python and R agreeRecorded 2026-11-25 · 88 values compared
R

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

Sample energy distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalySample energy
false1.355
false0.3882
false0.5838
false0.5362
false1.090
false1.018
false0.5500
false0.9782
false0.8322
false0.3850
false0.8010
false0.7156
false0.4746
false0.7779
false2.471
true4.406
false1.025
false1.267
false1.268
false0.7262
false0.3315
false0.7034
false0.6394
false0.3079
false0.4346
false0.2830
false0.4231
false0.8658
false0.5744
false0.4979
false0.4360
false0.2826
false1.978
false2.880
false0.3790
false0.4072
false0.5265
false0.8515
false0.7052
false0.7788
false1.330
false2.007
false0.5829
false0.3804
false0.6820
false0.4555
false0.7482
false0.5520
false0.8150
false0.6555
false1.212
false−0.0453
false0.3946
false1.423
false−0.1731
false0.5870
false0.3561
false1.884
false1.034
false2.139

First 60 of 150 rows.

Training loss by epochIs the network still learning, and which part of its loss moves?
View data
PartLoss per rowEpoch
total5.7531
total5.2922
total4.9863
total4.7794
total4.6305
total4.5156
total4.4207
total4.3378
total4.2609
total4.18710
total4.11511
total4.04512
total3.97413
total3.90214
total3.82915
total3.75616
total3.68017
total3.60418
total3.52619
total3.44720
total3.36621
total3.28522
total3.20223
total3.11924
total3.03525
total2.95126
total2.86627
total2.78228
total2.69929
total2.61630
total2.53531
total2.45632
total2.37933
total2.30534
total2.23435
total2.16636
total2.10137
total2.04038
total1.98239
total1.92840
total1.87841
total1.83142
total1.78743
total1.74744
total1.70945
total1.67446
total1.64147
total1.61148
total1.58249
total1.55650
total1.53051
total1.50752
total1.48453
total1.46354
total1.44255
total1.42356
total1.40457
total1.38558
total1.36759
total1.35060

First 60 of 320 rows.

Assumptions

  • Mixture covariances well conditioned — The smallest eigenvalue of the component covariances is 0.00497.

Most anomalous rows

RankRowSample energyMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
1679.532sepal_length = 5.6 (robust z -0.2); 28% of its tail scoresepal_length: falls 6.86 at its median5.60034.5001.500
2659.305petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 5.51 at its median5.6002.9003.6001.300
3898.195sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 1.85 at its median5.60034.1001.300
4968.128sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_length: falls 1.84 at its median5.70034.2001.200
5856.855sepal_length = 5.4 (robust z -0.4); 33% of its tail scoresepal_length: falls 4.18 at its median5.40034.5001.500
6164.406sepal_width = 4.4 (robust z +3.1); 61% of its tail scoresepal_width: falls 3.38 at its median5.7004.4001.5000.4000
71323.720sepal_length = 7.9 (robust z +2.0); 40% of its tail scoresepal_width: falls 2.93 at its median7.9003.8006.4002
8973.637sepal_width = 2.9 (robust z -0.2); 32% of its tail scoresepal_length: falls 0.929 at its median5.7002.9004.2001.300
91183.386sepal_length = 7.7 (robust z +1.8); 28% of its tail scoresepal_width: falls 2.7 at its median7.7003.8006.7002.200
10342.880sepal_width = 4.2 (robust z +2.7); 50% of its tail scoresepal_width: falls 2.55 at its median5.5004.2001.4000.2000
11612.766sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.574 at its median523.5001
121132.561sepal_length = 6.8 (robust z +1.0); 33% of its tail scoresepal_length: falls 2.48 at its median6.80035.5002.100
13152.471sepal_width = 4 (robust z +2.2); 39% of its tail scoresepal_width: falls 1.58 at its median5.80041.2000.2000
141402.351sepal_length = 6.9 (robust z +1.1); 34% of its tail scoresepal_length: falls 2.18 at its median6.9003.1005.4002.100
151072.282sepal_width = 2.5 (robust z -1.1); 35% of its tail scoresepal_length: falls 1.69 at its median4.9002.5004.5001.700
16602.139sepal_width = 2.7 (robust z -0.7); 35% of its tail scoresepal_length: falls 2.11 at its median5.2002.7003.9001.400
17942.010sepal_width = 2.3 (robust z -1.6); 45% of its tail scoresepal_length: falls 0.882 at its median52.3003.3001
18422.007petal_length = 1.3 (robust z -1.6); 26% of its tail scoresepal_width: falls 1.36 at its median4.5002.3001.3000.3000
19331.978sepal_width = 4.1 (robust z +2.5); 39% of its tail scoresepal_width: falls 1.85 at its median5.2004.1001.5000.1000
20581.884sepal_width = 2.4 (robust z -1.3); 40% of its tail scoresepal_length: falls 1.11 at its median4.9002.4003.3001
The exact R script · R 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"))
))
Python

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

RankRowSample energyMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
1679.532sepal_length = 5.6 (robust z -0.2); 28% of its tail scoresepal_length: falls 6.86 at its median5.60034.5001.500
2659.305petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 5.51 at its median5.6002.9003.6001.300
3898.195sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 1.85 at its median5.60034.1001.300
4968.128sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_length: falls 1.84 at its median5.70034.2001.200
5856.855sepal_length = 5.4 (robust z -0.4); 33% of its tail scoresepal_length: falls 4.18 at its median5.40034.5001.500
6164.406sepal_width = 4.4 (robust z +3.1); 61% of its tail scoresepal_width: falls 3.38 at its median5.7004.4001.5000.4000
71323.720sepal_length = 7.9 (robust z +2.0); 40% of its tail scoresepal_width: falls 2.93 at its median7.9003.8006.4002
8973.637sepal_width = 2.9 (robust z -0.2); 32% of its tail scoresepal_length: falls 0.929 at its median5.7002.9004.2001.300
91183.386sepal_length = 7.7 (robust z +1.8); 28% of its tail scoresepal_width: falls 2.7 at its median7.7003.8006.7002.200
10342.880sepal_width = 4.2 (robust z +2.7); 50% of its tail scoresepal_width: falls 2.55 at its median5.5004.2001.4000.2000
11612.766sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.574 at its median523.5001
121132.561sepal_length = 6.8 (robust z +1.0); 33% of its tail scoresepal_length: falls 2.48 at its median6.80035.5002.100
13152.471sepal_width = 4 (robust z +2.2); 39% of its tail scoresepal_width: falls 1.58 at its median5.80041.2000.2000
141402.351sepal_length = 6.9 (robust z +1.1); 34% of its tail scoresepal_length: falls 2.18 at its median6.9003.1005.4002.100
151072.282sepal_width = 2.5 (robust z -1.1); 35% of its tail scoresepal_length: falls 1.69 at its median4.9002.5004.5001.700
16602.139sepal_width = 2.7 (robust z -0.7); 35% of its tail scoresepal_length: falls 2.11 at its median5.2002.7003.9001.400
17942.010sepal_width = 2.3 (robust z -1.6); 45% of its tail scoresepal_length: falls 0.882 at its median52.3003.3001
18422.007petal_length = 1.3 (robust z -1.6); 26% of its tail scoresepal_width: falls 1.36 at its median4.5002.3001.3000.3000
19331.978sepal_width = 4.1 (robust z +2.5); 39% of its tail scoresepal_width: falls 1.85 at its median5.2004.1001.5000.1000
20581.884sepal_width = 2.4 (robust z -1.3); 40% of its tail scoresepal_length: falls 1.11 at its median4.9002.4003.3001
The exact Python script · Python 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 training chart shows the loss's three parts: reconstruction, energy (weighted by λ1) and a covariance penalty (λ2). On iris the mean energy is 1.046.

Training loss and its partsIs the network still learning, and which part of its loss moves?
View data
epochloss per rowpart
17.125total
16.811reconstruction
10.3137KL
26.925total
26.487reconstruction
20.4377KL
36.670total
36.162reconstruction
30.5081KL
46.475total
45.945reconstruction
40.5298KL
56.203total
55.595reconstruction
50.6079KL
66.132total
65.446reconstruction
60.6860KL
75.830total
75.134reconstruction
70.6954KL
85.757total
85.006reconstruction
80.7514KL
95.534total
94.744reconstruction
90.7901KL
105.402total
104.566reconstruction
100.8367KL
115.256total
114.403reconstruction
110.8538KL
125.085total
124.217reconstruction
120.8687KL
134.915total
134.015reconstruction
130.9002KL
144.759total
143.830reconstruction
140.9284KL
154.641total
153.697reconstruction
150.9439KL
164.501total
163.547reconstruction
160.9542KL
174.479total
173.483reconstruction
170.9962KL
184.296total
183.293reconstruction
181.003KL
194.165total
193.173reconstruction
190.9917KL
204.165total
203.156reconstruction
201.009KL

First 60 of 360 rows.

The penalty matters because a mixture component can shrink onto a few rows and give them huge densities. CodeSplash reports the smallest covariance eigenvalue as a conditioning checkCovariance conditioningHow far a mixture component's covariance is from flat; a smallest eigenvalue near 0 means it collapsed onto a line or point.: 0.005 on the diabetes data with two components.

06

Check against a shallow baseline

Reflect

A deep detector earns its place only if it finds something a simpler one misses. Run a one-class SVM, a Gaussian mixture or isolation forest on the same features and compare the flagged rows. If they agree, prefer the simpler model: it's easier to explain and to rerun.

07

Check your understanding

Checkpoint

Check yourself

Why does Deep SVDD use a network without bias terms?

Show the answer

Answer: b

The fixed center plus a bias-free network rules out the trivial solution, so the network has to use the rows' features.

Check yourself

When does the soft-boundary objective fit better than the one-class objective?

Show the answer

Answer: b

ν sets the share of training rows allowed outside the radius, so a few anomalies don't drag the boundary out.

Check yourself

A row has a high DAGMM energy. Which explanation fits?

Show the answer

Answer: b

The mixture sees the latent code and the two reconstruction features, so either kind of oddity raises the energy.

Check yourself

The covariance check warns that the smallest eigenvalue is near 0. What's the first thing to try?

Show the answer

Answer: b

A component has collapsed onto a line or point. A stronger penalty on small variances, or fewer components to share the rows, keeps the mixture well posed.

08

Recap

Recap
  • Deep SVDD pulls typical rows toward a fixed center with a bias-free network; the squared distance is the score.
  • A falling loss can mean collapse; the spread check tells you how much of the rows' spread survives.
  • DAGMM scores rows by mixture energy over a compressed code plus reconstruction features; watch the covariance check.
  • Compare any deep detector with a shallow one before you trust its alerts.
09

Do it on your own data

In the app

Under Spot anomalies, open the Deep learning group and run Deep SVDD with the defaults. Then run One-class SVM on the same features and compare the top rows.

Concepts in this lesson