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.
What runs in CodeSplash
- Deep SVDD (one-class neural anomaly detection) Experimental
- Deep autoencoding Gaussian mixture (DAGMM) Experimental
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
Learning what "typical" means
ReadIsolation 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.
Deep SVDD: pull everything toward one point
ReadDeep 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‖².
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
View data
| Anomaly | Squared distance to the center |
|---|---|
| false | 0.0036 |
| false | 0.0275 |
| false | 0.0009 |
| false | 0.0053 |
| false | 0.0119 |
| false | 0.0358 |
| false | 0.0045 |
| false | 0.0016 |
| false | 0.0547 |
| false | 0.0100 |
| false | 0.0073 |
| false | 0.0007 |
| false | 0.0112 |
| false | 0.0301 |
| false | 0.0155 |
| false | 0.1022 |
| false | 0.0071 |
| false | 0.0038 |
| false | 0.0318 |
| false | 0.0072 |
| false | 0.0164 |
| false | 0.0075 |
| false | 0.0757 |
| false | 0.0467 |
| false | 0.0071 |
| false | 0.0570 |
| false | 0.0120 |
| false | 0.0031 |
| false | 0.0032 |
| false | 0.0044 |
| false | 0.0165 |
| false | 0.0204 |
| false | 0.0077 |
| false | 0.0157 |
| false | 0.0152 |
| false | 0.0009 |
| false | 0.0036 |
| false | 0.0209 |
| false | 0.0080 |
| false | 0.0032 |
| false | 0.0050 |
| false | 0.3751 |
| false | 0.0078 |
| false | 0.0186 |
| false | 0.0258 |
| false | 0.0217 |
| false | 0.0108 |
| false | 0.0011 |
| false | 0.0113 |
| false | 0.0016 |
| false | 0.2019 |
| false | 0.4550 |
| false | 0.2097 |
| false | 0.0230 |
| false | 0.1838 |
| false | 0.2621 |
| false | 0.4600 |
| false | 0.1245 |
| false | 0.3448 |
| false | 0.0263 |
First 60 of 150 rows.
View data
| Part | Loss per row | Epoch |
|---|---|---|
| total | 2.197 | 1 |
| total | 1.936 | 2 |
| total | 1.703 | 3 |
| total | 1.498 | 4 |
| total | 1.319 | 5 |
| total | 1.165 | 6 |
| total | 1.032 | 7 |
| total | 0.9195 | 8 |
| total | 0.8247 | 9 |
| total | 0.7451 | 10 |
| total | 0.6791 | 11 |
| total | 0.6244 | 12 |
| total | 0.5789 | 13 |
| total | 0.5409 | 14 |
| total | 0.5092 | 15 |
| total | 0.4817 | 16 |
| total | 0.4575 | 17 |
| total | 0.4357 | 18 |
| total | 0.4159 | 19 |
| total | 0.3978 | 20 |
| total | 0.3812 | 21 |
| total | 0.3658 | 22 |
| total | 0.3518 | 23 |
| total | 0.3391 | 24 |
| total | 0.3276 | 25 |
| total | 0.3173 | 26 |
| total | 0.3080 | 27 |
| total | 0.2995 | 28 |
| total | 0.2919 | 29 |
| total | 0.2848 | 30 |
| total | 0.2782 | 31 |
| total | 0.2720 | 32 |
| total | 0.2661 | 33 |
| total | 0.2606 | 34 |
| total | 0.2554 | 35 |
| total | 0.2506 | 36 |
| total | 0.2460 | 37 |
| total | 0.2419 | 38 |
| total | 0.2381 | 39 |
| total | 0.2347 | 40 |
| total | 0.2316 | 41 |
| total | 0.2288 | 42 |
| total | 0.2263 | 43 |
| total | 0.2239 | 44 |
| total | 0.2216 | 45 |
| total | 0.2194 | 46 |
| total | 0.2172 | 47 |
| total | 0.2151 | 48 |
| total | 0.2130 | 49 |
| total | 0.2108 | 50 |
| total | 0.2087 | 51 |
| total | 0.2066 | 52 |
| total | 0.2045 | 53 |
| total | 0.2024 | 54 |
| total | 0.2004 | 55 |
| total | 0.1984 | 56 |
| total | 0.1965 | 57 |
| total | 0.1946 | 58 |
| total | 0.1928 | 59 |
| total | 0.1911 | 60 |
First 60 of 100 rows.
Assumptions
- Representation keeps its spread — The representation keeps 0.0638 of its starting spread across rows.
Most anomalous rows
| Rank | Row | Squared distance to the center | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 119 | 1.232 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.84 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 2 | 96 | 0.8214 | sepal_length = 5.7 (robust z -0.1); 25% of its tail score | petal_width: falls 0.114 at its median | 5.700 | 3 | 4.200 | 1.200 |
| 3 | 86 | 0.7867 | sepal_width = 3.4 (robust z +0.9); 35% of its tail score | sepal_width: falls 0.364 at its median | 6 | 3.400 | 4.500 | 1.600 |
| 4 | 89 | 0.7487 | sepal_length = 5.6 (robust z -0.2); 29% of its tail score | petal_length: falls 0.152 at its median | 5.600 | 3 | 4.100 | 1.300 |
| 5 | 72 | 0.7372 | sepal_width = 2.8 (robust z -0.4); 33% of its tail score | petal_length: falls 0.305 at its median | 6.100 | 2.800 | 4 | 1.300 |
| 6 | 71 | 0.7050 | petal_width = 1.8 (robust z +0.5); 30% of its tail score | sepal_width: falls 0.505 at its median | 5.900 | 3.200 | 4.800 | 1.800 |
| 7 | 65 | 0.6442 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 0.26 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 8 | 62 | 0.6437 | petal_width = 1.5 (robust z +0.2); 29% of its tail score | petal_length: falls 0.117 at its median | 5.900 | 3 | 4.200 | 1.500 |
| 9 | 61 | 0.6316 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.61 at its median | 5 | 2 | 3.500 | 1 |
| 10 | 76 | 0.6112 | sepal_length = 6.6 (robust z +0.8); 44% of its tail score | sepal_length: falls 0.0852 at its median | 6.600 | 3 | 4.400 | 1.400 |
| 11 | 97 | 0.5335 | sepal_width = 2.9 (robust z -0.2); 32% of its tail score | petal_length: falls 0.0996 at its median | 5.700 | 2.900 | 4.200 | 1.300 |
| 12 | 75 | 0.5309 | sepal_length = 6.4 (robust z +0.6); 35% of its tail score | petal_length: falls 0.0379 at its median | 6.400 | 2.900 | 4.300 | 1.300 |
| 13 | 98 | 0.5077 | sepal_length = 6.2 (robust z +0.4); 30% of its tail score | petal_length: falls 0.036 at its median | 6.200 | 2.900 | 4.300 | 1.300 |
| 14 | 123 | 0.4815 | sepal_length = 7.7 (robust z +1.8); 34% of its tail score | sepal_width: falls 0.256 at its median | 7.700 | 2.800 | 6.700 | 2 |
| 15 | 66 | 0.4673 | sepal_length = 6.7 (robust z +0.9); 43% of its tail score | no single feature lowers it | 6.700 | 3.100 | 4.400 | 1.400 |
| 16 | 57 | 0.4600 | sepal_width = 3.3 (robust z +0.7); 29% of its tail score | sepal_width: falls 0.136 at its median | 6.300 | 3.300 | 4.700 | 1.600 |
| 17 | 52 | 0.4550 | sepal_length = 6.4 (robust z +0.6); 33% of its tail score | no single feature lowers it | 6.400 | 3.200 | 4.500 | 1.500 |
| 18 | 100 | 0.4543 | sepal_width = 2.8 (robust z -0.4); 35% of its tail score | petal_length: falls 0.113 at its median | 5.700 | 2.800 | 4.100 | 1.300 |
| 19 | 83 | 0.4527 | sepal_width = 2.7 (robust z -0.7); 39% of its tail score | petal_length: falls 0.101 at its median | 5.800 | 2.700 | 3.900 | 1.200 |
| 20 | 92 | 0.4350 | sepal_length = 6.1 (robust z +0.3); 29% of its tail score | sepal_length: falls 0.0209 at its median | 6.100 | 3 | 4.600 | 1.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"))
))
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
| Rank | Row | Squared distance to the center | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 119 | 1.232 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.84 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 2 | 96 | 0.8214 | sepal_length = 5.7 (robust z -0.1); 25% of its tail score | petal_width: falls 0.114 at its median | 5.700 | 3 | 4.200 | 1.200 |
| 3 | 86 | 0.7867 | sepal_width = 3.4 (robust z +0.9); 35% of its tail score | sepal_width: falls 0.364 at its median | 6 | 3.400 | 4.500 | 1.600 |
| 4 | 89 | 0.7487 | sepal_length = 5.6 (robust z -0.2); 29% of its tail score | petal_length: falls 0.152 at its median | 5.600 | 3 | 4.100 | 1.300 |
| 5 | 72 | 0.7372 | sepal_width = 2.8 (robust z -0.4); 33% of its tail score | petal_length: falls 0.305 at its median | 6.100 | 2.800 | 4 | 1.300 |
| 6 | 71 | 0.7050 | petal_width = 1.8 (robust z +0.5); 30% of its tail score | sepal_width: falls 0.505 at its median | 5.900 | 3.200 | 4.800 | 1.800 |
| 7 | 65 | 0.6442 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 0.26 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 8 | 62 | 0.6437 | petal_width = 1.5 (robust z +0.2); 29% of its tail score | petal_length: falls 0.117 at its median | 5.900 | 3 | 4.200 | 1.500 |
| 9 | 61 | 0.6316 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.61 at its median | 5 | 2 | 3.500 | 1 |
| 10 | 76 | 0.6112 | sepal_length = 6.6 (robust z +0.8); 44% of its tail score | sepal_length: falls 0.0852 at its median | 6.600 | 3 | 4.400 | 1.400 |
| 11 | 97 | 0.5335 | sepal_width = 2.9 (robust z -0.2); 32% of its tail score | petal_length: falls 0.0996 at its median | 5.700 | 2.900 | 4.200 | 1.300 |
| 12 | 75 | 0.5309 | sepal_length = 6.4 (robust z +0.6); 35% of its tail score | petal_length: falls 0.0379 at its median | 6.400 | 2.900 | 4.300 | 1.300 |
| 13 | 98 | 0.5077 | sepal_length = 6.2 (robust z +0.4); 30% of its tail score | petal_length: falls 0.036 at its median | 6.200 | 2.900 | 4.300 | 1.300 |
| 14 | 123 | 0.4815 | sepal_length = 7.7 (robust z +1.8); 34% of its tail score | sepal_width: falls 0.256 at its median | 7.700 | 2.800 | 6.700 | 2 |
| 15 | 66 | 0.4673 | sepal_length = 6.7 (robust z +0.9); 43% of its tail score | no single feature lowers it | 6.700 | 3.100 | 4.400 | 1.400 |
| 16 | 57 | 0.4600 | sepal_width = 3.3 (robust z +0.7); 29% of its tail score | sepal_width: falls 0.136 at its median | 6.300 | 3.300 | 4.700 | 1.600 |
| 17 | 52 | 0.4550 | sepal_length = 6.4 (robust z +0.6); 33% of its tail score | no single feature lowers it | 6.400 | 3.200 | 4.500 | 1.500 |
| 18 | 100 | 0.4543 | sepal_width = 2.8 (robust z -0.4); 35% of its tail score | petal_length: falls 0.113 at its median | 5.700 | 2.800 | 4.100 | 1.300 |
| 19 | 83 | 0.4527 | sepal_width = 2.7 (robust z -0.7); 39% of its tail score | petal_length: falls 0.101 at its median | 5.800 | 2.700 | 3.900 | 1.200 |
| 20 | 92 | 0.4350 | sepal_length = 6.1 (robust z +0.3); 29% of its tail score | sepal_length: falls 0.0209 at its median | 6.100 | 3 | 4.600 | 1.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.
Watch for collapse
PredictPredict first
You train Deep SVDD for many more epochs and the training loss keeps falling. Is the detector getting better?
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.
DAGMM: reconstruction and density together
ReadDAGMMDAGMMAn autoencoder and a Gaussian mixture trained together; a row's anomaly score is its energy under the mixture. trains three parts at once:
- an autoencoder that compresses each row to a few latent coordinates;
- two features of how well the row is rebuilt: relative distance and cosine similarity;
- 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.
Read the training curve
Read8 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 |
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"))
))
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 |
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.
View data
| epoch | loss per row | part |
|---|---|---|
| 1 | 7.125 | total |
| 1 | 6.811 | reconstruction |
| 1 | 0.3137 | KL |
| 2 | 6.925 | total |
| 2 | 6.487 | reconstruction |
| 2 | 0.4377 | KL |
| 3 | 6.670 | total |
| 3 | 6.162 | reconstruction |
| 3 | 0.5081 | KL |
| 4 | 6.475 | total |
| 4 | 5.945 | reconstruction |
| 4 | 0.5298 | KL |
| 5 | 6.203 | total |
| 5 | 5.595 | reconstruction |
| 5 | 0.6079 | KL |
| 6 | 6.132 | total |
| 6 | 5.446 | reconstruction |
| 6 | 0.6860 | KL |
| 7 | 5.830 | total |
| 7 | 5.134 | reconstruction |
| 7 | 0.6954 | KL |
| 8 | 5.757 | total |
| 8 | 5.006 | reconstruction |
| 8 | 0.7514 | KL |
| 9 | 5.534 | total |
| 9 | 4.744 | reconstruction |
| 9 | 0.7901 | KL |
| 10 | 5.402 | total |
| 10 | 4.566 | reconstruction |
| 10 | 0.8367 | KL |
| 11 | 5.256 | total |
| 11 | 4.403 | reconstruction |
| 11 | 0.8538 | KL |
| 12 | 5.085 | total |
| 12 | 4.217 | reconstruction |
| 12 | 0.8687 | KL |
| 13 | 4.915 | total |
| 13 | 4.015 | reconstruction |
| 13 | 0.9002 | KL |
| 14 | 4.759 | total |
| 14 | 3.830 | reconstruction |
| 14 | 0.9284 | KL |
| 15 | 4.641 | total |
| 15 | 3.697 | reconstruction |
| 15 | 0.9439 | KL |
| 16 | 4.501 | total |
| 16 | 3.547 | reconstruction |
| 16 | 0.9542 | KL |
| 17 | 4.479 | total |
| 17 | 3.483 | reconstruction |
| 17 | 0.9962 | KL |
| 18 | 4.296 | total |
| 18 | 3.293 | reconstruction |
| 18 | 1.003 | KL |
| 19 | 4.165 | total |
| 19 | 3.173 | reconstruction |
| 19 | 0.9917 | KL |
| 20 | 4.165 | total |
| 20 | 3.156 | reconstruction |
| 20 | 1.009 | KL |
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.
Check against a shallow baseline
ReflectA 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.
Check your understanding
CheckpointCheck 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.
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.
Do it on your own data
In the appUnder 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