CDiscover · discover.deep_svdd
Deep SVDD (one-class neural anomaly detection)
Which rows sit far from where a neural network learns to place typical rows?
Deep support vector data description trains a neural network to map every row close to one fixed point, the center, so rows the network can't bring close are the unusual ones. The network has no bias terms (with them it could send every row to the center and learn nothing). The one-class objective scores each row by its squared distance to the center; the soft-boundary objective also learns a radius that leaves a share ν of rows outside and scores the distance beyond it. Lab tier: trained by Adam on torch in both engines from the same initial weights and batch order.
A real result
Example “Iris one class”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
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 |
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 |
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Iris one classml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Penguins soft boundary batchesml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass, sex
- Pima tanh deepml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Degenerate infml_iris · features: sepal_length, sepal_width, petal_length, petal_width
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
- Representation learning (autoencoders, contrastive) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 1–500 columns
- Columns used to describe each row. Numbers are standardized (median-filled); categories become indicator columns.
Choices you make
model
- Hidden layers (units)default 16
Units in each hidden layer, input side first. The layers have no bias terms.
- Representation sizedefault 4
Coordinates in the space where rows are pulled toward the center.
- Activationdefault relu
Nonlinearity in the hidden layers. ReLU follows the original paper; tanh saturates, which can help a collapse.
- ReLU(default) — Passes positive signals and zeroes the rest; the original paper's choice.
- tanh — An S-shaped unit with outputs from −1 to 1; smoother, and bounded, so watch the spread check.
- Objectivedefault one_class
Score every row by its distance to the center, or also learn a radius that leaves a share ν of rows outside.
- One-class (distance to the center)(default) — Minimizes the mean squared distance to the center; pick it when the training rows are almost all normal.
- Soft boundary (radius with a share outside) — Learns a radius and penalizes rows outside it; ν sets the share allowed outside, for data with some anomalies mixed in.
- Share outside the radius (ν)default 0.1
Upper bound on the share of training rows left outside the learned radius.
- Epochsdefault 150
Training passes over the data.
- Learning ratedefault 0.005
Adam's step size.
- Batch sizedefault —
Rows per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).
Advanced
- L2 penalty (λ)default 0.000001
Adds ½·λ·Σw² over the weights to the loss, as the paper's weight decay.
- Optimizerdefault default
How the weights are updated. The method's own choice is the usual one.
- Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
- Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
- AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
- SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
- Learning-rate scheduledefault none
How the learning rate changes over training.
- Constant(default) — The same learning rate every epoch (the method's default).
- Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
- Step — Divides the learning rate by 10 after each third of the epochs.
- One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
- Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
- Warm-up epochsdefault 0
Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.
- Gradient clippingdefault 0
Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.
- Weight average (EMA)default 0
Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.
- Weight average from epoch (SWA)default 0
Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.
- Record every stepdefault off
Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.
- Compute profiledefault parity
Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.
- Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
- Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
- Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
- Checkpoint every (epochs)default —
Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.
options
- Flag anomalies bydefault share
Flag a fixed share of the most unusual rows, or every row whose score passes a cutoff.
- Share of rows (the largest scores)(default) — Flags a set share of rows with the largest scores; pick it when you know how many you can review.
- Score cutoff — Flags rows whose score passes the value you set; pick it when you know a meaningful threshold.
- Share flaggeddefault 0.05
Share of rows to flag as anomalies (0.05 flags the most unusual 5%).
- Score cutoffdefault 1
Squared distance to the center (one-class) or beyond the radius (soft boundary) at which a row is flagged.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Representation keeps its spread
Share of the rows' starting spread left after training; near 0 means the network collapsed the rows onto the center.
- If violated → One-class SVM — A fixed kernel cannot collapse, and the reference advises comparing a deep one-class model with a shallow one. Changes the question: A kernel boundary around the rows instead of a learned representation.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_flagged
- How many independent units the analysis used; it sets precision and power.
- threshold
- The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
- score_check
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_max
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_mean
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- n_features
- How many independent units the analysis used; it sets precision and power.
- rep_dim
- A network trained to map typical rows close to one fixed center; a row's squared distance to it is its anomaly score.
- final_loss
- A neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.
- epochs_run
- Stopping training when a score on held-back rows has stopped improving for a set number of rounds.
- center_norm
- A network trained to map typical rows close to one fixed center; a row's squared distance to it is its anomaly score.
- radius
- A Deep SVDD variant that learns a radius and lets at most a share ν of training rows fall outside it.
- dist_median
- A network trained to map typical rows close to one fixed center; a row's squared distance to it is its anomaly score.
- spread_ratio
- The share of the rows' starting spread a Deep SVDD network keeps after training; near 0 means it collapsed the rows together.
Per group, level or term: top_row[<rank>], top_score[<rank>], why_feature[<rank>], why_z[<rank>], why_share[<rank>], drop_feature[<rank>], drop_score[<rank>]
Python and R
Python and R use different algorithms; results agree in substance (relative tolerance 1e-6). Python uses torch, codesplash; R uses torch, codesplashr.
Default traps between the two languages
- Lab tier. Both engines run the codesplash twin (codesplash.deep.unsupervised.fit_deep_svdd ↔ codesplashr::cs_deep_fit_svdd): the same bias-free network on LibTorch in double precision on one thread, initial weights from the shared Wichmann–Hill stream, Adam written out with torch's arithmetic, the same batch order and the same radius quantile (type 7). Python's and R's torch ship different LibTorch builds, so single kernels can differ by an ulp, which training can amplify; on the fixtures the values agree to about 1e-12 relative, so the stated band leaves room for other builds.
The exact script CodeSplash ran for example “Iris one class” · 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"},
],
})
The exact script CodeSplash ran for example “Iris one class” · 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"))
))
Sources
- Ruff L, Vandermeulen R, Görnitz N, Deecke L, Siddiqui SA, Binder A, Müller E, Kloft M (2018). Deep one-class classification. ICML 2018, PMLR 80:4393–4402.
- Tax DMJ, Duin RPW (2004). Support vector data description. Machine Learning 54(1):45–66.
From the CodeSplash method registry · discover.deep_svdd v1.1.0.