Skip to content

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.

Applied ~12 min9 steps

What runs in CodeSplash

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

Read first

01

Distance to the big groups: CBLOF

Read

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

02

CBLOF on Pima

Read
Cluster-based local outlier factor (CBLOF)Recorded · Python and R agreeRecorded 2026-11-25 · 79 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (CBLOF ≥ 2.12).

Anomalies
27
Threshold
2.122

Plots

CBLOF distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyCBLOF
false1.052
false1.623
false1.342
true2.184
false0.2784
false0.8656
false1.039
true2.122
false0.9245
false1.645
true2.382
false1.019
false1.766
false1.340
false0.9519
false1.161
false0.4317
false0.9100
false1.403
false1.403
false1.198
false0.7893
false1.333
false0.8556
false0.7801
false1.386
false0.3454
false1.296
false0.9592
false0.4228
false1.337
false1.053
false0.9260
false0.8523
false0.6392
false1.534
false1.257
false1.543
false0.7702
false0.5867
false1.168
false0.7996
false1.130
false1.212
false0.8299
false0.9515
false0.8024
false1.043
false0.6946
false1.940
false0.6907
false1.189
false1.012
false0.5513
false0.8019
false1.254
false0.7621
false1.783
false1.520
false1.513

First 60 of 532 rows.

Most anomalous rows

RankRowCBLOFMost unusualBiggest score dropglubpbmiage
12794.942bmi = 67.1 (robust z +5.2); 47% of its tail scorebmi: falls 2.59 at its median12911067.10026
23983.855bmi = 59.4 (robust z +4.0); 54% of its tail scorebmi: falls 2.81 at its median1807859.40025
32573.790bp = 30 (robust z -3.5); 40% of its tail scorebmi: falls 1.17 at its median88305526
44923.661bmi = 57.3 (robust z +3.7); 45% of its tail scorebmi: falls 1.67 at its median12310057.30022
53582.948age = 65 (robust z +4.2); 40% of its tail scorebp: falls 0.76 at its median10310839.20065
62082.940bp = 30 (robust z -3.5); 52% of its tail scorebp: falls 1.67 at its median1033043.30033
72552.937bmi = 53.2 (robust z +3.1); 54% of its tail scorebmi: falls 2.08 at its median1627653.20025
83072.925bmi = 52.3 (robust z +3.0); 42% of its tail scorebmi: falls 0.999 at its median1659052.30023
94622.914bp = 24 (robust z -4.0); 52% of its tail scorebp: falls 1.97 at its median892427.80021
104912.753bp = 106 (robust z +2.9); 37% of its tail scorebp: falls 1.55 at its median6810635.50047
114032.671age = 81 (robust z +6.0); 62% of its tail scoreage: falls 1.59 at its median1347425.90081
121112.548bp = 110 (robust z +3.2); 46% of its tail scorebp: falls 1.31 at its median18911028.50037
132212.492bp = 110 (robust z +3.2); 38% of its tail scorebp: falls 0.433 at its median17111045.40054
144932.423bmi = 49.6 (robust z +2.5); 52% of its tail scorebmi: falls 1.61 at its median1627649.60026
15112.382bp = 40 (robust z -2.7); 49% of its tail scorebp: falls 0.824 at its median1374043.10033
163012.334glu = 179 (robust z +2.2); 28% of its tail scorebp: falls 0.622 at its median1799044.10023
174322.314age = 60 (robust z +3.6); 32% of its tail scorebmi: falls 0.835 at its median1299019.60060
185222.303bmi = 49.3 (robust z +2.5); 41% of its tail scorebmi: falls 0.745 at its median1479449.30027
191402.277bmi = 46.8 (robust z +2.1); 46% of its tail scorebmi: falls 1.17 at its median1008846.80031
202482.240bmi = 49.7 (robust z +2.6); 48% of its tail scorebmi: falls 0.954 at its median1229049.70031
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"))
))
Python

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

RankRowCBLOFMost unusualBiggest score dropglubpbmiage
12794.942bmi = 67.1 (robust z +5.2); 47% of its tail scorebmi: falls 2.59 at its median12911067.10026
23983.855bmi = 59.4 (robust z +4.0); 54% of its tail scorebmi: falls 2.81 at its median1807859.40025
32573.790bp = 30 (robust z -3.5); 40% of its tail scorebmi: falls 1.17 at its median88305526
44923.661bmi = 57.3 (robust z +3.7); 45% of its tail scorebmi: falls 1.67 at its median12310057.30022
53582.948age = 65 (robust z +4.2); 40% of its tail scorebp: falls 0.76 at its median10310839.20065
62082.940bp = 30 (robust z -3.5); 52% of its tail scorebp: falls 1.67 at its median1033043.30033
72552.937bmi = 53.2 (robust z +3.1); 54% of its tail scorebmi: falls 2.08 at its median1627653.20025
83072.925bmi = 52.3 (robust z +3.0); 42% of its tail scorebmi: falls 0.999 at its median1659052.30023
94622.914bp = 24 (robust z -4.0); 52% of its tail scorebp: falls 1.97 at its median892427.80021
104912.753bp = 106 (robust z +2.9); 37% of its tail scorebp: falls 1.55 at its median6810635.50047
114032.671age = 81 (robust z +6.0); 62% of its tail scoreage: falls 1.59 at its median1347425.90081
121112.548bp = 110 (robust z +3.2); 46% of its tail scorebp: falls 1.31 at its median18911028.50037
132212.492bp = 110 (robust z +3.2); 38% of its tail scorebp: falls 0.433 at its median17111045.40054
144932.423bmi = 49.6 (robust z +2.5); 52% of its tail scorebmi: falls 1.61 at its median1627649.60026
15112.382bp = 40 (robust z -2.7); 49% of its tail scorebp: falls 0.824 at its median1374043.10033
163012.334glu = 179 (robust z +2.2); 28% of its tail scorebp: falls 0.622 at its median1799044.10023
174322.314age = 60 (robust z +3.6); 32% of its tail scorebmi: falls 0.835 at its median1299019.60060
185222.303bmi = 49.3 (robust z +2.5); 41% of its tail scorebmi: falls 0.745 at its median1479449.30027
191402.277bmi = 46.8 (robust z +2.1); 46% of its tail scorebmi: falls 1.17 at its median1008846.80031
202482.240bmi = 49.7 (robust z +2.6); 48% of its tail scorebmi: falls 0.954 at its median1229049.70031
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.

03

When there is no clear boundary

Predict

Predict 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?

Some clusters are smallEvery cluster counts as large
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.

04

Column by column: ECOD, COPOD and HBOS

Read

ECOD 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 + α).
05

Three tail scores on Pima

Read
ECOD anomaly scoresRecorded · Python and R agreeRecorded 2026-11-25 · 76 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (COPOD score ≥ 13.6).

Anomalies
27
Threshold
13.600

Plots

COPOD score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyCOPOD score
false6.032
false12.995
false9.435
false11.559
false7.458
false7.942
false7.157
false11.688
false10.332
false10.380
true16.894
false9.418
false11.485
true13.820
false12.269
false7.215
false9.975
false12.099
false6.913
false8.608
false6.696
false6.209
false6.836
false7.847
false6.659
false9.852
false8.740
false8.069
false8.012
false5.460
false11.001
false6.454
false6.573
false7.435
false7.941
false13.125
false6.710
false10.645
false6.790
false6.891
false12.075
false7.574
false8.098
false8.247
false6.659
false8.375
false6.822
false9.317
false7.259
true17.187
false6.945
false6.141
false8.782
false7.190
false5.941
false7.770
false7.297
false9.868
false9.923
true13.807

First 60 of 532 rows.

Most anomalous rows

RankRowCOPOD scoreMost unusualBiggest score dropnpregglubpskinbmipedage
139822.539ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 5.58 at its median0180786359.4002.42025
215718.519skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 5.62 at its median2197709934.7000.575062
327217.290npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 5.72 at its median17163724140.9000.817047
45017.187ped = 1.394 (robust z +3.7); 21% of its tail scoreglu: falls 5.59 at its median1199764342.9001.39422
51116.894ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 4.48 at its median0137403543.1002.28833
629615.793ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 4.89 at its median4197703936.7002.32931
725515.669bmi = 53.2 (robust z +3.1); 27% of its tail scoreskin: falls 4.23 at its median0162765653.2000.759025
822115.579bp = 110 (robust z +3.2); 28% of its tail scorebmi: falls 2.38 at its median91711102445.4000.721054
925715.475bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 4.5 at its median1883042550.496026
1010015.202npreg = 10 (robust z +2.7); 17% of its tail scoreskin: falls 2.67 at its median10148844837.6001.00151
1127915.135bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 5.59 at its median01291104667.1000.319026
1214015.091skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 4.52 at its median0100886046.8000.962031
1352015.053npreg = 13 (robust z +3.7); 26% of its tail scorenpreg: falls 3.64 at its median13153883740.6001.17439
1441714.820age = 58 (robust z +3.4); 21% of its tail scorebmi: falls 2.89 at its median0173783246.5001.15958
1545814.522npreg = 11 (robust z +3.0); 20% of its tail scorebmi: falls 3.03 at its median11111844046.8000.925045
1636214.512ped = 2.137 (robust z +6.5); 32% of its tail scoreped: falls 4.2 at its median3173824838.4002.13725
1724114.453npreg = 13 (robust z +3.7); 27% of its tail scoreskin: falls 3.82 at its median13106725436.6000.178045
189614.277npreg = 12 (robust z +3.4); 23% of its tail scorenpreg: falls 2.95 at its median12140824339.2000.528058
1922214.007ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 3.97 at its median01806639421.89325
2044313.989age = 53 (robust z +2.8); 20% of its tail scoreglu: falls 2.55 at its median5187762743.6001.03453
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"))
))
Python

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

RankRowCOPOD scoreMost unusualBiggest score dropnpregglubpskinbmipedage
139822.539ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 5.58 at its median0180786359.4002.42025
215718.519skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 5.62 at its median2197709934.7000.575062
327217.290npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 5.72 at its median17163724140.9000.817047
45017.187ped = 1.394 (robust z +3.7); 21% of its tail scoreglu: falls 5.59 at its median1199764342.9001.39422
51116.894ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 4.48 at its median0137403543.1002.28833
629615.793ped = 2.329 (robust z +7.2); 35% of its tail scoreped: falls 4.89 at its median4197703936.7002.32931
725515.669bmi = 53.2 (robust z +3.1); 27% of its tail scoreskin: falls 4.23 at its median0162765653.2000.759025
822115.579bp = 110 (robust z +3.2); 28% of its tail scorebmi: falls 2.38 at its median91711102445.4000.721054
925715.475bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 4.5 at its median1883042550.496026
1010015.202npreg = 10 (robust z +2.7); 17% of its tail scoreskin: falls 2.67 at its median10148844837.6001.00151
1127915.135bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 5.59 at its median01291104667.1000.319026
1214015.091skin = 60 (robust z +3.0); 29% of its tail scoreskin: falls 4.52 at its median0100886046.8000.962031
1352015.053npreg = 13 (robust z +3.7); 26% of its tail scorenpreg: falls 3.64 at its median13153883740.6001.17439
1441714.820age = 58 (robust z +3.4); 21% of its tail scorebmi: falls 2.89 at its median0173783246.5001.15958
1545814.522npreg = 11 (robust z +3.0); 20% of its tail scorebmi: falls 3.03 at its median11111844046.8000.925045
1636214.512ped = 2.137 (robust z +6.5); 32% of its tail scoreped: falls 4.2 at its median3173824838.4002.13725
1724114.453npreg = 13 (robust z +3.7); 27% of its tail scoreskin: falls 3.82 at its median13106725436.6000.178045
189614.277npreg = 12 (robust z +3.4); 23% of its tail scorenpreg: falls 2.95 at its median12140824339.2000.528058
1922214.007ped = 1.893 (robust z +5.6); 31% of its tail scoreped: falls 3.97 at its median01806639421.89325
2044313.989age = 53 (robust z +2.8); 20% of its tail scoreglu: falls 2.55 at its median5187762743.6001.03453
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.

06

The boundary as a sphere: SVDD

Read

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

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

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

Anomalies
3
Threshold
8.292e-5

Plots

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

Most anomalous rows

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

# %% Setup
library(codesplashr)


# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = c("Murder", "Assault", "UrbanPop", "Rape"))), c("Murder", "Assault", "UrbanPop", "Rape"))
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    Murder = "numeric",
    Assault = "numeric",
    UrbanPop = "numeric",
    Rape = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L

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

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

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

# %% Flag anomalies
RULE <- "share"
cutoff_ <- 0
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.ocsvm/usarrests_svdd/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))

# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
                 score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
            extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
  values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
  values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)

# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("Murder", "Assault", "UrbanPop", "Rape")
why <- NULL
if (length(NUMERIC)) {
  F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
  med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
  for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
  why <- cs_ml_anomaly_explain(F_, top - 1L)
  for (rank in seq_len(min(10L, length(top)))) {
    values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
    values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
    values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
  }
  # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
  drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
  for (rank in seq_len(min(10L, length(top)))) {
    values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
    values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
  }
}
table_rows <- lapply(seq_along(top), function(rank) {
  i <- top[rank]
  r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
  if (!is.null(why)) {
    j <- why$feature[rank] + 1L
    sh <- why$share[rank]
    r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
                    if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
    d_ <- drop_$drop[rank]
    r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
  }
  for (f in FEATURES) {
    v <- df[[f]][rows[i] + 1L]
    r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
  }
  r
})
cs_publish(list(
  title = "One-class SVM",
  engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
  n = length(rows),
  summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
                    100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
  statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
                    list(key = "threshold", label = "Threshold", value = threshold)),
  tables = list(list(
    key = "top", title = "Most anomalous rows",
    columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
                     list(key = "score", label = SCORE_LABEL, type = "number")),
                if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
                lapply(FEATURES, function(f) list(key = f, label = f))),
    rows = table_rows
  )),
  charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
    score = cs_col(SCORE_LABEL, scores, "numeric"),
    anomaly = cs_col("Anomaly", flags, "boolean")
  ), controls = list(threshold = threshold))),
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Python

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

Anomalies
3
Threshold
8.292e-5

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

Most anomalous rows

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

import numpy as np
import pandas as pd
from sklearn.svm import OneClassSVM

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

# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "Murder": "numeric",
        "Assault": "numeric",
        "UrbanPop": "numeric",
        "Rape": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))

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

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

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

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

# %% Flag anomalies
RULE = "share"
_cutoff = 0
if _cutoff is None:
    _cutoff = DEFAULT_CUTOFF  # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.ocsvm/usarrests_svdd/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)

# %% Result
values = {
    "n": len(rows),
    "n_flagged": int(flags.sum()),
    "threshold": float(threshold),
    "score_check": csembed.checksum(scores, rows),
    "score_max": float(scores.max()),
    "score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
    values[f"top_row[{rank}]"] = int(rows[i])
    values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]

# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx

NUMERIC = ["Murder", "Assault", "UrbanPop", "Rape", ]
why = None
if NUMERIC:
    _F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
    _med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
    _F = np.where(np.isnan(_F), _med[None, :], _F)
    why = _dx.explain_rows(_F, top)
    for rank in range(1, min(10, len(top)) + 1):
        values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
        values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
        values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
    # Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
    _cols = [fitted.names.index(f) for f in NUMERIC]
    drop = _dx.score_drops(X, top, _cols, scores, rescore)
    for rank in range(1, min(10, len(top)) + 1):
        values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
        values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
    r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
    if why is not None:
        _j = int(why["feature"][rank - 1])
        _share = why["share"][rank - 1]
        r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
        _d = float(drop["drop"][rank - 1])
        r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
    for f in FEATURES:
        v = rec[f]
        r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v))  # None, NaN, pd.NA, NaT
    table_rows.append(r)
pct = flags.mean()
cs.publish({
    "title": "One-class SVM",
    "engine": cs.engine_info(*ENGINE_PACKAGES),
    "n": len(rows),
    "summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
    "statistics": [
        {"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
        {"key": "threshold", "label": "Threshold", "value": float(threshold)},
    ],
    "tables": [{
        "key": "top",
        "title": "Most anomalous rows",
        "columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
                    {"key": "score", "label": SCORE_LABEL, "type": "number"}]
                   + ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
                   + [{"key": f, "label": f} for f in FEATURES],
        "rows": table_rows,
    }],
    "charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
        "score": cs.col(SCORE_LABEL, scores, "numeric"),
        "anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
    }, controls={"threshold": float(threshold)})],
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})

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.

07

Check your understanding

Checkpoint

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

08

Do it on your own data

In the app

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

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

09

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.