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.
What runs in CodeSplash
- UCL048Isolation Forest Runs in CodeSplash
- UCL049Extended Isolation Forest Runs in CodeSplash
- UCL055Histogram-Based Outlier Score (HBOS) Runs in CodeSplash
- UCL056One-class support vector machine Runs in CodeSplash
- UCL057Support Vector Data Description (SVDD) Runs in CodeSplash
- UCL059Copula-Based Outlier Detection (COPOD) Runs in CodeSplash
- UCL060Empirical Cumulative Distribution Outlier Detection (ECOD) Runs in CodeSplash
- Isolation forest Verified in Python and R
- ECOD anomaly scores Verified in Python and R
- One-class SVM Verified in Python and R
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
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.)
Commit your prediction above to see the result
Make your prediction to see the result.
Isolation forest: short paths
ReadEach 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 over trees: , where is the average path length for a subsample of size . Scores near 1 are anomalous; around 0.5 is ordinary.
27 of 532 rows (5.1%) are flagged as anomalies (Isolation score ≥ 0.544).
- Anomalies
- 27
- Threshold
- 0.5439
Plots
View data
| Anomaly | Isolation score |
|---|---|
| false | 0.4081 |
| false | 0.5287 |
| false | 0.4413 |
| false | 0.4636 |
| false | 0.4169 |
| false | 0.4347 |
| false | 0.4074 |
| false | 0.4973 |
| false | 0.5010 |
| false | 0.4784 |
| true | 0.5893 |
| false | 0.4503 |
| false | 0.5303 |
| true | 0.5869 |
| false | 0.4832 |
| false | 0.4453 |
| false | 0.4789 |
| false | 0.5061 |
| false | 0.4188 |
| false | 0.4556 |
| false | 0.4309 |
| false | 0.4163 |
| false | 0.4443 |
| false | 0.4376 |
| false | 0.3962 |
| false | 0.4868 |
| false | 0.4475 |
| false | 0.4318 |
| false | 0.4052 |
| false | 0.3880 |
| false | 0.4534 |
| false | 0.4077 |
| false | 0.4203 |
| false | 0.4442 |
| false | 0.4156 |
| true | 0.5612 |
| false | 0.4338 |
| false | 0.4865 |
| false | 0.4497 |
| false | 0.4056 |
| false | 0.5027 |
| false | 0.4411 |
| false | 0.4342 |
| false | 0.4533 |
| false | 0.4100 |
| false | 0.4241 |
| false | 0.3961 |
| false | 0.5211 |
| false | 0.4149 |
| true | 0.5698 |
| false | 0.4223 |
| false | 0.3942 |
| false | 0.4276 |
| false | 0.3996 |
| false | 0.3894 |
| false | 0.4685 |
| false | 0.4098 |
| false | 0.4536 |
| false | 0.4511 |
| false | 0.5424 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | Isolation score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 0.6665 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 0.0805 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 157 | 0.6541 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.126 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 279 | 0.5900 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 0.104 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.5893 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.0926 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 432 | 0.5892 | age = 60 (robust z +3.6); 19% of its tail score | bmi: falls 0.0492 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 6 | 221 | 0.5880 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 0.0554 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 7 | 14 | 0.5869 | npreg = 12 (robust z +3.4); 19% of its tail score | npreg: falls 0.0653 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 8 | 417 | 0.5850 | age = 58 (robust z +3.4); 21% of its tail score | age: falls 0.0749 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 9 | 491 | 0.5701 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.0591 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 10 | 50 | 0.5698 | ped = 1.394 (robust z +3.7); 21% of its tail score | ped: falls 0.0674 at its median | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 11 | 306 | 0.5633 | ped = 1.213 (robust z +3.0); 19% of its tail score | ped: falls 0.0492 at its median | 9 | 184 | 85 | 15 | 30 | 1.213 | 49 |
| 12 | 272 | 0.5613 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 0.0954 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 13 | 36 | 0.5612 | npreg = 13 (robust z +3.7); 25% of its tail score | npreg: falls 0.0451 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 14 | 296 | 0.5607 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.101 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 15 | 140 | 0.5587 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 0.0604 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 16 | 403 | 0.5566 | age = 81 (robust z +6.0); 44% of its tail score | age: falls 0.105 at its median | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 17 | 255 | 0.5536 | bmi = 53.2 (robust z +3.1); 27% of its tail score | bmi: falls 0.0537 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 18 | 358 | 0.5532 | age = 65 (robust z +4.2); 31% of its tail score | age: falls 0.0785 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 19 | 222 | 0.5529 | ped = 1.893 (robust z +5.6); 31% of its tail score | ped: falls 0.0861 at its median | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 20 | 218 | 0.5519 | ped = 1.39 (robust z +3.7); 27% of its tail score | ped: falls 0.0804 at its median | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
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"))
))
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
| Rank | Row | Isolation score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 0.6665 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 0.0805 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 157 | 0.6541 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.126 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 279 | 0.5900 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 0.104 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.5893 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.0926 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 432 | 0.5892 | age = 60 (robust z +3.6); 19% of its tail score | bmi: falls 0.0492 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 6 | 221 | 0.5880 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 0.0554 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 7 | 14 | 0.5869 | npreg = 12 (robust z +3.4); 19% of its tail score | npreg: falls 0.0653 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 8 | 417 | 0.5850 | age = 58 (robust z +3.4); 21% of its tail score | age: falls 0.0749 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 9 | 491 | 0.5701 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.0591 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 10 | 50 | 0.5698 | ped = 1.394 (robust z +3.7); 21% of its tail score | ped: falls 0.0674 at its median | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 11 | 306 | 0.5633 | ped = 1.213 (robust z +3.0); 19% of its tail score | ped: falls 0.0492 at its median | 9 | 184 | 85 | 15 | 30 | 1.213 | 49 |
| 12 | 272 | 0.5613 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 0.0954 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 13 | 36 | 0.5612 | npreg = 13 (robust z +3.7); 25% of its tail score | npreg: falls 0.0451 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 14 | 296 | 0.5607 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.101 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 15 | 140 | 0.5587 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 0.0604 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 16 | 403 | 0.5566 | age = 81 (robust z +6.0); 44% of its tail score | age: falls 0.105 at its median | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 17 | 255 | 0.5536 | bmi = 53.2 (robust z +3.1); 27% of its tail score | bmi: falls 0.0537 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 18 | 358 | 0.5532 | age = 65 (robust z +4.2); 31% of its tail score | age: falls 0.0785 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 19 | 222 | 0.5529 | ped = 1.893 (robust z +5.6); 31% of its tail score | ped: falls 0.0861 at its median | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 20 | 218 | 0.5519 | ped = 1.39 (robust z +3.7); 27% of its tail score | ped: falls 0.0804 at its median | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
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.
Extended isolation forest
ReadCuts 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 left when for a random point and direction ; the extension level sets how many columns each cut mixes.
16 of 153 rows (10.5%) are flagged as anomalies (Isolation score ≥ 0.538).
- Anomalies
- 16
- Threshold
- 0.5376
Plots
View data
| Anomaly | Isolation score |
|---|---|
| false | 0.4820 |
| false | 0.4463 |
| false | 0.4251 |
| false | 0.5036 |
| false | 0.5120 |
| false | 0.4744 |
| false | 0.4801 |
| false | 0.5106 |
| true | 0.6110 |
| false | 0.4300 |
| false | 0.4407 |
| false | 0.4354 |
| false | 0.4814 |
| false | 0.4539 |
| false | 0.5312 |
| false | 0.5097 |
| false | 0.4909 |
| true | 0.5861 |
| false | 0.4895 |
| false | 0.4892 |
| true | 0.5401 |
| false | 0.5322 |
| false | 0.5135 |
| false | 0.4995 |
| true | 0.5664 |
| true | 0.5406 |
| false | 0.4879 |
| false | 0.4931 |
| false | 0.4760 |
| true | 0.5378 |
| false | 0.4343 |
| false | 0.4145 |
| false | 0.4222 |
| false | 0.5095 |
| false | 0.4070 |
| false | 0.4078 |
| false | 0.4376 |
| false | 0.4234 |
| false | 0.4328 |
| true | 0.5388 |
| false | 0.5119 |
| false | 0.4612 |
| false | 0.4495 |
| false | 0.4119 |
| false | 0.5154 |
| false | 0.4745 |
| false | 0.4420 |
| true | 0.5798 |
| false | 0.4765 |
| false | 0.4284 |
| false | 0.4227 |
| false | 0.4241 |
| false | 0.5201 |
| false | 0.4574 |
| false | 0.4180 |
| false | 0.4055 |
| false | 0.4009 |
| false | 0.4471 |
| false | 0.4279 |
| false | 0.5088 |
First 60 of 153 rows.
Most anomalous rows
| Rank | Row | Isolation score | Most unusual | Biggest score drop | Ozone | solar radiation | Wind | Temp |
|---|---|---|---|---|---|---|---|---|
| 1 | 117 | 0.6220 | Ozone = 168 (robust z +7.4); 48% of its tail score | Ozone: falls 0.147 at its median | 168 | 238 | 3.400 | 81 |
| 2 | 9 | 0.6110 | Wind = 20.1 (robust z +3.0); 32% of its tail score | Wind: falls 0.0941 at its median | 8 | 19 | 20.100 | 61 |
| 3 | 121 | 0.6097 | Ozone = 118 (robust z +4.7); 29% of its tail score | Ozone: falls 0.0616 at its median | 118 | 225 | 2.300 | 94 |
| 4 | 18 | 0.5861 | Wind = 18.4 (robust z +2.6); 30% of its tail score | Wind: falls 0.0693 at its median | 6 | 78 | 18.400 | 57 |
| 5 | 62 | 0.5818 | Ozone = 135 (robust z +5.6); 41% of its tail score | Ozone: falls 0.1 at its median | 135 | 269 | 4.100 | 84 |
| 6 | 48 | 0.5798 | Wind = 20.7 (robust z +3.2); 52% of its tail score | Wind: falls 0.135 at its median | 37 | 284 | 20.700 | 72 |
| 7 | 25 | 0.5664 | Temp = 57 (robust z -2.5); 39% of its tail score | Temp: falls 0.0518 at its median | — | 66 | 16.600 | 57 |
| 8 | 148 | 0.5598 | Wind = 16.6 (robust z +2.0); 30% of its tail score | Wind: falls 0.0675 at its median | 14 | 20 | 16.600 | 63 |
| 9 | 99 | 0.5593 | Ozone = 122 (robust z +4.9); 37% of its tail score | Ozone: falls 0.0649 at its median | 122 | 255 | 4 | 89 |
| 10 | 126 | 0.5491 | Ozone = 73 (robust z +2.2); 19% of its tail score | Wind: falls 0.0467 at its median | 73 | 183 | 2.800 | 93 |
| 11 | 122 | 0.5425 | Ozone = 84 (robust z +2.8); 24% of its tail score | Temp: falls 0.0762 at its median | 84 | 237 | 6.300 | 96 |
| 12 | 26 | 0.5406 | Temp = 58 (robust z -2.4); 43% of its tail score | Temp: falls 0.0911 at its median | — | 266 | 14.900 | 58 |
| 13 | 21 | 0.5401 | Temp = 59 (robust z -2.2); 23% of its tail score | Temp: falls 0.0358 at its median | 1 | 8 | 9.700 | 59 |
| 14 | 40 | 0.5388 | Ozone = 71 (robust z +2.1); 22% of its tail score | Wind: falls 0.0488 at its median | 71 | 291 | 13.800 | 90 |
| 15 | 30 | 0.5378 | Ozone = 115 (robust z +4.5); 48% of its tail score | Ozone: falls 0.111 at its median | 115 | 223 | 5.700 | 79 |
| 16 | 120 | 0.5376 | Ozone = 76 (robust z +2.4); 23% of its tail score | Temp: falls 0.0793 at its median | 76 | 203 | 9.700 | 97 |
| 17 | 22 | 0.5322 | Wind = 16.6 (robust z +2.0); 32% of its tail score | Wind: falls 0.0645 at its median | 11 | 320 | 16.600 | 73 |
| 18 | 15 | 0.5312 | Temp = 58 (robust z -2.4); 39% of its tail score | Temp: falls 0.0483 at its median | 18 | 65 | 13.200 | 58 |
| 19 | 124 | 0.5288 | Ozone = 96 (robust z +3.5); 36% of its tail score | Ozone: falls 0.0418 at its median | 96 | 167 | 6.900 | 91 |
| 20 | 94 | 0.5253 | solar radiation = 24 (robust z -2.0); 36% of its tail score | solar radiation: falls 0.0599 at its median | 9 | 24 | 13.800 | 81 |
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"))
))
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
| Rank | Row | Isolation score | Most unusual | Biggest score drop | Ozone | solar radiation | Wind | Temp |
|---|---|---|---|---|---|---|---|---|
| 1 | 117 | 0.6220 | Ozone = 168 (robust z +7.4); 48% of its tail score | Ozone: falls 0.147 at its median | 168 | 238 | 3.400 | 81 |
| 2 | 9 | 0.6110 | Wind = 20.1 (robust z +3.0); 32% of its tail score | Wind: falls 0.0941 at its median | 8 | 19 | 20.100 | 61 |
| 3 | 121 | 0.6097 | Ozone = 118 (robust z +4.7); 29% of its tail score | Ozone: falls 0.0616 at its median | 118 | 225 | 2.300 | 94 |
| 4 | 18 | 0.5861 | Wind = 18.4 (robust z +2.6); 30% of its tail score | Wind: falls 0.0693 at its median | 6 | 78 | 18.400 | 57 |
| 5 | 62 | 0.5818 | Ozone = 135 (robust z +5.6); 41% of its tail score | Ozone: falls 0.1 at its median | 135 | 269 | 4.100 | 84 |
| 6 | 48 | 0.5798 | Wind = 20.7 (robust z +3.2); 52% of its tail score | Wind: falls 0.135 at its median | 37 | 284 | 20.700 | 72 |
| 7 | 25 | 0.5664 | Temp = 57 (robust z -2.5); 39% of its tail score | Temp: falls 0.0518 at its median | — | 66 | 16.600 | 57 |
| 8 | 148 | 0.5598 | Wind = 16.6 (robust z +2.0); 30% of its tail score | Wind: falls 0.0675 at its median | 14 | 20 | 16.600 | 63 |
| 9 | 99 | 0.5593 | Ozone = 122 (robust z +4.9); 37% of its tail score | Ozone: falls 0.0649 at its median | 122 | 255 | 4 | 89 |
| 10 | 126 | 0.5491 | Ozone = 73 (robust z +2.2); 19% of its tail score | Wind: falls 0.0467 at its median | 73 | 183 | 2.800 | 93 |
| 11 | 122 | 0.5425 | Ozone = 84 (robust z +2.8); 24% of its tail score | Temp: falls 0.0762 at its median | 84 | 237 | 6.300 | 96 |
| 12 | 26 | 0.5406 | Temp = 58 (robust z -2.4); 43% of its tail score | Temp: falls 0.0911 at its median | — | 266 | 14.900 | 58 |
| 13 | 21 | 0.5401 | Temp = 59 (robust z -2.2); 23% of its tail score | Temp: falls 0.0358 at its median | 1 | 8 | 9.700 | 59 |
| 14 | 40 | 0.5388 | Ozone = 71 (robust z +2.1); 22% of its tail score | Wind: falls 0.0488 at its median | 71 | 291 | 13.800 | 90 |
| 15 | 30 | 0.5378 | Ozone = 115 (robust z +4.5); 48% of its tail score | Ozone: falls 0.111 at its median | 115 | 223 | 5.700 | 79 |
| 16 | 120 | 0.5376 | Ozone = 76 (robust z +2.4); 23% of its tail score | Temp: falls 0.0793 at its median | 76 | 203 | 9.700 | 97 |
| 17 | 22 | 0.5322 | Wind = 16.6 (robust z +2.0); 32% of its tail score | Wind: falls 0.0645 at its median | 11 | 320 | 16.600 | 73 |
| 18 | 15 | 0.5312 | Temp = 58 (robust z -2.4); 39% of its tail score | Temp: falls 0.0483 at its median | 18 | 65 | 13.200 | 58 |
| 19 | 124 | 0.5288 | Ozone = 96 (robust z +3.5); 36% of its tail score | Ozone: falls 0.0418 at its median | 96 | 167 | 6.900 | 91 |
| 20 | 94 | 0.5253 | solar radiation = 24 (robust z -2.0); 36% of its tail score | solar radiation: falls 0.0599 at its median | 9 | 24 | 13.800 | 81 |
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.
Per-column surprise: HBOS, COPOD, ECOD
ReadThese 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.: 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, and , 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.
27 of 532 rows (5.1%) are flagged as anomalies (ECOD score ≥ 16).
- Anomalies
- 27
- Threshold
- 15.963
Plots
View data
| Anomaly | ECOD score |
|---|---|
| false | 7.981 |
| false | 15.166 |
| false | 13.068 |
| false | 13.510 |
| false | 11.891 |
| false | 9.075 |
| false | 8.886 |
| false | 14.376 |
| false | 12.985 |
| false | 10.909 |
| true | 17.860 |
| false | 11.191 |
| false | 12.666 |
| true | 17.991 |
| false | 13.771 |
| false | 12.474 |
| false | 15.089 |
| false | 14.422 |
| false | 7.909 |
| false | 14.136 |
| false | 11.022 |
| false | 7.176 |
| false | 10.402 |
| false | 13.710 |
| false | 8.555 |
| false | 11.424 |
| false | 13.799 |
| false | 9.667 |
| false | 8.737 |
| false | 5.989 |
| false | 13.545 |
| false | 8.109 |
| false | 8.461 |
| false | 9.706 |
| false | 8.882 |
| true | 16.647 |
| false | 11.188 |
| true | 16.763 |
| false | 10.444 |
| false | 9.313 |
| false | 13.418 |
| false | 10.573 |
| false | 10.293 |
| false | 14.260 |
| false | 9.631 |
| false | 11.692 |
| false | 7.454 |
| false | 12.292 |
| false | 8.652 |
| true | 18.684 |
| false | 11.423 |
| false | 8.756 |
| false | 9.253 |
| false | 9.216 |
| false | 8.962 |
| false | 10.646 |
| false | 10.617 |
| false | 12.766 |
| false | 10.170 |
| true | 17.192 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | ECOD score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 24.174 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 5.58 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 432 | 19.828 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 4.91 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 3 | 279 | 19.099 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 5.59 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 50 | 18.684 | ped = 1.394 (robust z +3.7); 21% of its tail score | glu: falls 5.59 at its median | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 5 | 228 | 18.665 | bp = 50 (robust z -1.9); 16% of its tail score | skin: falls 3.4 at its median | 1 | 73 | 50 | 10 | 23 | 0.2480 | 21 |
| 6 | 157 | 18.629 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 5.61 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 7 | 221 | 18.524 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 4.49 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 8 | 14 | 17.991 | npreg = 12 (robust z +3.4); 19% of its tail score | skin: falls 4.91 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 9 | 11 | 17.860 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 4.48 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 10 | 140 | 17.591 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 4.51 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 11 | 179 | 17.382 | npreg = 9 (robust z +2.4); 13% of its tail score | glu: falls 4.89 at its median | 9 | 57 | 80 | 37 | 32.800 | 0.0960 | 41 |
| 12 | 272 | 17.341 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 5.61 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 13 | 491 | 17.223 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.8 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 14 | 255 | 17.194 | bmi = 53.2 (robust z +3.1); 27% of its tail score | skin: falls 4.22 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 15 | 60 | 17.192 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.8 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 16 | 257 | 16.994 | bp = 30 (robust z -3.5); 30% of its tail score | bp: falls 4.5 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 17 | 38 | 16.763 | bp = 48 (robust z -2.0); 22% of its tail score | glu: falls 3.28 at its median | 1 | 71 | 48 | 18 | 20.400 | 0.3230 | 22 |
| 18 | 36 | 16.647 | npreg = 13 (robust z +3.7); 25% of its tail score | npreg: falls 3.53 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 19 | 358 | 16.613 | age = 65 (robust z +4.2); 31% of its tail score | age: falls 4.5 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 20 | 189 | 16.607 | skin = 10 (robust z -1.8); 25% of its tail score | skin: falls 3.4 at its median | 0 | 74 | 52 | 10 | 27.800 | 0.2690 | 22 |
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"))
))
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
| Rank | Row | ECOD score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 24.174 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 5.58 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 2 | 432 | 19.828 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 4.91 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 3 | 279 | 19.099 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 5.59 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 50 | 18.684 | ped = 1.394 (robust z +3.7); 21% of its tail score | glu: falls 5.59 at its median | 1 | 199 | 76 | 43 | 42.900 | 1.394 | 22 |
| 5 | 228 | 18.665 | bp = 50 (robust z -1.9); 16% of its tail score | skin: falls 3.4 at its median | 1 | 73 | 50 | 10 | 23 | 0.2480 | 21 |
| 6 | 157 | 18.629 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 5.61 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 7 | 221 | 18.524 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 4.49 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 8 | 14 | 17.991 | npreg = 12 (robust z +3.4); 19% of its tail score | skin: falls 4.91 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 9 | 11 | 17.860 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 4.48 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 10 | 140 | 17.591 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 4.51 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 11 | 179 | 17.382 | npreg = 9 (robust z +2.4); 13% of its tail score | glu: falls 4.89 at its median | 9 | 57 | 80 | 37 | 32.800 | 0.0960 | 41 |
| 12 | 272 | 17.341 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 5.61 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 13 | 491 | 17.223 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.8 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 14 | 255 | 17.194 | bmi = 53.2 (robust z +3.1); 27% of its tail score | skin: falls 4.22 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 15 | 60 | 17.192 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.8 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 16 | 257 | 16.994 | bp = 30 (robust z -3.5); 30% of its tail score | bp: falls 4.5 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 17 | 38 | 16.763 | bp = 48 (robust z -2.0); 22% of its tail score | glu: falls 3.28 at its median | 1 | 71 | 48 | 18 | 20.400 | 0.3230 | 22 |
| 18 | 36 | 16.647 | npreg = 13 (robust z +3.7); 25% of its tail score | npreg: falls 3.53 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 19 | 358 | 16.613 | age = 65 (robust z +4.2); 31% of its tail score | age: falls 4.5 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 20 | 189 | 16.607 | skin = 10 (robust z -1.8); 25% of its tail score | skin: falls 3.4 at its median | 0 | 74 | 52 | 10 | 27.800 | 0.2690 | 22 |
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"}],
})
Ordinary values, odd combination
PredictPredict 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?
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.
One-class SVM: a soft fence
ReadThe 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 with . Rows with fall outside.
27 of 532 rows (5.1%) are flagged as anomalies (One-class SVM score ≥ 6.22e-05).
- Anomalies
- 27
- Threshold
- 6.217e-5
Plots
View data
| Anomaly | One-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 |
| true | 0.1363 |
| false | −0.7790 |
| true | 0.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 |
| true | 0.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 |
| true | 0.0002 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | One-class SVM score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 0.5142 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.681 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 0.3378 | ped = 2.42 (robust z +7.6); 26% of its tail score | no single feature lowers it | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 279 | 0.1742 | bmi = 67.1 (robust z +5.2); 33% of its tail score | ped: falls 0.0249 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.1363 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.259 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 257 | 0.0962 | bp = 30 (robust z -3.5); 30% of its tail score | age: falls 0.00225 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 6 | 255 | 0.0004 | bmi = 53.2 (robust z +3.1); 27% of its tail score | glu: falls 0.0456 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 7 | 449 | 0.0004 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 0.393 at its median | 11 | 103 | 68 | 40 | 46.200 | 0.1260 | 42 |
| 8 | 36 | 0.0004 | npreg = 13 (robust z +3.7); 25% of its tail score | bmi: falls 0.228 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 9 | 492 | 0.0004 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 0.109 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 327 | 0.0003 | bp = 88 (robust z +1.3); 18% of its tail score | glu: falls 0.299 at its median | 0 | 78 | 88 | 29 | 36.900 | 0.4340 | 21 |
| 11 | 147 | 0.0003 | glu = 56 (robust z -2.0); 42% of its tail score | glu: falls 0.464 at its median | 2 | 56 | 56 | 28 | 24.200 | 0.3320 | 22 |
| 12 | 526 | 0.0003 | glu = 181 (robust z +2.2); 19% of its tail score | glu: falls 0.279 at its median | 0 | 181 | 88 | 44 | 43.300 | 0.2220 | 26 |
| 13 | 347 | 0.0003 | ped = 1.476 (robust z +4.0); 29% of its tail score | ped: falls 0.699 at its median | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 14 | 432 | 0.0003 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 0.205 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 15 | 440 | 0.0002 | bp = 90 (robust z +1.5); 22% of its tail score | glu: falls 0.179 at its median | 4 | 84 | 90 | 23 | 39.500 | 0.1590 | 25 |
| 16 | 60 | 0.0002 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.398 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 13 | 0.0002 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 0.359 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 18 | 530 | 0.0002 | age = 63 (robust z +3.9); 29% of its tail score | skin: falls 0.332 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 19 | 296 | 0.0002 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.337 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 20 | 520 | 0.0002 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 0.802 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
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"))
))
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
| Rank | Row | One-class SVM score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 0.5142 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 0.681 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 0.3378 | ped = 2.42 (robust z +7.6); 26% of its tail score | no single feature lowers it | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 279 | 0.1742 | bmi = 67.1 (robust z +5.2); 33% of its tail score | ped: falls 0.0249 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 4 | 11 | 0.1363 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 0.259 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 5 | 257 | 0.0962 | bp = 30 (robust z -3.5); 30% of its tail score | age: falls 0.00225 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 6 | 255 | 0.0004 | bmi = 53.2 (robust z +3.1); 27% of its tail score | glu: falls 0.0456 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 7 | 449 | 0.0004 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 0.393 at its median | 11 | 103 | 68 | 40 | 46.200 | 0.1260 | 42 |
| 8 | 36 | 0.0004 | npreg = 13 (robust z +3.7); 25% of its tail score | bmi: falls 0.228 at its median | 13 | 145 | 82 | 19 | 22.200 | 0.2450 | 57 |
| 9 | 492 | 0.0004 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 0.109 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 327 | 0.0003 | bp = 88 (robust z +1.3); 18% of its tail score | glu: falls 0.299 at its median | 0 | 78 | 88 | 29 | 36.900 | 0.4340 | 21 |
| 11 | 147 | 0.0003 | glu = 56 (robust z -2.0); 42% of its tail score | glu: falls 0.464 at its median | 2 | 56 | 56 | 28 | 24.200 | 0.3320 | 22 |
| 12 | 526 | 0.0003 | glu = 181 (robust z +2.2); 19% of its tail score | glu: falls 0.279 at its median | 0 | 181 | 88 | 44 | 43.300 | 0.2220 | 26 |
| 13 | 347 | 0.0003 | ped = 1.476 (robust z +4.0); 29% of its tail score | ped: falls 0.699 at its median | 8 | 118 | 72 | 19 | 23.100 | 1.476 | 46 |
| 14 | 432 | 0.0003 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 0.205 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 15 | 440 | 0.0002 | bp = 90 (robust z +1.5); 22% of its tail score | glu: falls 0.179 at its median | 4 | 84 | 90 | 23 | 39.500 | 0.1590 | 25 |
| 16 | 60 | 0.0002 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 0.398 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 13 | 0.0002 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 0.359 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 18 | 530 | 0.0002 | age = 63 (robust z +3.9); 29% of its tail score | skin: falls 0.332 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 19 | 296 | 0.0002 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 0.337 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 20 | 520 | 0.0002 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 0.802 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
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 was 0.0500, and 34 of 532 training rows fell outside. In theory 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.
SVDD: the smallest sphere
ReadSVDDSupport 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 with . A row's score is its squared distance from the center minus .
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 . With other kernels they differ. A contaminated reference set inflates the sphere, and the score is a distance, not a probability.
3 of 50 rows (6.0%) are flagged as anomalies (SVDD score (d² − R²) ≥ 8.29e-05).
- Anomalies
- 3
- Threshold
- 8.292e-5
Plots
View data
| Anomaly | SVDD score (d² − R²) |
|---|---|
| false | −0.0309 |
| false | −3.872e-5 |
| false | 6.307e-5 |
| false | 4.520e-5 |
| false | 1.442e-5 |
| false | 2.905e-5 |
| false | −0.0294 |
| false | 5.054e-5 |
| false | −1.363e-5 |
| false | 5.662e-5 |
| false | −0.0002 |
| false | 6.971e-5 |
| false | −0.0037 |
| false | −0.0373 |
| false | −0.0093 |
| false | −0.0531 |
| false | −3.664e-5 |
| false | −0.0121 |
| false | −0.0048 |
| true | 8.292e-5 |
| false | −0.0414 |
| false | −0.0531 |
| false | −0.0190 |
| false | −5.402e-5 |
| false | −0.0313 |
| false | −0.0298 |
| false | −0.0382 |
| true | 0.0001 |
| false | −0.0058 |
| false | 3.724e-5 |
| false | −0.0318 |
| true | 0.0001 |
| false | 1.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 |
| false | 5.752e-5 |
| false | −0.0069 |
| false | −0.0001 |
| false | −0.0412 |
| false | −0.0114 |
| false | −0.0001 |
| false | 2.676e-5 |
| false | −0.0315 |
Most anomalous rows
| Rank | Row | SVDD score (d² − R²) | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 28 | 0.0001 | Rape = 46 (robust z +3.0); 45% of its tail score | no single feature lowers it | 12.200 | 252 | 81 | 46 |
| 2 | 32 | 0.0001 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.0261 at its median | 11.100 | 254 | 86 | 26.100 |
| 3 | 20 | 8.292e-5 | Assault = 300 (robust z +1.3); 44% of its tail score | no single feature lowers it | 11.300 | 300 | 67 | 27.800 |
| 4 | 12 | 6.971e-5 | Murder = 2.6 (robust z -0.9); 34% of its tail score | Murder: falls 0.0266 at its median | 2.600 | 120 | 54 | 14.200 |
| 5 | 3 | 6.307e-5 | Rape = 31 (robust z +1.3); 28% of its tail score | no single feature lowers it | 8.100 | 294 | 80 | 31 |
| 6 | 43 | 5.752e-5 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.0327 at its median | 12.700 | 201 | 80 | 25.500 |
| 7 | 10 | 5.662e-5 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.00702 at its median | 17.400 | 211 | 60 | 25.800 |
| 8 | 8 | 5.054e-5 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.0583 at its median | 5.900 | 238 | 72 | 15.800 |
| 9 | 4 | 4.520e-5 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.0383 at its median | 8.800 | 190 | 50 | 19.500 |
| 10 | 30 | 3.724e-5 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.0521 at its median | 7.400 | 159 | 89 | 18.800 |
| 11 | 6 | 2.905e-5 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.0378 at its median | 7.900 | 204 | 78 | 38.700 |
| 12 | 49 | 2.676e-5 | Rape = 10.8 (robust z -1.1); 29% of its tail score | no single feature lowers it | 2.600 | 53 | 66 | 10.800 |
| 13 | 5 | 1.442e-5 | Rape = 40.6 (robust z +2.4); 29% of its tail score | no single feature lowers it | 9 | 276 | 91 | 40.600 |
| 14 | 33 | 1.442e-5 | Assault = 337 (robust z +1.6); 43% of its tail score | no single feature lowers it | 13 | 337 | 45 | 16.100 |
| 15 | 9 | −1.363e-5 | Assault = 335 (robust z +1.6); 35% of its tail score | no single feature lowers it | 15.400 | 335 | 80 | 31.900 |
| 16 | 37 | −1.743e-5 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.0472 at its median | 4.900 | 159 | 67 | 29.300 |
| 17 | 17 | −3.664e-5 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.0252 at its median | 9.700 | 109 | 52 | 16.300 |
| 18 | 39 | −3.761e-5 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Assault: falls 0.0024 at its median | 3.400 | 174 | 87 | 8.300 |
| 19 | 2 | −3.872e-5 | Rape = 44.5 (robust z +2.8); 40% of its tail score | no single feature lowers it | 10 | 263 | 48 | 44.500 |
| 20 | 24 | −5.402e-5 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.00244 at its median | 16.100 | 259 | 44 | 17.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"))
))
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
| Rank | Row | SVDD score (d² − R²) | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 28 | 0.0001 | Rape = 46 (robust z +3.0); 45% of its tail score | no single feature lowers it | 12.200 | 252 | 81 | 46 |
| 2 | 32 | 0.0001 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.0261 at its median | 11.100 | 254 | 86 | 26.100 |
| 3 | 20 | 8.292e-5 | Assault = 300 (robust z +1.3); 44% of its tail score | no single feature lowers it | 11.300 | 300 | 67 | 27.800 |
| 4 | 12 | 6.971e-5 | Murder = 2.6 (robust z -0.9); 34% of its tail score | Murder: falls 0.0266 at its median | 2.600 | 120 | 54 | 14.200 |
| 5 | 3 | 6.307e-5 | Rape = 31 (robust z +1.3); 28% of its tail score | no single feature lowers it | 8.100 | 294 | 80 | 31 |
| 6 | 43 | 5.752e-5 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.0327 at its median | 12.700 | 201 | 80 | 25.500 |
| 7 | 10 | 5.662e-5 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.00702 at its median | 17.400 | 211 | 60 | 25.800 |
| 8 | 8 | 5.054e-5 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.0583 at its median | 5.900 | 238 | 72 | 15.800 |
| 9 | 4 | 4.520e-5 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.0383 at its median | 8.800 | 190 | 50 | 19.500 |
| 10 | 30 | 3.724e-5 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.0521 at its median | 7.400 | 159 | 89 | 18.800 |
| 11 | 6 | 2.905e-5 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.0378 at its median | 7.900 | 204 | 78 | 38.700 |
| 12 | 49 | 2.676e-5 | Rape = 10.8 (robust z -1.1); 29% of its tail score | no single feature lowers it | 2.600 | 53 | 66 | 10.800 |
| 13 | 5 | 1.442e-5 | Rape = 40.6 (robust z +2.4); 29% of its tail score | no single feature lowers it | 9 | 276 | 91 | 40.600 |
| 14 | 33 | 1.442e-5 | Assault = 337 (robust z +1.6); 43% of its tail score | no single feature lowers it | 13 | 337 | 45 | 16.100 |
| 15 | 9 | −1.363e-5 | Assault = 335 (robust z +1.6); 35% of its tail score | no single feature lowers it | 15.400 | 335 | 80 | 31.900 |
| 16 | 37 | −1.743e-5 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.0472 at its median | 4.900 | 159 | 67 | 29.300 |
| 17 | 17 | −3.664e-5 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.0252 at its median | 9.700 | 109 | 52 | 16.300 |
| 18 | 39 | −3.761e-5 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Assault: falls 0.0024 at its median | 3.400 | 174 | 87 | 8.300 |
| 19 | 2 | −3.872e-5 | Rape = 44.5 (robust z +2.8); 40% of its tail score | no single feature lowers it | 10 | 263 | 48 | 44.500 |
| 20 | 24 | −5.402e-5 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.00244 at its median | 16.100 | 259 | 44 | 17.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"}],
})
Where each idea stands in CodeSplash
Read| Entry | In 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 |
Check your understanding
CheckpointCheck 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.
Do it on your own data
In the appUnder 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