Clusters, tails and spheres: CBLOF, COPOD, HBOS and SVDD
Score rows by their distance to large clusters (CBLOF), by how far into each column's tails they sit (COPOD, HBOS), or by their distance to an enclosing sphere (SVDD), and know what each one can't see.
What runs in CodeSplash
- Cluster-based local outlier factor (CBLOF) 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 how CBLOF splits clusters into large and small ones and scores each row
- Tell column-by-column detectors (ECOD, COPOD, HBOS) from ones that see combinations
- Read the one-class SVM as a sphere and relate the two scores
Distance to the big groups: CBLOF
ReadCBLOFCluster-based local outlier factor (CBLOF)k-means clusters split into large (normal) and small ones; each row scores its distance to its own large center or the nearest one. first runs k-means. It sorts the clusters by size and calls the largest ones normal: together they must hold a share α of the rows (90% by default), or end where the next cluster is β times smaller (5 by default). A row in a large cluster scores its distance to its own center. A row in a small cluster scores its distance to the nearest large center.
CBLOF on Pima
Read27 of 532 rows (5.1%) are flagged as anomalies (CBLOF ≥ 2.12).
- Anomalies
- 27
- Threshold
- 2.122
Plots
View data
| Anomaly | CBLOF |
|---|---|
| false | 1.052 |
| false | 1.623 |
| false | 1.342 |
| true | 2.184 |
| false | 0.2784 |
| false | 0.8656 |
| false | 1.039 |
| true | 2.122 |
| false | 0.9245 |
| false | 1.645 |
| true | 2.382 |
| false | 1.019 |
| false | 1.766 |
| false | 1.340 |
| false | 0.9519 |
| false | 1.161 |
| false | 0.4317 |
| false | 0.9100 |
| false | 1.403 |
| false | 1.403 |
| false | 1.198 |
| false | 0.7893 |
| false | 1.333 |
| false | 0.8556 |
| false | 0.7801 |
| false | 1.386 |
| false | 0.3454 |
| false | 1.296 |
| false | 0.9592 |
| false | 0.4228 |
| false | 1.337 |
| false | 1.053 |
| false | 0.9260 |
| false | 0.8523 |
| false | 0.6392 |
| false | 1.534 |
| false | 1.257 |
| false | 1.543 |
| false | 0.7702 |
| false | 0.5867 |
| false | 1.168 |
| false | 0.7996 |
| false | 1.130 |
| false | 1.212 |
| false | 0.8299 |
| false | 0.9515 |
| false | 0.8024 |
| false | 1.043 |
| false | 0.6946 |
| false | 1.940 |
| false | 0.6907 |
| false | 1.189 |
| false | 1.012 |
| false | 0.5513 |
| false | 0.8019 |
| false | 1.254 |
| false | 0.7621 |
| false | 1.783 |
| false | 1.520 |
| false | 1.513 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | glu | bp | bmi | age |
|---|---|---|---|---|---|---|---|---|
| 1 | 279 | 4.942 | bmi = 67.1 (robust z +5.2); 47% of its tail score | bmi: falls 2.59 at its median | 129 | 110 | 67.100 | 26 |
| 2 | 398 | 3.855 | bmi = 59.4 (robust z +4.0); 54% of its tail score | bmi: falls 2.81 at its median | 180 | 78 | 59.400 | 25 |
| 3 | 257 | 3.790 | bp = 30 (robust z -3.5); 40% of its tail score | bmi: falls 1.17 at its median | 88 | 30 | 55 | 26 |
| 4 | 492 | 3.661 | bmi = 57.3 (robust z +3.7); 45% of its tail score | bmi: falls 1.67 at its median | 123 | 100 | 57.300 | 22 |
| 5 | 358 | 2.948 | age = 65 (robust z +4.2); 40% of its tail score | bp: falls 0.76 at its median | 103 | 108 | 39.200 | 65 |
| 6 | 208 | 2.940 | bp = 30 (robust z -3.5); 52% of its tail score | bp: falls 1.67 at its median | 103 | 30 | 43.300 | 33 |
| 7 | 255 | 2.937 | bmi = 53.2 (robust z +3.1); 54% of its tail score | bmi: falls 2.08 at its median | 162 | 76 | 53.200 | 25 |
| 8 | 307 | 2.925 | bmi = 52.3 (robust z +3.0); 42% of its tail score | bmi: falls 0.999 at its median | 165 | 90 | 52.300 | 23 |
| 9 | 462 | 2.914 | bp = 24 (robust z -4.0); 52% of its tail score | bp: falls 1.97 at its median | 89 | 24 | 27.800 | 21 |
| 10 | 491 | 2.753 | bp = 106 (robust z +2.9); 37% of its tail score | bp: falls 1.55 at its median | 68 | 106 | 35.500 | 47 |
| 11 | 403 | 2.671 | age = 81 (robust z +6.0); 62% of its tail score | age: falls 1.59 at its median | 134 | 74 | 25.900 | 81 |
| 12 | 111 | 2.548 | bp = 110 (robust z +3.2); 46% of its tail score | bp: falls 1.31 at its median | 189 | 110 | 28.500 | 37 |
| 13 | 221 | 2.492 | bp = 110 (robust z +3.2); 38% of its tail score | bp: falls 0.433 at its median | 171 | 110 | 45.400 | 54 |
| 14 | 493 | 2.423 | bmi = 49.6 (robust z +2.5); 52% of its tail score | bmi: falls 1.61 at its median | 162 | 76 | 49.600 | 26 |
| 15 | 11 | 2.382 | bp = 40 (robust z -2.7); 49% of its tail score | bp: falls 0.824 at its median | 137 | 40 | 43.100 | 33 |
| 16 | 301 | 2.334 | glu = 179 (robust z +2.2); 28% of its tail score | bp: falls 0.622 at its median | 179 | 90 | 44.100 | 23 |
| 17 | 432 | 2.314 | age = 60 (robust z +3.6); 32% of its tail score | bmi: falls 0.835 at its median | 129 | 90 | 19.600 | 60 |
| 18 | 522 | 2.303 | bmi = 49.3 (robust z +2.5); 41% of its tail score | bmi: falls 0.745 at its median | 147 | 94 | 49.300 | 27 |
| 19 | 140 | 2.277 | bmi = 46.8 (robust z +2.1); 46% of its tail score | bmi: falls 1.17 at its median | 100 | 88 | 46.800 | 31 |
| 20 | 248 | 2.240 | bmi = 49.7 (robust z +2.6); 48% of its tail score | bmi: falls 0.954 at its median | 122 | 90 | 49.700 | 31 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec d723e36b4b661f8a
# 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("glu", "bp", "bmi", "age"))), c("glu", "bp", "bmi", "age"))
FEATURES <- c("glu", "bp", "bmi", "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(
glu = "numeric",
bp = "numeric",
bmi = "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
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K <- 8
SEED <- 42
if (nrow(df) <= K) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("CBLOF with %d clusters", K), min = K + 1L, n = nrow(df))
.km <- cs_ml_kmeans_fit(X, K, cs_rng(SEED), n_init = 10)
labels <- as.integer(cs_ml_canonical(.km$labels)) # 1..k by size, ties by first row
k_found <- max(labels)
centers <- do.call(rbind, lapply(seq_len(k_found), function(c) .km$centers[.km$labels[which(labels == c)[1]] + 1L, ]))
sizes <- tabulate(labels, nbins = k_found)
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
.split <- cs_ml_cblof_split(labels, 0.9, 5)
n_large <- .split$n_large
if (!.split$split) warnings <- c(warnings, "No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED <- FALSE
scores <- cs_ml_cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL <- "CBLOF"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(clusters = k_found, n_large = n_large, small_rows = sum(labels > n_large))
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth") # median + 3 scaled MADs
rescore <- function(Q, where0, col0) {
lab <- cs_ml_nearest_center(Q, centers) # the fitted clusters, no refit
cs_ml_cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
}
# %% Flag anomalies
RULE <- "share"
cutoff_ <- NULL
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.cblof/pima_default/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("glu", "bp", "bmi", "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 = "Cluster-based local outlier factor (CBLOF)",
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 (CBLOF ≥ 2.12).
- Anomalies
- 27
- Threshold
- 2.122
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | glu | bp | bmi | age |
|---|---|---|---|---|---|---|---|---|
| 1 | 279 | 4.942 | bmi = 67.1 (robust z +5.2); 47% of its tail score | bmi: falls 2.59 at its median | 129 | 110 | 67.100 | 26 |
| 2 | 398 | 3.855 | bmi = 59.4 (robust z +4.0); 54% of its tail score | bmi: falls 2.81 at its median | 180 | 78 | 59.400 | 25 |
| 3 | 257 | 3.790 | bp = 30 (robust z -3.5); 40% of its tail score | bmi: falls 1.17 at its median | 88 | 30 | 55 | 26 |
| 4 | 492 | 3.661 | bmi = 57.3 (robust z +3.7); 45% of its tail score | bmi: falls 1.67 at its median | 123 | 100 | 57.300 | 22 |
| 5 | 358 | 2.948 | age = 65 (robust z +4.2); 40% of its tail score | bp: falls 0.76 at its median | 103 | 108 | 39.200 | 65 |
| 6 | 208 | 2.940 | bp = 30 (robust z -3.5); 52% of its tail score | bp: falls 1.67 at its median | 103 | 30 | 43.300 | 33 |
| 7 | 255 | 2.937 | bmi = 53.2 (robust z +3.1); 54% of its tail score | bmi: falls 2.08 at its median | 162 | 76 | 53.200 | 25 |
| 8 | 307 | 2.925 | bmi = 52.3 (robust z +3.0); 42% of its tail score | bmi: falls 0.999 at its median | 165 | 90 | 52.300 | 23 |
| 9 | 462 | 2.914 | bp = 24 (robust z -4.0); 52% of its tail score | bp: falls 1.97 at its median | 89 | 24 | 27.800 | 21 |
| 10 | 491 | 2.753 | bp = 106 (robust z +2.9); 37% of its tail score | bp: falls 1.55 at its median | 68 | 106 | 35.500 | 47 |
| 11 | 403 | 2.671 | age = 81 (robust z +6.0); 62% of its tail score | age: falls 1.59 at its median | 134 | 74 | 25.900 | 81 |
| 12 | 111 | 2.548 | bp = 110 (robust z +3.2); 46% of its tail score | bp: falls 1.31 at its median | 189 | 110 | 28.500 | 37 |
| 13 | 221 | 2.492 | bp = 110 (robust z +3.2); 38% of its tail score | bp: falls 0.433 at its median | 171 | 110 | 45.400 | 54 |
| 14 | 493 | 2.423 | bmi = 49.6 (robust z +2.5); 52% of its tail score | bmi: falls 1.61 at its median | 162 | 76 | 49.600 | 26 |
| 15 | 11 | 2.382 | bp = 40 (robust z -2.7); 49% of its tail score | bp: falls 0.824 at its median | 137 | 40 | 43.100 | 33 |
| 16 | 301 | 2.334 | glu = 179 (robust z +2.2); 28% of its tail score | bp: falls 0.622 at its median | 179 | 90 | 44.100 | 23 |
| 17 | 432 | 2.314 | age = 60 (robust z +3.6); 32% of its tail score | bmi: falls 0.835 at its median | 129 | 90 | 19.600 | 60 |
| 18 | 522 | 2.303 | bmi = 49.3 (robust z +2.5); 41% of its tail score | bmi: falls 0.745 at its median | 147 | 94 | 49.300 | 27 |
| 19 | 140 | 2.277 | bmi = 46.8 (robust z +2.1); 46% of its tail score | bmi: falls 1.17 at its median | 100 | 88 | 46.800 | 31 |
| 20 | 248 | 2.240 | bmi = 49.7 (robust z +2.6); 48% of its tail score | bmi: falls 0.954 at its median | 122 | 90 | 49.700 | 31 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec d723e36b4b661f8a
# 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.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import cluster as csc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% 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=["glu", "bp", "bmi", "age"]), ["glu", "bp", "bmi", "age"])
FEATURES = ["glu", "bp", "bmi", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"glu": "numeric",
"bp": "numeric",
"bmi": "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))
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K = 8
SEED = 42
if len(df) <= K:
cs_error("CS_E_TOO_FEW_ROWS", what=f"CBLOF with {K} clusters", min=K + 1, n=len(df))
_raw, _centers, _ = csc.kmeans_fit(X, K, Rng(SEED), n_init=10)
labels = csc.canonical(_raw) # 1..k by size, ties by first row
k_found = int(labels.max())
centers = np.vstack([_centers[int(_raw[np.flatnonzero(labels == c)[0]])] for c in range(1, k_found + 1)])
sizes = np.bincount(labels, minlength=k_found + 1)[1:]
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
n_large, _split = csax.cblof_split(labels, 0.9, 5)
if not _split:
warnings.append("No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED = False
scores = csax.cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL = "CBLOF"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"clusters": k_found, "n_large": int(n_large), "small_rows": int(np.sum(labels > n_large))}
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth") # median + 3 scaled MADs
def rescore(Q, where, col):
lab = csax.nearest_center(Q, centers) # the fitted clusters, no refit
return csax.cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
# %% Flag anomalies
RULE = "share"
_cutoff = None
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.cblof/pima_default/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 = ["glu", "bp", "bmi", "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": "Cluster-based local outlier factor (CBLOF)",
"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"}],
})
On Pima, 7 of 8 clusters count as large and 34 rows sit in small ones. Those small clusters are exactly what CBLOF is for: a tight group of unusual records that a neighbor score would call normal, because its members are each other's neighbors.
The same rule wrongly flags a real minority. If a small cluster is a legitimate group of customers, CBLOF still scores it as remote. Check the small clusters before you act on their rows.
When there is no clear boundary
PredictPredict first
US arrests has 50 states. With 4 clusters, none of the first three ever holds 90% of the states, and no cluster is 5 times bigger than the next. What does CBLOF do?
Reveal
Every cluster counts as large: 4 of 4, with 0 rows in small clusters. Each state is scored by its distance to its own center, and the result says no boundary was found. PyOD stops with an error here; CodeSplash keeps going and tells you.
Multiply by cluster size gives He et al.'s original weighting, where rows of big clusters weigh more. It changes the ranking a lot, so say which version you used.
Column by column: ECOD, COPOD and HBOS
ReadECOD anomaly scores now offers three scores that all add up one surprise per column:
- ECOD takes each column's tail on the side its skewness points to.
- COPODCOPODAdds up per-feature tail scores from the empirical CDFs: the skewed tail or the average of both tails, whichever is larger. takes the skewed tail, or the average of both tails if that is larger.
- HBOSHistogram-based outlier score (HBOS)Minus the sum over features of log₂(histogram density + α): values in sparse bins of several columns score high. builds an equal-width histogram per column and scores −log2(density + α).
Three tail scores on Pima
Read27 of 532 rows (5.1%) are flagged as anomalies (COPOD score ≥ 13.6).
- Anomalies
- 27
- Threshold
- 13.600
Plots
View data
| Anomaly | COPOD score |
|---|---|
| false | 6.032 |
| false | 12.995 |
| false | 9.435 |
| false | 11.559 |
| false | 7.458 |
| false | 7.942 |
| false | 7.157 |
| false | 11.688 |
| false | 10.332 |
| false | 10.380 |
| true | 16.894 |
| false | 9.418 |
| false | 11.485 |
| true | 13.820 |
| false | 12.269 |
| false | 7.215 |
| false | 9.975 |
| false | 12.099 |
| false | 6.913 |
| false | 8.608 |
| false | 6.696 |
| false | 6.209 |
| false | 6.836 |
| false | 7.847 |
| false | 6.659 |
| false | 9.852 |
| false | 8.740 |
| false | 8.069 |
| false | 8.012 |
| false | 5.460 |
| false | 11.001 |
| false | 6.454 |
| false | 6.573 |
| false | 7.435 |
| false | 7.941 |
| false | 13.125 |
| false | 6.710 |
| false | 10.645 |
| false | 6.790 |
| false | 6.891 |
| false | 12.075 |
| false | 7.574 |
| false | 8.098 |
| false | 8.247 |
| false | 6.659 |
| false | 8.375 |
| false | 6.822 |
| false | 9.317 |
| false | 7.259 |
| true | 17.187 |
| false | 6.945 |
| false | 6.141 |
| false | 8.782 |
| false | 7.190 |
| false | 5.941 |
| false | 7.770 |
| false | 7.297 |
| false | 9.868 |
| false | 9.923 |
| true | 13.807 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | COPOD score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 22.539 | 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 | 157 | 18.519 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 5.62 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 272 | 17.290 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 5.72 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 4 | 50 | 17.187 | 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 | 11 | 16.894 | 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 |
| 6 | 296 | 15.793 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 4.89 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 7 | 255 | 15.669 | bmi = 53.2 (robust z +3.1); 27% of its tail score | skin: falls 4.23 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 8 | 221 | 15.579 | bp = 110 (robust z +3.2); 28% of its tail score | bmi: falls 2.38 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 9 | 257 | 15.475 | 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 |
| 10 | 100 | 15.202 | npreg = 10 (robust z +2.7); 17% of its tail score | skin: falls 2.67 at its median | 10 | 148 | 84 | 48 | 37.600 | 1.001 | 51 |
| 11 | 279 | 15.135 | 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 |
| 12 | 140 | 15.091 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 4.52 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 13 | 520 | 15.053 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 3.64 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
| 14 | 417 | 14.820 | age = 58 (robust z +3.4); 21% of its tail score | bmi: falls 2.89 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 15 | 458 | 14.522 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 3.03 at its median | 11 | 111 | 84 | 40 | 46.800 | 0.9250 | 45 |
| 16 | 362 | 14.512 | ped = 2.137 (robust z +6.5); 32% of its tail score | ped: falls 4.2 at its median | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 17 | 241 | 14.453 | npreg = 13 (robust z +3.7); 27% of its tail score | skin: falls 3.82 at its median | 13 | 106 | 72 | 54 | 36.600 | 0.1780 | 45 |
| 18 | 96 | 14.277 | npreg = 12 (robust z +3.4); 23% of its tail score | npreg: falls 2.95 at its median | 12 | 140 | 82 | 43 | 39.200 | 0.5280 | 58 |
| 19 | 222 | 14.007 | ped = 1.893 (robust z +5.6); 31% of its tail score | ped: falls 3.97 at its median | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 20 | 443 | 13.989 | age = 53 (robust z +2.8); 20% of its tail score | glu: falls 2.55 at its median | 5 | 187 | 76 | 27 | 43.600 | 1.034 | 53 |
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 9e4bd5d4dbf963a4
# 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
# COPOD (Li et al. 2020) as PyOD 3 computes it (twin: codesplash.ml.anomaly_ext.copod)
scores <- cs_ml_copod(X)
SCORE_LABEL <- "COPOD score"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list()
rescore <- function(Q, where0, col0) cs_ml_copod_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_copod/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 (COPOD score ≥ 13.6).
- Anomalies
- 27
- Threshold
- 13.600
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | COPOD score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 398 | 22.539 | 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 | 157 | 18.519 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 5.62 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 3 | 272 | 17.290 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 5.72 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
| 4 | 50 | 17.187 | 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 | 11 | 16.894 | 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 |
| 6 | 296 | 15.793 | ped = 2.329 (robust z +7.2); 35% of its tail score | ped: falls 4.89 at its median | 4 | 197 | 70 | 39 | 36.700 | 2.329 | 31 |
| 7 | 255 | 15.669 | bmi = 53.2 (robust z +3.1); 27% of its tail score | skin: falls 4.23 at its median | 0 | 162 | 76 | 56 | 53.200 | 0.7590 | 25 |
| 8 | 221 | 15.579 | bp = 110 (robust z +3.2); 28% of its tail score | bmi: falls 2.38 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 9 | 257 | 15.475 | 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 |
| 10 | 100 | 15.202 | npreg = 10 (robust z +2.7); 17% of its tail score | skin: falls 2.67 at its median | 10 | 148 | 84 | 48 | 37.600 | 1.001 | 51 |
| 11 | 279 | 15.135 | 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 |
| 12 | 140 | 15.091 | skin = 60 (robust z +3.0); 29% of its tail score | skin: falls 4.52 at its median | 0 | 100 | 88 | 60 | 46.800 | 0.9620 | 31 |
| 13 | 520 | 15.053 | npreg = 13 (robust z +3.7); 26% of its tail score | npreg: falls 3.64 at its median | 13 | 153 | 88 | 37 | 40.600 | 1.174 | 39 |
| 14 | 417 | 14.820 | age = 58 (robust z +3.4); 21% of its tail score | bmi: falls 2.89 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 15 | 458 | 14.522 | npreg = 11 (robust z +3.0); 20% of its tail score | bmi: falls 3.03 at its median | 11 | 111 | 84 | 40 | 46.800 | 0.9250 | 45 |
| 16 | 362 | 14.512 | ped = 2.137 (robust z +6.5); 32% of its tail score | ped: falls 4.2 at its median | 3 | 173 | 82 | 48 | 38.400 | 2.137 | 25 |
| 17 | 241 | 14.453 | npreg = 13 (robust z +3.7); 27% of its tail score | skin: falls 3.82 at its median | 13 | 106 | 72 | 54 | 36.600 | 0.1780 | 45 |
| 18 | 96 | 14.277 | npreg = 12 (robust z +3.4); 23% of its tail score | npreg: falls 2.95 at its median | 12 | 140 | 82 | 43 | 39.200 | 0.5280 | 58 |
| 19 | 222 | 14.007 | ped = 1.893 (robust z +5.6); 31% of its tail score | ped: falls 3.97 at its median | 0 | 180 | 66 | 39 | 42 | 1.893 | 25 |
| 20 | 443 | 13.989 | age = 53 (robust z +2.8); 20% of its tail score | glu: falls 2.55 at its median | 5 | 187 | 76 | 27 | 43.600 | 1.034 | 53 |
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 9e4bd5d4dbf963a4
# 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
# COPOD (Li et al. 2020) as PyOD 3 computes it (twin: codesplashr::cs_ml_copod)
from codesplash.ml import anomaly_ext as csax
scores = csax.copod(X)
SCORE_LABEL = "COPOD score"
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {}
rescore = lambda Q, where, col: csax.copod_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_copod/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"}],
})
On the same seven Pima columns, the share rule flags 27 rows with each score, but not the same rows: the most unusual COPOD score is 22.5, the most unusual HBOS score 20.5, on different scales.
Because they read each column separately, all three miss a row whose values are ordinary one at a time but odd together, such as a tall person who weighs very little. Use a neighbor score or the one-class SVM for combinations. In return they are fast, and COPOD doesn't change at all if you rescale a column.
The boundary as a sphere: SVDD
ReadThe one-class SVM draws a boundary around most rows. SVDDSupport vector data description (SVDD)The smallest sphere in feature space that encloses most rows; the score is squared distance to its center minus its squared radius. draws the smallest sphere (in the kernel's feature space) that holds most rows. With the RBF kernel the two are the same fit read two ways, so View → Sphere (SVDD) changes the scale of the score, not the boundary or the flags.
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"}],
})
The sphere's radius here is 0.948 and C = 1/(νn) = 0.20. Like the one-class view, 14 states lie outside, with a score above 0.
Check your understanding
CheckpointCheck yourself
CBLOF flags every row of a small cluster of 30 customers. What should you check before acting on them?
Show the answer
Answer: a
CBLOF assumes small remote clusters deserve scrutiny. A real but rare group of customers fits that pattern too, so a person needs to look at the cluster as a whole.
Check yourself
In CBLOF, a row sits in a small cluster. What is its score (unweighted)?
Show the answer
Answer: b
Small clusters aren't trusted as normal, so their rows are measured against the large, normal clusters. Rows in large clusters use their own center.
Check yourself
A row has an ordinary height and an ordinary weight, but that weight is very unusual for that height. Which detector is least likely to flag it?
Show the answer
Answer: a
HBOS (like ECOD and COPOD) scores each column on its own, so it can't see that the combination is rare. The one-class SVM and neighbor scores work with all columns together.
Check yourself
You switch the one-class SVM's view from One-class SVM to Sphere (SVDD) with the share rule. What changes?
Show the answer
Answer: b
With the RBF kernel, the sphere and the boundary are the same solution; the SVDD score is the one-class score times 2/(νn). Same ranking, same flags.
Do it on your own data
In the appRun Cluster-based local outlier factor (CBLOF) next to a neighbor score. Rows only CBLOF flags often come from small clusters; open them in Review together.
import pandas as pd
from pyod.models.cblof import CBLOF
from pyod.models.copod import COPOD
from sklearn.preprocessing import StandardScaler
df = pd.read_csv("pima.csv")
X = StandardScaler().fit_transform(df[["glu", "bp", "bmi", "age"]])
print(CBLOF(n_clusters=8, random_state=1).fit(X).decision_scores_[:5].round(3))
print(COPOD().fit(df[["glu", "bp", "bmi", "age"]]).decision_scores_[:5].round(3))df <- read.csv("pima.csv")
X <- scale(df[, c("glu", "bp", "bmi", "age")])
set.seed(1)
km <- kmeans(X, centers = 8, nstart = 10)
# distance of each row to its own center (the large-cluster branch of CBLOF)
round(head(sqrt(rowSums((X - km$centers[km$cluster, ])^2))), 3)PyOD's k-means starts differ from CodeSplash's shared ones, so its clusters, and the scores, can differ from the app's.
Recap
Recap- CBLOF measures rows against the large clusters; small clusters are suspects, not proof.
- ECOD, COPOD and HBOS add up one surprise per column, so they miss odd combinations.
- SVDD and the one-class SVM are one boundary read two ways.