Skip to content

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.

Experimental Python and R use different algorithms; results agree in substance Seeded Also called Deep SVDD, deep support vector data description, deep one-class classification…

A real result

Example “Iris one class”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

Anomalies
8
Threshold
0.6437
Spread kept by the representation
0.0638

Plots

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

First 60 of 150 rows.

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

First 60 of 100 rows.

Assumptions

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

Most anomalous rows

RankRowSquared distance to the centerMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
11191.232sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.84 at its median7.7002.6006.9002.300
2960.8214sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_width: falls 0.114 at its median5.70034.2001.200
3860.7867sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.364 at its median63.4004.5001.600
4890.7487sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 0.152 at its median5.60034.1001.300
5720.7372sepal_width = 2.8 (robust z -0.4); 33% of its tail scorepetal_length: falls 0.305 at its median6.1002.80041.300
6710.7050petal_width = 1.8 (robust z +0.5); 30% of its tail scoresepal_width: falls 0.505 at its median5.9003.2004.8001.800
7650.6442petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.26 at its median5.6002.9003.6001.300
8620.6437petal_width = 1.5 (robust z +0.2); 29% of its tail scorepetal_length: falls 0.117 at its median5.90034.2001.500
9610.6316sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.61 at its median523.5001
10760.6112sepal_length = 6.6 (robust z +0.8); 44% of its tail scoresepal_length: falls 0.0852 at its median6.60034.4001.400
11970.5335sepal_width = 2.9 (robust z -0.2); 32% of its tail scorepetal_length: falls 0.0996 at its median5.7002.9004.2001.300
12750.5309sepal_length = 6.4 (robust z +0.6); 35% of its tail scorepetal_length: falls 0.0379 at its median6.4002.9004.3001.300
13980.5077sepal_length = 6.2 (robust z +0.4); 30% of its tail scorepetal_length: falls 0.036 at its median6.2002.9004.3001.300
141230.4815sepal_length = 7.7 (robust z +1.8); 34% of its tail scoresepal_width: falls 0.256 at its median7.7002.8006.7002
15660.4673sepal_length = 6.7 (robust z +0.9); 43% of its tail scoreno single feature lowers it6.7003.1004.4001.400
16570.4600sepal_width = 3.3 (robust z +0.7); 29% of its tail scoresepal_width: falls 0.136 at its median6.3003.3004.7001.600
17520.4550sepal_length = 6.4 (robust z +0.6); 33% of its tail scoreno single feature lowers it6.4003.2004.5001.500
181000.4543sepal_width = 2.8 (robust z -0.4); 35% of its tail scorepetal_length: falls 0.113 at its median5.7002.8004.1001.300
19830.4527sepal_width = 2.7 (robust z -0.7); 39% of its tail scorepetal_length: falls 0.101 at its median5.8002.7003.9001.200
20920.4350sepal_length = 6.1 (robust z +0.3); 29% of its tail scoresepal_length: falls 0.0209 at its median6.10034.6001.400
Python

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

Anomalies
8
Threshold
0.6437
Spread kept by the representation
0.0638

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

Assumptions

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

Most anomalous rows

RankRowSquared distance to the centerMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
11191.232sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.84 at its median7.7002.6006.9002.300
2960.8214sepal_length = 5.7 (robust z -0.1); 25% of its tail scorepetal_width: falls 0.114 at its median5.70034.2001.200
3860.7867sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.364 at its median63.4004.5001.600
4890.7487sepal_length = 5.6 (robust z -0.2); 29% of its tail scorepetal_length: falls 0.152 at its median5.60034.1001.300
5720.7372sepal_width = 2.8 (robust z -0.4); 33% of its tail scorepetal_length: falls 0.305 at its median6.1002.80041.300
6710.7050petal_width = 1.8 (robust z +0.5); 30% of its tail scoresepal_width: falls 0.505 at its median5.9003.2004.8001.800
7650.6442petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.26 at its median5.6002.9003.6001.300
8620.6437petal_width = 1.5 (robust z +0.2); 29% of its tail scorepetal_length: falls 0.117 at its median5.90034.2001.500
9610.6316sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.61 at its median523.5001
10760.6112sepal_length = 6.6 (robust z +0.8); 44% of its tail scoresepal_length: falls 0.0852 at its median6.60034.4001.400
11970.5335sepal_width = 2.9 (robust z -0.2); 32% of its tail scorepetal_length: falls 0.0996 at its median5.7002.9004.2001.300
12750.5309sepal_length = 6.4 (robust z +0.6); 35% of its tail scorepetal_length: falls 0.0379 at its median6.4002.9004.3001.300
13980.5077sepal_length = 6.2 (robust z +0.4); 30% of its tail scorepetal_length: falls 0.036 at its median6.2002.9004.3001.300
141230.4815sepal_length = 7.7 (robust z +1.8); 34% of its tail scoresepal_width: falls 0.256 at its median7.7002.8006.7002
15660.4673sepal_length = 6.7 (robust z +0.9); 43% of its tail scoreno single feature lowers it6.7003.1004.4001.400
16570.4600sepal_width = 3.3 (robust z +0.7); 29% of its tail scoresepal_width: falls 0.136 at its median6.3003.3004.7001.600
17520.4550sepal_length = 6.4 (robust z +0.6); 33% of its tail scoreno single feature lowers it6.4003.2004.5001.500
181000.4543sepal_width = 2.8 (robust z -0.4); 35% of its tail scorepetal_length: falls 0.113 at its median5.7002.8004.1001.300
19830.4527sepal_width = 2.7 (robust z -0.7); 39% of its tail scorepetal_length: falls 0.101 at its median5.8002.7003.9001.200
20920.4350sepal_length = 6.1 (robust z +0.3); 29% of its tail scoresepal_length: falls 0.0209 at its median6.10034.6001.400

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.
Python

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"},
    ],
})
R

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.