Skip to content

Isolation, tails and boundaries: forests, per-column surprise and one-class fences

Isolation forests count random cuts, HBOS, COPOD and ECOD add up how surprising each column is, and one-class SVMs and SVDD draw a fence around normal data. What each assumes, what each misses, and what their settings really control.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Explain why a short isolation path means an anomaly, and what extended splits fix
  • Explain why per-column scores miss unusual combinations and double-count correlated columns
  • Read ν in a one-class SVM as a soft share, not an exact future anomaly rate
  • Say when SVDD and the one-class SVM coincide

Read first

01

Three more ideas

Read
  • Isolation: anomalies are few and different, so random cuts separate them quickly.
  • Tails: score each column on its own by how far into its tail a value sits, then add the columns up.
  • Boundaries: learn a fence around normal data and score how far outside a row falls.

Isolation and tail scores are fast and need little tuning, so they make good first baselines. Boundaries can bend around odd shapes but need a kernel and its width.

AExplorable · Isolation forest: where to draw the line

Why are anomalies easy to isolate, and how many should you flag?

Cut at random until a point stands alone. On average, how many cuts does a planted anomaly take? (A normal point takes about 7.)

6.0
How sure?
0.60
100
64
0.05
300
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

02

Isolation forest: short paths

Read

Each tree picks a random column and a random cut inside its range, and keeps splitting until each row stands alone. An odd row is cut off early. The score averages path lengths h(x)h(x) over trees: s(x)=2−E[h(x)]/c(ψ)s(x)=2^{-E[h(x)]/c(\psi)}, where c(ψ)c(\psi) is the average path length for a subsample of size ψ\psi. Scores near 1 are anomalous; around 0.5 is ordinary.

Isolation forestRecorded · Python and R agreeRecorded 2026-11-25 · 76 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (Isolation score ≥ 0.544).

Anomalies
27
Threshold
0.5439

Plots

Isolation score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyIsolation score
false0.4081
false0.5287
false0.4413
false0.4636
false0.4169
false0.4347
false0.4074
false0.4973
false0.5010
false0.4784
true0.5893
false0.4503
false0.5303
true0.5869
false0.4832
false0.4453
false0.4789
false0.5061
false0.4188
false0.4556
false0.4309
false0.4163
false0.4443
false0.4376
false0.3962
false0.4868
false0.4475
false0.4318
false0.4052
false0.3880
false0.4534
false0.4077
false0.4203
false0.4442
false0.4156
true0.5612
false0.4338
false0.4865
false0.4497
false0.4056
false0.5027
false0.4411
false0.4342
false0.4533
false0.4100
false0.4241
false0.3961
false0.5211
false0.4149
true0.5698
false0.4223
false0.3942
false0.4276
false0.3996
false0.3894
false0.4685
false0.4098
false0.4536
false0.4511
false0.5424

First 60 of 532 rows.

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropnpregglubpskinbmipedage
13980.6665ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 0.0805 at its median0180786359.4002.42025
21570.6541skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.126 at its median2197709934.7000.575062
32790.5900bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 0.104 at its median01291104667.1000.319026
4110.5893ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.0926 at its median0137403543.1002.28833
54320.5892age = 60 (robust z +3.6); 19% of its tail scorebmi: falls 0.0492 at its median612990719.6000.582060
62210.5880bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 0.0554 at its median91711102445.4000.721054
7140.5869npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 0.0653 at its median129262727.6000.926044
84170.5850age = 58 (robust z +3.4); 21% of its tail scoreage: falls 0.0749 at its median0173783246.5001.15958
94910.5701bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.0591 at its median10681062335.5000.285047
10500.5698ped = 1.394 (robust z +3.7); 21% of its tail scoreped: falls 0.0674 at its median1199764342.9001.39422
113060.5633ped = 1.213 (robust z +3.0); 19% of its tail scoreped: falls 0.0492 at its median91848515301.21349
122720.5613npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 0.0954 at its median17163724140.9000.817047
13360.5612npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 0.0451 at its median13145821922.2000.245057
142960.5607ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.101 at its median4197703936.7002.32931
151400.5587skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 0.0604 at its median0100886046.8000.962031
164030.5566age = 81 (robust z +6.0); 44% of its tail scoreage: falls 0.105 at its median9134743325.9000.460081
172550.5536bmi = 53.2 (robust z +3.1); 27% of its tail scorebmi: falls 0.0537 at its median0162765653.2000.759025
183580.5532age = 65 (robust z +4.2); 31% of its tail scoreage: falls 0.0785 at its median51031083739.2000.305065
192220.5529ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 0.0861 at its median01806639421.89325
202180.5519ped = 1.39 (robust z +3.7); 27% of its tail scoreped: falls 0.0804 at its median4111724737.1001.39056
The exact R script · R R version 4.5.1 (2025-06-13)
# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec 59a1df5b296d40c4
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(isotree))

# %% Data
IMPUTE <- "none"  # isotree handles missing numbers itself
SCALE <- "none"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "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

# %% Scores
model <- isotree::isolation.forest(
  X,
  ntrees = 100,
  sample_size = min(256, nrow(df)),
  ndim = 1,
  missing_action = "impute",
  nthreads = 1,  # pinned: identical trees in Python and R
  seed = 42
)
scores <- as.numeric(predict(model, X, type = "score"))  # standardized isolation score
SCORE_LABEL <- "Isolation score"
ENGINE_PACKAGES <- c("isotree", "nanoparquet")
extra_values <- list()

rescore <- function(Q, where0, col0) as.numeric(predict(model, Q, type = "score"))  # the fitted trees, no refit

# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0.6
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
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.iforest/pima/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.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; Phase 11 DS1)
NUMERIC <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
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]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  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
})
cs_publish(list(
  title = "Isolation forest",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = 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))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  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 = 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))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

27 of 532 rows (5.1%) are flagged as anomalies (Isolation score ≥ 0.544).

Anomalies
27
Threshold
0.5439

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

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropnpregglubpskinbmipedage
13980.6665ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 0.0805 at its median0180786359.4002.42025
21570.6541skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.126 at its median2197709934.7000.575062
32790.5900bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 0.104 at its median01291104667.1000.319026
4110.5893ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.0926 at its median0137403543.1002.28833
54320.5892age = 60 (robust z +3.6); 19% of its tail scorebmi: falls 0.0492 at its median612990719.6000.582060
62210.5880bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 0.0554 at its median91711102445.4000.721054
7140.5869npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 0.0653 at its median129262727.6000.926044
84170.5850age = 58 (robust z +3.4); 21% of its tail scoreage: falls 0.0749 at its median0173783246.5001.15958
94910.5701bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.0591 at its median10681062335.5000.285047
10500.5698ped = 1.394 (robust z +3.7); 21% of its tail scoreped: falls 0.0674 at its median1199764342.9001.39422
113060.5633ped = 1.213 (robust z +3.0); 19% of its tail scoreped: falls 0.0492 at its median91848515301.21349
122720.5613npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 0.0954 at its median17163724140.9000.817047
13360.5612npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 0.0451 at its median13145821922.2000.245057
142960.5607ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.101 at its median4197703936.7002.32931
151400.5587skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 0.0604 at its median0100886046.8000.962031
164030.5566age = 81 (robust z +6.0); 44% of its tail scoreage: falls 0.105 at its median9134743325.9000.460081
172550.5536bmi = 53.2 (robust z +3.1); 27% of its tail scorebmi: falls 0.0537 at its median0162765653.2000.759025
183580.5532age = 65 (robust z +4.2); 31% of its tail scoreage: falls 0.0785 at its median51031083739.2000.305065
192220.5529ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 0.0861 at its median01806639421.89325
202180.5519ped = 1.39 (robust z +3.7); 27% of its tail scoreped: falls 0.0804 at its median4111724737.1001.39056
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec 59a1df5b296d40c4
# Dataset: ml_pima (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
from isotree import IsolationForest

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "none"  # isotree handles missing numbers itself
SCALE = "none"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "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))

# %% Scores
model = IsolationForest(
    ntrees=100,
    sample_size=min(256, len(df)),
    ndim=1,
    missing_action="impute",
    nthreads=1,  # pinned: identical trees in Python and R
    random_seed=42,
)
model.fit(X)
scores = np.asarray(model.predict(X), dtype=np.float64)  # standardized isolation score
SCORE_LABEL = "Isolation score"
ENGINE_PACKAGES = ("isotree", "numpy", "pandas")
extra_values = {}

rescore = lambda Q, where, col: np.asarray(model.predict(Q), dtype=np.float64)  # the fitted trees, no refit

# %% Flag anomalies
RULE = "share"
_cutoff = 0.6
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.iforest/pima/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.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; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age", ]
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])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _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)
pct = flags.mean()
cs.publish({
    "title": "Isolation forest",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "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": [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)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})

The contamination or share you set only places the threshold; it isn't an estimate of how many anomalies exist. Clustered anomalies can shield each other, and many irrelevant columns dilute the cuts.

03

Extended isolation forest

Read

Cuts on one column at a time are axis-aligned, so scores show stripes and crosses that have nothing to do with the data: a row lined up with a dense cluster along one axis looks more normal than it is. The extended version cuts with random hyperplanes, sending xx left when (x−p)⊤n≤0(x-p)^\top n\le 0 for a random point pp and direction nn; the extension level sets how many columns each cut mixes.

Isolation forestRecorded · Python and R agreeRecorded 2026-11-25 · 76 values compared
R

16 of 153 rows (10.5%) are flagged as anomalies (Isolation score ≥ 0.538).

Anomalies
16
Threshold
0.5376

Plots

Isolation score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyIsolation score
false0.4820
false0.4463
false0.4251
false0.5036
false0.5120
false0.4744
false0.4801
false0.5106
true0.6110
false0.4300
false0.4407
false0.4354
false0.4814
false0.4539
false0.5312
false0.5097
false0.4909
true0.5861
false0.4895
false0.4892
true0.5401
false0.5322
false0.5135
false0.4995
true0.5664
true0.5406
false0.4879
false0.4931
false0.4760
true0.5378
false0.4343
false0.4145
false0.4222
false0.5095
false0.4070
false0.4078
false0.4376
false0.4234
false0.4328
true0.5388
false0.5119
false0.4612
false0.4495
false0.4119
false0.5154
false0.4745
false0.4420
true0.5798
false0.4765
false0.4284
false0.4227
false0.4241
false0.5201
false0.4574
false0.4180
false0.4055
false0.4009
false0.4471
false0.4279
false0.5088

First 60 of 153 rows.

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropOzonesolar radiationWindTemp
11170.6220Ozone = 168 (robust z +7.4); 48% of its tail scoreOzone: falls 0.147 at its median1682383.40081
290.6110Wind = 20.1 (robust z +3.0); 32% of its tail scoreWind: falls 0.0941 at its median81920.10061
31210.6097Ozone = 118 (robust z +4.7); 29% of its tail scoreOzone: falls 0.0616 at its median1182252.30094
4180.5861Wind = 18.4 (robust z +2.6); 30% of its tail scoreWind: falls 0.0693 at its median67818.40057
5620.5818Ozone = 135 (robust z +5.6); 41% of its tail scoreOzone: falls 0.1 at its median1352694.10084
6480.5798Wind = 20.7 (robust z +3.2); 52% of its tail scoreWind: falls 0.135 at its median3728420.70072
7250.5664Temp = 57 (robust z -2.5); 39% of its tail scoreTemp: falls 0.0518 at its median—6616.60057
81480.5598Wind = 16.6 (robust z +2.0); 30% of its tail scoreWind: falls 0.0675 at its median142016.60063
9990.5593Ozone = 122 (robust z +4.9); 37% of its tail scoreOzone: falls 0.0649 at its median122255489
101260.5491Ozone = 73 (robust z +2.2); 19% of its tail scoreWind: falls 0.0467 at its median731832.80093
111220.5425Ozone = 84 (robust z +2.8); 24% of its tail scoreTemp: falls 0.0762 at its median842376.30096
12260.5406Temp = 58 (robust z -2.4); 43% of its tail scoreTemp: falls 0.0911 at its median—26614.90058
13210.5401Temp = 59 (robust z -2.2); 23% of its tail scoreTemp: falls 0.0358 at its median189.70059
14400.5388Ozone = 71 (robust z +2.1); 22% of its tail scoreWind: falls 0.0488 at its median7129113.80090
15300.5378Ozone = 115 (robust z +4.5); 48% of its tail scoreOzone: falls 0.111 at its median1152235.70079
161200.5376Ozone = 76 (robust z +2.4); 23% of its tail scoreTemp: falls 0.0793 at its median762039.70097
17220.5322Wind = 16.6 (robust z +2.0); 32% of its tail scoreWind: falls 0.0645 at its median1132016.60073
18150.5312Temp = 58 (robust z -2.4); 39% of its tail scoreTemp: falls 0.0483 at its median186513.20058
191240.5288Ozone = 96 (robust z +3.5); 36% of its tail scoreOzone: falls 0.0418 at its median961676.90091
20940.5253solar radiation = 24 (robust z -2.0); 36% of its tail scoresolar radiation: falls 0.0599 at its median92413.80081
The exact R script · R R version 4.5.1 (2025-06-13)
# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec ec946b4a431cb387
# Dataset: ml_airquality (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(isotree))

# %% Data
IMPUTE <- "none"  # isotree handles missing numbers itself
SCALE <- "none"
FEATURES <- c("Ozone", "solar radiation", "Wind", "Temp")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_airquality.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    Ozone = "numeric",
    `solar radiation` = "numeric",
    Wind = "numeric",
    Temp = "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

# %% Scores
model <- isotree::isolation.forest(
  X,
  ntrees = 100,
  sample_size = min(64, nrow(df)),
  ndim = 2,
  missing_action = "impute",
  nthreads = 1,  # pinned: identical trees in Python and R
  seed = 42
)
scores <- as.numeric(predict(model, X, type = "score"))  # standardized isolation score
SCORE_LABEL <- "Isolation score"
ENGINE_PACKAGES <- c("isotree", "nanoparquet")
extra_values <- list()

rescore <- function(Q, where0, col0) as.numeric(predict(model, Q, type = "score"))  # the fitted trees, no refit

# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0.6
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.1, cutoff_)
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-97231/discover.iforest/airquality_extended/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.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; Phase 11 DS1)
NUMERIC <- c("Ozone", "solar radiation", "Wind", "Temp")
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]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  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
})
cs_publish(list(
  title = "Isolation forest",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = 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))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  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 = 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))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

16 of 153 rows (10.5%) are flagged as anomalies (Isolation score ≥ 0.538).

Anomalies
16
Threshold
0.5376

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

Most anomalous rows

RankRowIsolation scoreMost unusualBiggest score dropOzonesolar radiationWindTemp
11170.6220Ozone = 168 (robust z +7.4); 48% of its tail scoreOzone: falls 0.147 at its median1682383.40081
290.6110Wind = 20.1 (robust z +3.0); 32% of its tail scoreWind: falls 0.0941 at its median81920.10061
31210.6097Ozone = 118 (robust z +4.7); 29% of its tail scoreOzone: falls 0.0616 at its median1182252.30094
4180.5861Wind = 18.4 (robust z +2.6); 30% of its tail scoreWind: falls 0.0693 at its median67818.40057
5620.5818Ozone = 135 (robust z +5.6); 41% of its tail scoreOzone: falls 0.1 at its median1352694.10084
6480.5798Wind = 20.7 (robust z +3.2); 52% of its tail scoreWind: falls 0.135 at its median3728420.70072
7250.5664Temp = 57 (robust z -2.5); 39% of its tail scoreTemp: falls 0.0518 at its median—6616.60057
81480.5598Wind = 16.6 (robust z +2.0); 30% of its tail scoreWind: falls 0.0675 at its median142016.60063
9990.5593Ozone = 122 (robust z +4.9); 37% of its tail scoreOzone: falls 0.0649 at its median122255489
101260.5491Ozone = 73 (robust z +2.2); 19% of its tail scoreWind: falls 0.0467 at its median731832.80093
111220.5425Ozone = 84 (robust z +2.8); 24% of its tail scoreTemp: falls 0.0762 at its median842376.30096
12260.5406Temp = 58 (robust z -2.4); 43% of its tail scoreTemp: falls 0.0911 at its median—26614.90058
13210.5401Temp = 59 (robust z -2.2); 23% of its tail scoreTemp: falls 0.0358 at its median189.70059
14400.5388Ozone = 71 (robust z +2.1); 22% of its tail scoreWind: falls 0.0488 at its median7129113.80090
15300.5378Ozone = 115 (robust z +4.5); 48% of its tail scoreOzone: falls 0.111 at its median1152235.70079
161200.5376Ozone = 76 (robust z +2.4); 23% of its tail scoreTemp: falls 0.0793 at its median762039.70097
17220.5322Wind = 16.6 (robust z +2.0); 32% of its tail scoreWind: falls 0.0645 at its median1132016.60073
18150.5312Temp = 58 (robust z -2.4); 39% of its tail scoreTemp: falls 0.0483 at its median186513.20058
191240.5288Ozone = 96 (robust z +3.5); 36% of its tail scoreOzone: falls 0.0418 at its median961676.90091
20940.5253solar radiation = 24 (robust z -2.0); 36% of its tail scoresolar radiation: falls 0.0599 at its median92413.80081
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Isolation forest
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.iforest 1.2.0 · spec ec946b4a431cb387
# Dataset: ml_airquality (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
from isotree import IsolationForest

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "none"  # isotree handles missing numbers itself
SCALE = "none"
FEATURES = ["Ozone", "solar radiation", "Wind", "Temp"]
df = pd.read_parquet("tests/parity/fixtures/ml_airquality.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "Ozone": "numeric",
        "solar radiation": "numeric",
        "Wind": "numeric",
        "Temp": "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))

# %% Scores
model = IsolationForest(
    ntrees=100,
    sample_size=min(64, len(df)),
    ndim=2,
    missing_action="impute",
    nthreads=1,  # pinned: identical trees in Python and R
    random_seed=42,
)
model.fit(X)
scores = np.asarray(model.predict(X), dtype=np.float64)  # standardized isolation score
SCORE_LABEL = "Isolation score"
ENGINE_PACKAGES = ("isotree", "numpy", "pandas")
extra_values = {}

rescore = lambda Q, where, col: np.asarray(model.predict(Q), dtype=np.float64)  # the fitted trees, no refit

# %% Flag anomalies
RULE = "share"
_cutoff = 0.6
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.1, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-97231/discover.iforest/airquality_extended/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.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; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["Ozone", "solar radiation", "Wind", "Temp", ]
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])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _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)
pct = flags.mean()
cs.publish({
    "title": "Isolation forest",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "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": [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)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})

It removes that artifact. It doesn't make the scores a density, and scaling and irrelevant columns still matter. Compare it with the ordinary forest at the same false-alarm budget.

04

Per-column surprise: HBOS, COPOD, ECOD

Read

These three score each column separately and add:

  • HBOSHistogram-based outlier score (HBOS)Minus the sum over features of log₂(histogram density + α): values in sparse bins of several columns score high.: s(x)=−∑jlog⁡p^j(xj)s(x)=-\sum_j\log\hat p_j(x_j) from a histogram per column; bin edges and empty bins need care.
  • ECODECODScores each row by how far into the tails of each column's own distribution it falls, with no settings to tune.: left and right empirical tail surprisals, −log⁡F^j(xj)-\log\hat F_j(x_j) and −log⁡(1−F^j(xj))-\log(1-\hat F_j(x_j)), combined using each column's skew.
  • COPODCOPODAdds up per-feature tail scores from the empirical CDFs: the skewed tail or the average of both tails, whichever is larger.: tail probabilities in the spirit of a copula, combined the same way; despite the name, it isn't a fitted copula density.
ECOD anomaly scoresRecorded · Python and R agreeRecorded 2026-11-25 · 76 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (ECOD score ≥ 16).

Anomalies
27
Threshold
15.963

Plots

ECOD score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyECOD score
false7.981
false15.166
false13.068
false13.510
false11.891
false9.075
false8.886
false14.376
false12.985
false10.909
true17.860
false11.191
false12.666
true17.991
false13.771
false12.474
false15.089
false14.422
false7.909
false14.136
false11.022
false7.176
false10.402
false13.710
false8.555
false11.424
false13.799
false9.667
false8.737
false5.989
false13.545
false8.109
false8.461
false9.706
false8.882
true16.647
false11.188
true16.763
false10.444
false9.313
false13.418
false10.573
false10.293
false14.260
false9.631
false11.692
false7.454
false12.292
false8.652
true18.684
false11.423
false8.756
false9.253
false9.216
false8.962
false10.646
false10.617
false12.766
false10.170
true17.192

First 60 of 532 rows.

Most anomalous rows

RankRowECOD scoreMost unusualBiggest score dropnpregglubpskinbmipedage
139824.174ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 5.58 at its median0180786359.4002.42025
243219.828age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 4.91 at its median612990719.6000.582060
327919.099bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 5.59 at its median01291104667.1000.319026
45018.684ped = 1.394 (robust z +3.7); 21% of its tail scoreglu: falls 5.59 at its median1199764342.9001.39422
522818.665bp = 50 (robust z -1.9); 16% of its tail scoreskin: falls 3.4 at its median1735010230.248021
615718.629skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 5.61 at its median2197709934.7000.575062
722118.524bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 4.49 at its median91711102445.4000.721054
81417.991npreg = 12 (robust z +3.4); 19% of its tail scoreskin: falls 4.91 at its median129262727.6000.926044
91117.860ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 4.48 at its median0137403543.1002.28833
1014017.591skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 4.51 at its median0100886046.8000.962031
1117917.382npreg = 9 (robust z +2.4); 13% of its tail scoreglu: falls 4.89 at its median957803732.8000.096041
1227217.341npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 5.61 at its median17163724140.9000.817047
1349117.223bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.8 at its median10681062335.5000.285047
1425517.194bmi = 53.2 (robust z +3.1); 27% of its tail scoreskin: falls 4.22 at its median0162765653.2000.759025
156017.192bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.8 at its median81671064637.6000.165043
1625716.994bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 4.5 at its median1883042550.496026
173816.763bp = 48 (robust z -2.0); 22% of its tail scoreglu: falls 3.28 at its median171481820.4000.323022
183616.647npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 3.53 at its median13145821922.2000.245057
1935816.613age = 65 (robust z +4.2); 31% of its tail scoreage: falls 4.5 at its median51031083739.2000.305065
2018916.607skin = 10 (robust z -1.8); 25% of its tail scoreskin: falls 3.4 at its median074521027.8000.269022
The exact R script · R R version 4.5.1 (2025-06-13)
# ECOD anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ecod 1.3.0 · spec 8befa3826b147035
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)


# %% Data
IMPUTE <- "median"
SCALE <- "none"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "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

# %% Scores
scores <- cs_ml_ecod(X)  # port of PyOD's ECOD
SCORE_LABEL <- "ECOD score"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list()

rescore <- function(Q, where0, col0) cs_ml_ecod_rescore(X, scores, Q, where0, col0)


# %% Flag anomalies
RULE <- "share"
cutoff_ <- 10
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
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.ecod/pima/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.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; Phase 11 DS1)
NUMERIC <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
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]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  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
})
cs_publish(list(
  title = "ECOD anomaly scores",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = 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))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  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 = 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))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

27 of 532 rows (5.1%) are flagged as anomalies (ECOD score ≥ 16).

Anomalies
27
Threshold
15.963

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

Most anomalous rows

RankRowECOD scoreMost unusualBiggest score dropnpregglubpskinbmipedage
139824.174ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 5.58 at its median0180786359.4002.42025
243219.828age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 4.91 at its median612990719.6000.582060
327919.099bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 5.59 at its median01291104667.1000.319026
45018.684ped = 1.394 (robust z +3.7); 21% of its tail scoreglu: falls 5.59 at its median1199764342.9001.39422
522818.665bp = 50 (robust z -1.9); 16% of its tail scoreskin: falls 3.4 at its median1735010230.248021
615718.629skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 5.61 at its median2197709934.7000.575062
722118.524bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 4.49 at its median91711102445.4000.721054
81417.991npreg = 12 (robust z +3.4); 19% of its tail scoreskin: falls 4.91 at its median129262727.6000.926044
91117.860ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 4.48 at its median0137403543.1002.28833
1014017.591skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 4.51 at its median0100886046.8000.962031
1117917.382npreg = 9 (robust z +2.4); 13% of its tail scoreglu: falls 4.89 at its median957803732.8000.096041
1227217.341npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 5.61 at its median17163724140.9000.817047
1349117.223bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.8 at its median10681062335.5000.285047
1425517.194bmi = 53.2 (robust z +3.1); 27% of its tail scoreskin: falls 4.22 at its median0162765653.2000.759025
156017.192bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.8 at its median81671064637.6000.165043
1625716.994bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 4.5 at its median1883042550.496026
173816.763bp = 48 (robust z -2.0); 22% of its tail scoreglu: falls 3.28 at its median171481820.4000.323022
183616.647npreg = 13 (robust z +3.7); 25% of its tail scorenpreg: falls 3.53 at its median13145821922.2000.245057
1935816.613age = 65 (robust z +4.2); 31% of its tail scoreage: falls 4.5 at its median51031083739.2000.305065
2018916.607skin = 10 (robust z -1.8); 25% of its tail scoreskin: falls 3.4 at its median074521027.8000.269022
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ECOD anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ecod 1.3.0 · spec 8befa3826b147035
# Dataset: ml_pima (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.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "median"
SCALE = "none"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "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))

# %% Scores
from pyod.models.ecod import ECOD

model = ECOD(n_jobs=1).fit(X)
scores = np.asarray(model.decision_scores_, dtype=np.float64)
SCORE_LABEL = "ECOD score"
ENGINE_PACKAGES = ("pyod", "numpy", "pandas")
extra_values = {}

from codesplash.ml import discover_ext as _dx_e

rescore = lambda Q, where, col: _dx_e.ecod_rescore(X, scores, Q, where, col)


# %% Flag anomalies
RULE = "share"
_cutoff = 10
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.ecod/pima/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.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; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age", ]
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])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _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)
pct = flags.mean()
cs.publish({
    "title": "ECOD anomaly scores",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "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": [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)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
05

Ordinary values, odd combination

Predict

Predict first

A patient record has an ordinary height and an ordinary weight, but that weight is very unusual for that height. What does ECOD score it?

High: something is clearly offLow: each value is ordinary on its own
Reveal

Low. ECOD, COPOD and HBOS look at one column at a time, so a rare combination of ordinary values slips through. And three correlated columns that are all extreme count the same evidence three times. Pair these fast baselines with a dependence-aware detector such as robust covariance or kNN distance.

06

One-class SVM: a soft fence

Read

The one-class SVMOne-class SVMLearns a smooth boundary around most rows; rows outside it score as anomalies. separates the data from the origin in a kernel feature space: minimize 12∥w∥2+1νn∑iξi−ρ\tfrac12\lVert w\rVert^2+\frac{1}{\nu n}\sum_i\xi_i-\rho with w⊤ϕ(xi)≥ρ−ξiw^\top\phi(x_i)\ge\rho-\xi_i. Rows with w⊤ϕ(x)<ρw^\top\phi(x)<\rho fall outside.

One-class SVMRecorded · Python and R agreeRecorded 2026-11-25 · 80 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (One-class SVM score ≥ 6.22e-05).

Anomalies
27
Threshold
6.217e-5

Plots

One-class SVM score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyOne-class SVM score
false−0.5286
false−0.0418
false−0.3742
false−0.1168
false−0.3205
false−0.6584
false−0.4743
false−5.478e-5
false−0.0242
false−0.6677
true0.1363
false−0.7790
true0.0002
false−0.0002
false−0.1001
false−0.1698
false−0.1427
false−0.6612
false−0.7404
false−0.1418
false−0.3107
false−0.5438
false−0.3718
false−0.2284
false−0.4660
false−0.4329
false−0.3381
false−0.2765
false−0.7064
false−0.8842
false−0.1249
false−0.5039
false−0.5228
false−0.2672
false−0.6600
true0.0004
false−0.2038
false−0.0569
false−0.2050
false−0.3041
false−0.6747
false−0.4018
false−0.6309
false−0.1680
false−0.3066
false−0.3530
false−0.7007
false−0.0002
false−0.3471
false−0.0003
false−0.2637
false−0.4869
false−1.170
false−0.4593
false−0.3679
false−0.2207
false−0.3180
false−0.2365
false−0.4202
true0.0002

First 60 of 532 rows.

Most anomalous rows

RankRowOne-class SVM scoreMost unusualBiggest score dropnpregglubpskinbmipedage
11570.5142skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.681 at its median2197709934.7000.575062
23980.3378ped = 2.42 (robust z +7.6); 26% of its tail scoreno single feature lowers it0180786359.4002.42025
32790.1742bmi = 67.1 (robust z +5.2); 33% of its tail scoreped: falls 0.0249 at its median01291104667.1000.319026
4110.1363ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.259 at its median0137403543.1002.28833
52570.0962bp = 30 (robust z -3.5); 30% of its tail scoreage: falls 0.00225 at its median1883042550.496026
62550.0004bmi = 53.2 (robust z +3.1); 27% of its tail scoreglu: falls 0.0456 at its median0162765653.2000.759025
74490.0004npreg = 11 (robust z +3.0); 20% of its tail scorebmi: falls 0.393 at its median11103684046.2000.126042
8360.0004npreg = 13 (robust z +3.7); 25% of its tail scorebmi: falls 0.228 at its median13145821922.2000.245057
94920.0004bmi = 57.3 (robust z +3.7); 33% of its tail scorebmi: falls 0.109 at its median31231003557.3000.880022
103270.0003bp = 88 (robust z +1.3); 18% of its tail scoreglu: falls 0.299 at its median078882936.9000.434021
111470.0003glu = 56 (robust z -2.0); 42% of its tail scoreglu: falls 0.464 at its median256562824.2000.332022
125260.0003glu = 181 (robust z +2.2); 19% of its tail scoreglu: falls 0.279 at its median0181884443.3000.222026
133470.0003ped = 1.476 (robust z +4.0); 29% of its tail scoreped: falls 0.699 at its median8118721923.1001.47646
144320.0003age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 0.205 at its median612990719.6000.582060
154400.0002bp = 90 (robust z +1.5); 22% of its tail scoreglu: falls 0.179 at its median484902339.5000.159025
16600.0002bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.398 at its median81671064637.6000.165043
17130.0002age = 59 (robust z +3.5); 28% of its tail scoreage: falls 0.359 at its median1189602330.1000.398059
185300.0002age = 63 (robust z +3.9); 29% of its tail scoreskin: falls 0.332 at its median10101764832.9000.171063
192960.0002ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.337 at its median4197703936.7002.32931
205200.0002npreg = 13 (robust z +3.7); 26% of its tail scorenpreg: falls 0.802 at its median13153883740.6001.17439
The exact R script · R R version 4.5.1 (2025-06-13)
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec 1be6576db7edad53
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)


# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    npreg = "numeric",
    glu = "numeric",
    bp = "numeric",
    skin = "numeric",
    bmi = "numeric",
    ped = "numeric",
    age = "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

# %% Scores (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU <- 0.05
GAMMA <- NULL
if (is.null(GAMMA)) {
  v <- mean((X - mean(X))^2)  # population variance of every entry (scikit-learn's "scale")
  GAMMA <- if (v > 0) 1 / (ncol(X) * v) else 1
}
model <- e1071::svm(x = X, type = "one-classification", kernel = "radial", gamma = GAMMA, nu = NU,
                    scale = FALSE, tolerance = 1e-3, shrinking = TRUE)
dv <- attr(stats::predict(model, X, decision.values = TRUE), "decision.values")
scores <- -as.numeric(dv)
SCORE_LABEL <- "One-class SVM score"
ENGINE_PACKAGES <- c("e1071", "nanoparquet")
extra_values <- list(gamma = GAMMA, nu = NU, n_support = nrow(model$SV), outside_boundary = sum(scores > 0))

rescore <- function(Q, where0, col0) -as.numeric(attr(stats::predict(model, Q, decision.values = TRUE), "decision.values"))  # the fitted boundary, no refit


# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
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.ocsvm/pima/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.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; Phase 11 DS1)
NUMERIC <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")
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]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  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
})
cs_publish(list(
  title = "One-class SVM",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = 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))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  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 = 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))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

27 of 532 rows (5.1%) are flagged as anomalies (One-class SVM score ≥ 6.22e-05).

Anomalies
27
Threshold
6.217e-5

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

Most anomalous rows

RankRowOne-class SVM scoreMost unusualBiggest score dropnpregglubpskinbmipedage
11570.5142skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 0.681 at its median2197709934.7000.575062
23980.3378ped = 2.42 (robust z +7.6); 26% of its tail scoreno single feature lowers it0180786359.4002.42025
32790.1742bmi = 67.1 (robust z +5.2); 33% of its tail scoreped: falls 0.0249 at its median01291104667.1000.319026
4110.1363ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 0.259 at its median0137403543.1002.28833
52570.0962bp = 30 (robust z -3.5); 30% of its tail scoreage: falls 0.00225 at its median1883042550.496026
62550.0004bmi = 53.2 (robust z +3.1); 27% of its tail scoreglu: falls 0.0456 at its median0162765653.2000.759025
74490.0004npreg = 11 (robust z +3.0); 20% of its tail scorebmi: falls 0.393 at its median11103684046.2000.126042
8360.0004npreg = 13 (robust z +3.7); 25% of its tail scorebmi: falls 0.228 at its median13145821922.2000.245057
94920.0004bmi = 57.3 (robust z +3.7); 33% of its tail scorebmi: falls 0.109 at its median31231003557.3000.880022
103270.0003bp = 88 (robust z +1.3); 18% of its tail scoreglu: falls 0.299 at its median078882936.9000.434021
111470.0003glu = 56 (robust z -2.0); 42% of its tail scoreglu: falls 0.464 at its median256562824.2000.332022
125260.0003glu = 181 (robust z +2.2); 19% of its tail scoreglu: falls 0.279 at its median0181884443.3000.222026
133470.0003ped = 1.476 (robust z +4.0); 29% of its tail scoreped: falls 0.699 at its median8118721923.1001.47646
144320.0003age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 0.205 at its median612990719.6000.582060
154400.0002bp = 90 (robust z +1.5); 22% of its tail scoreglu: falls 0.179 at its median484902339.5000.159025
16600.0002bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 0.398 at its median81671064637.6000.165043
17130.0002age = 59 (robust z +3.5); 28% of its tail scoreage: falls 0.359 at its median1189602330.1000.398059
185300.0002age = 63 (robust z +3.9); 29% of its tail scoreskin: falls 0.332 at its median10101764832.9000.171063
192960.0002ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 0.337 at its median4197703936.7002.32931
205200.0002npreg = 13 (robust z +3.7); 26% of its tail scorenpreg: falls 0.802 at its median13153883740.6001.17439
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec 1be6576db7edad53
# Dataset: ml_pima (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
from sklearn.svm import OneClassSVM

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"])
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "npreg": "numeric",
        "glu": "numeric",
        "bp": "numeric",
        "skin": "numeric",
        "bmi": "numeric",
        "ped": "numeric",
        "age": "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))

# %% Scores (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU = 0.05
GAMMA = None
if GAMMA is None:
    var = float(X.var())
    GAMMA = 1.0 / (X.shape[1] * var) if var > 0 else 1.0
model = OneClassSVM(kernel="rbf", nu=NU, gamma=GAMMA, tol=1e-3, shrinking=True).fit(X)
scores = -np.asarray(model.decision_function(X), dtype=np.float64)
SCORE_LABEL = "One-class SVM score"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"gamma": float(GAMMA), "nu": float(NU), "n_support": int(len(model.support_)), "outside_boundary": int(np.sum(scores > 0))}

rescore = lambda Q, where, col: -np.asarray(model.decision_function(Q), dtype=np.float64)  # the fitted boundary, no refit


# %% Flag anomalies
RULE = "share"
_cutoff = 0
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.ocsvm/pima/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.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; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age", ]
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])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _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)
pct = flags.mean()
cs.publish({
    "title": "One-class SVM",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "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": [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)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})

The setting ν\nu was 0.0500, and 34 of 532 training rows fell outside. In theory ν\nu bounds the share of training rows outside and of support vectors; it isn't a promise about future data. It interacts strongly with the RBF width, so tune both, and calibrate the threshold on separate normal rows.

07

SVDD: the smallest sphere

Read

SVDDSupport vector data description (SVDD)The smallest sphere in feature space that encloses most rows; the score is squared distance to its center minus its squared radius. finds the smallest sphere in feature space that holds most rows: minimize R2+C∑iξiR^2+C\sum_i\xi_i with ∥ϕ(xi)−a∥2≤R2+ξi\lVert\phi(x_i)-a\rVert^2\le R^2+\xi_i. A row's score is its squared distance from the center aa minus R2R^2.

With an RBF kernel, every row has the same length in feature space, so the sphere and the one-class SVM's plane cut off the same rows when C=1/(νn)C=1/(\nu n). With other kernels they differ. A contaminated reference set inflates the sphere, and the score is a distance, not a probability.

One-class SVMRecorded · Python and R agreeRecorded 2026-11-25 · 83 values compared
R

3 of 50 rows (6.0%) are flagged as anomalies (SVDD score (d² − R²) ≥ 8.29e-05).

Anomalies
3
Threshold
8.292e-5

Plots

SVDD score (d² − R²) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalySVDD score (d² − R²)
false−0.0309
false−3.872e-5
false6.307e-5
false4.520e-5
false1.442e-5
false2.905e-5
false−0.0294
false5.054e-5
false−1.363e-5
false5.662e-5
false−0.0002
false6.971e-5
false−0.0037
false−0.0373
false−0.0093
false−0.0531
false−3.664e-5
false−0.0121
false−0.0048
true8.292e-5
false−0.0414
false−0.0531
false−0.0190
false−5.402e-5
false−0.0313
false−0.0298
false−0.0382
true0.0001
false−0.0058
false3.724e-5
false−0.0318
true0.0001
false1.442e-5
false−0.0002
false−0.0451
false−0.0596
false−1.743e-5
false−0.0476
false−3.761e-5
false−0.0214
false−0.0301
false−0.0062
false5.752e-5
false−0.0069
false−0.0001
false−0.0412
false−0.0114
false−0.0001
false2.676e-5
false−0.0315

Most anomalous rows

RankRowSVDD score (d² − R²)Most unusualBiggest score dropMurderAssaultUrbanPopRape
1280.0001Rape = 46 (robust z +3.0); 45% of its tail scoreno single feature lowers it12.2002528146
2320.0001UrbanPop = 86 (robust z +1.1); 38% of its tail scoreUrbanPop: falls 0.0261 at its median11.1002548626.100
3208.292e-5Assault = 300 (robust z +1.3); 44% of its tail scoreno single feature lowers it11.3003006727.800
4126.971e-5Murder = 2.6 (robust z -0.9); 34% of its tail scoreMurder: falls 0.0266 at its median2.6001205414.200
536.307e-5Rape = 31 (robust z +1.3); 28% of its tail scoreno single feature lowers it8.1002948031
6435.752e-5Murder = 12.7 (robust z +1.0); 33% of its tail scoreMurder: falls 0.0327 at its median12.7002018025.500
7105.662e-5Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.00702 at its median17.4002116025.800
885.054e-5Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.0583 at its median5.9002387215.800
944.520e-5UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.0383 at its median8.8001905019.500
10303.724e-5UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.0521 at its median7.4001598918.800
1162.905e-5Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.0378 at its median7.9002047838.700
12492.676e-5Rape = 10.8 (robust z -1.1); 29% of its tail scoreno single feature lowers it2.600536610.800
1351.442e-5Rape = 40.6 (robust z +2.4); 29% of its tail scoreno single feature lowers it92769140.600
14331.442e-5Assault = 337 (robust z +1.6); 43% of its tail scoreno single feature lowers it133374516.100
159−1.363e-5Assault = 335 (robust z +1.6); 35% of its tail scoreno single feature lowers it15.4003358031.900
1637−1.743e-5Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.0472 at its median4.9001596729.300
1717−3.664e-5UrbanPop = 52 (robust z -0.8); 31% of its tail scoreMurder: falls 0.0252 at its median9.7001095216.300
1839−3.761e-5Rape = 8.3 (robust z -1.4); 36% of its tail scoreAssault: falls 0.0024 at its median3.400174878.300
192−3.872e-5Rape = 44.5 (robust z +2.8); 40% of its tail scoreno single feature lowers it102634844.500
2024−5.402e-5Murder = 16.1 (robust z +1.6); 39% of its tail scoreRape: falls 0.00244 at its median16.1002594417.100
The exact R script · R R version 4.5.1 (2025-06-13)
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec d5cbd5cc0211c404
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)


# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = c("Murder", "Assault", "UrbanPop", "Rape"))), c("Murder", "Assault", "UrbanPop", "Rape"))
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    Murder = "numeric",
    Assault = "numeric",
    UrbanPop = "numeric",
    Rape = "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

# %% Scores (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU <- 0.1
GAMMA <- 0.5
if (is.null(GAMMA)) {
  v <- mean((X - mean(X))^2)  # population variance of every entry (scikit-learn's "scale")
  GAMMA <- if (v > 0) 1 / (ncol(X) * v) else 1
}
model <- e1071::svm(x = X, type = "one-classification", kernel = "radial", gamma = GAMMA, nu = NU,
                    scale = FALSE, tolerance = 1e-3, shrinking = TRUE)
dv <- attr(stats::predict(model, X, decision.values = TRUE), "decision.values")
scores <- -as.numeric(dv)
SCORE_LABEL <- "One-class SVM score"
ENGINE_PACKAGES <- c("e1071", "nanoparquet")
extra_values <- list(gamma = GAMMA, nu = NU, n_support = nrow(model$SV), outside_boundary = sum(scores > 0))

rescore <- function(Q, where0, col0) -as.numeric(attr(stats::predict(model, Q, decision.values = TRUE), "decision.values"))  # the fitted boundary, no refit

# %% SVDD view (Tax & Duin 2004): with the RBF kernel k(x, x) = 1, the SVDD with C = 1/(νn) has the
# one-class solution scaled, β = α / (νn). Score = ‖φ(x) − a‖² − R² = −2 f(x) / (νn); 0 is the boundary.
.nl <- NU * nrow(X)
.beta <- as.numeric(model$coefs) / .nl
.K <- exp(-GAMMA * cs_ml_ax_dist_matrix(model$SV)^2)
.cn2 <- as.numeric(t(.beta) %*% .K %*% .beta)  # ‖a‖² = βᵀKβ
.r2 <- 1 - 2 * model$rho / .nl + .cn2
scores <- scores * (2 / .nl)
SCORE_LABEL <- "SVDD score (d² − R²)"
extra_values[["svdd[radius]"]] <- sqrt(max(.r2, 0))
extra_values[["svdd[c]"]] <- 1 / .nl
extra_values[["svdd[center_norm2]"]] <- .cn2
rescore <- function(Q, where0, col0) -as.numeric(attr(stats::predict(model, Q, decision.values = TRUE), "decision.values")) * (2 / .nl)

# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
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.ocsvm/usarrests_svdd/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.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; Phase 11 DS1)
NUMERIC <- c("Murder", "Assault", "UrbanPop", "Rape")
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]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  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
})
cs_publish(list(
  title = "One-class SVM",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = 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))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  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 = 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))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

3 of 50 rows (6.0%) are flagged as anomalies (SVDD score (d² − R²) ≥ 8.29e-05).

Anomalies
3
Threshold
8.292e-5

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

Most anomalous rows

RankRowSVDD score (d² − R²)Most unusualBiggest score dropMurderAssaultUrbanPopRape
1280.0001Rape = 46 (robust z +3.0); 45% of its tail scoreno single feature lowers it12.2002528146
2320.0001UrbanPop = 86 (robust z +1.1); 38% of its tail scoreUrbanPop: falls 0.0261 at its median11.1002548626.100
3208.292e-5Assault = 300 (robust z +1.3); 44% of its tail scoreno single feature lowers it11.3003006727.800
4126.971e-5Murder = 2.6 (robust z -0.9); 34% of its tail scoreMurder: falls 0.0266 at its median2.6001205414.200
536.307e-5Rape = 31 (robust z +1.3); 28% of its tail scoreno single feature lowers it8.1002948031
6435.752e-5Murder = 12.7 (robust z +1.0); 33% of its tail scoreMurder: falls 0.0327 at its median12.7002018025.500
7105.662e-5Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.00702 at its median17.4002116025.800
885.054e-5Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.0583 at its median5.9002387215.800
944.520e-5UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.0383 at its median8.8001905019.500
10303.724e-5UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.0521 at its median7.4001598918.800
1162.905e-5Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.0378 at its median7.9002047838.700
12492.676e-5Rape = 10.8 (robust z -1.1); 29% of its tail scoreno single feature lowers it2.600536610.800
1351.442e-5Rape = 40.6 (robust z +2.4); 29% of its tail scoreno single feature lowers it92769140.600
14331.442e-5Assault = 337 (robust z +1.6); 43% of its tail scoreno single feature lowers it133374516.100
159−1.363e-5Assault = 335 (robust z +1.6); 35% of its tail scoreno single feature lowers it15.4003358031.900
1637−1.743e-5Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.0472 at its median4.9001596729.300
1717−3.664e-5UrbanPop = 52 (robust z -0.8); 31% of its tail scoreMurder: falls 0.0252 at its median9.7001095216.300
1839−3.761e-5Rape = 8.3 (robust z -1.4); 36% of its tail scoreAssault: falls 0.0024 at its median3.400174878.300
192−3.872e-5Rape = 44.5 (robust z +2.8); 40% of its tail scoreno single feature lowers it102634844.500
2024−5.402e-5Murder = 16.1 (robust z +1.6); 39% of its tail scoreRape: falls 0.00244 at its median16.1002594417.100
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# One-class SVM
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ocsvm 1.2.0 · spec d5cbd5cc0211c404
# Dataset: ml_usarrests (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
from sklearn.svm import OneClassSVM

import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import embed as csembed

# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "Murder": "numeric",
        "Assault": "numeric",
        "UrbanPop": "numeric",
        "Rape": "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))

# %% Scores (LIBSVM ν one-class; score = −decision value, 0 = the boundary)
NU = 0.1
GAMMA = 0.5
if GAMMA is None:
    var = float(X.var())
    GAMMA = 1.0 / (X.shape[1] * var) if var > 0 else 1.0
model = OneClassSVM(kernel="rbf", nu=NU, gamma=GAMMA, tol=1e-3, shrinking=True).fit(X)
scores = -np.asarray(model.decision_function(X), dtype=np.float64)
SCORE_LABEL = "One-class SVM score"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"gamma": float(GAMMA), "nu": float(NU), "n_support": int(len(model.support_)), "outside_boundary": int(np.sum(scores > 0))}

rescore = lambda Q, where, col: -np.asarray(model.decision_function(Q), dtype=np.float64)  # the fitted boundary, no refit

# %% SVDD view (Tax & Duin 2004): with the RBF kernel k(x, x) = 1, the SVDD with C = 1/(νn) has the
# one-class solution scaled, β = α / (νn). Score = ‖φ(x) − a‖² − R² = −2 f(x) / (νn); 0 is the boundary.
from codesplash.ml import anomaly_ext as csax

_nl = NU * X.shape[0]
_beta = np.asarray(model.dual_coef_, dtype=np.float64).ravel() / _nl
_K = np.exp(-GAMMA * csax.dist_matrix(np.asarray(model.support_vectors_, dtype=np.float64)) ** 2)
_cn2 = float(_beta @ _K @ _beta)  # ‖a‖² = βᵀKβ
_r2 = 1.0 - 2.0 * (-float(model.intercept_[0])) / _nl + _cn2  # ρ = −intercept
scores = scores * (2.0 / _nl)
SCORE_LABEL = "SVDD score (d² − R²)"
extra_values.update({"svdd[radius]": float(np.sqrt(max(_r2, 0.0))), "svdd[c]": 1.0 / _nl, "svdd[center_norm2]": _cn2})
rescore = lambda Q, where, col: -np.asarray(model.decision_function(Q), dtype=np.float64) * (2.0 / _nl)

# %% Flag anomalies
RULE = "share"
_cutoff = 0
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.ocsvm/usarrests_svdd/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.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; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["Murder", "Assault", "UrbanPop", "Rape", ]
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])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _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)
pct = flags.mean()
cs.publish({
    "title": "One-class SVM",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "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": [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)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Isolation forest (UCL048)Runs in CodeSplash: Isolation forest
Extended isolation forest (UCL049)Runs in CodeSplash: Isolation forest, Split dimensions above 1
HBOS (UCL055)Runs as an option of ECOD anomaly scores: Score HBOS
One-class SVM (UCL056)Runs in CodeSplash: One-class SVM
SVDD (UCL057)Runs as an option of One-class SVM: Sphere (SVDD)
COPOD (UCL059)Runs as an option of ECOD anomaly scores: Score COPOD
ECOD (UCL060)Runs in CodeSplash: ECOD anomaly scores
09

Check your understanding

Checkpoint

Check yourself

Why does a short average path length mean a row is anomalous?

Show the answer

Answer: a

Rows in dense regions need many cuts before they stand alone. Rare, different rows are isolated early.

Check yourself

You set the share flagged to 5%. What have you told the isolation forest?

Show the answer

Answer: b

The share sets a cutoff on the ranking. It is a decision, not an estimate of the anomaly rate.

Check yourself

What problem do extended isolation forests fix?

Show the answer

Answer: b

One-column cuts favor rows lined up with dense regions along an axis. Mixing columns in each cut makes the score depend less on the axes.

Check yourself

Is the extended forest always the better choice?

Show the answer

Answer: b

Removing one artifact doesn't guarantee better detection on your data. Let a held-out comparison decide.

Check yourself

What does HBOS assume when it adds per-column histogram scores?

Show the answer

Answer: a

Summing per-column log densities treats columns as independent. Look at each column's contribution to see what drives a flag.

Check yourself

A value falls in an empty histogram bin. What must HBOS do?

Show the answer

Answer: b

An empty bin has estimated density zero, and the log of zero is minus infinity. Bin edges and floors change scores, so check sensitivity.

Check yourself

You train a one-class SVM with ν = 0.05. What can you say about new data?

Show the answer

Answer: b

ν bounds training fractions under the optimization's assumptions. Future false-alarm rates need calibration data.

Check yourself

Why tune the RBF width together with ν?

Show the answer

Answer: b

Both settings shape the boundary. Check the acceptance region and held-out normal coverage across a small grid.

Check yourself

When do SVDD and the one-class SVM flag the same rows?

Show the answer

Answer: a

With a translation-invariant kernel, the smallest sphere and the separating plane coincide. With other kernels they can differ.

Check yourself

The reference data used to fit SVDD contain several anomalies. What happens?

Show the answer

Answer: b

Slack helps, but contamination still pulls the center and widens the radius. Clean the reference set where you can.

Check yourself

COPOD has "copula" in its name. Does it fit a multivariate copula density?

Show the answer

Answer: b

COPOD scores marginal tails. For a real dependence model, use a copula density or a multivariate detector.

Check yourself

Why do COPOD and ECOD scores depend on the number of reference rows?

Show the answer

Answer: a

With 100 reference rows, nothing can look rarer than about 1 in 100 on one column. Check stability under resampling of the reference set.

Check yourself

An ECOD flag comes with per-column contributions. Why look at them?

Show the answer

Answer: b

ECOD is a sum over columns, so the contributions explain it directly.

Check yourself

ECOD is fast and needs no tuning. How should you use it?

Show the answer

Answer: b

A good default is still a default. It can miss combination anomalies, so check it against detectors that see dependence.

10

Do it on your own data

In the app

Under Spot anomalies, start with Isolation forest and ECOD anomaly scores as quick baselines, try Split dimensions above 1 and the COPOD or HBOS scores, and use One-class SVM (or Sphere (SVDD)) when normal data have a curved shape.

Concepts in this lesson