Skip to content

Angles, chains, clusters, selection and scale: five more anomaly scores

ABOD looks at the spread of angles, COF at chains of neighbors, CBLOF at small clusters, SOS at who would pick a row as a neighbor, and LOCI at counts across radii. What each one sees that plain distance misses, and its blind spot.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • Explain why an outlier sees the other rows within a narrow range of angles
  • Say when chaining distance (COF) beats density ratios (LOF)
  • Name CBLOF's hidden assumption about small clusters
  • Read SOS and LOCI scores without treating them as tested probabilities

Read first

01

Beyond "far from the neighbors"

Read

Distance and density scores ask how far a row is from its neighbors. The five scores here look at the shape of the neighborhood instead:

ScoreLooks at
ABODAngle-based outlier detection (ABOD)Variance of the weighted angles from a row to pairs of its neighbors; a small variance means the row sits outside.the spread of angles from the row to pairs of others
COFConnectivity-based outlier factor (COF)A row's average chaining distance along the nearest path through its neighbors, relative to theirs; well above 1 is weakly connected.how well the row chains to its neighbors
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.which cluster the row is in, and how big it is
SOSStochastic outlier selection (SOS)Probability that no other row picks this one as a neighbor, with each row's bandwidth set to a target perplexity.how likely other rows are to pick it as a neighbor
LOCILocal correlation integral (LOCI)Compares a row's neighbor count in a small radius with its neighbors' counts, at every radius; flags a drop beyond 3 standard deviations.neighbor counts compared across many radii

Each catches a case plain distance misses, and each brings its own blind spot.

02

ABOD: a narrow view of the crowd

Read

Stand inside a cloud and the other points surround you: angles to pairs of them vary widely. Stand outside it and they all lie in one direction: the angles barely vary. ABOD scores a row by the variance of weighted angle terms

gx(a,b)=(a−x)⊤(b−x)∥a−x∥2∥b−x∥2.g_x(a,b)=\frac{(a-x)^\top(b-x)}{\lVert a-x\rVert^2\lVert b-x\rVert^2}.

Low variance means outlying. FastABOD uses only the kk neighbors. The weights are part of the definition, scaling changes angles, and libraries differ in sign: in the app, higher still means more anomalous.

Nearest-neighbor outlier scoresRecorded · Python and R agreeRecorded 2026-11-25 · 78 values compared
R

3 of 344 rows (0.9%) are flagged as anomalies (ABOD score (−angle variance) ≥ -0.0704).

Anomalies
3
Threshold
−0.0704

Plots

ABOD score (−angle variance) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyABOD score (−angle variance)
false−9.682
false−8.354
false−4.767
false−1.581
false−3.606
false−2.609
false−6.905
false−0.8142
false−5.126
false−1.606
false−12.130
false−4.729
false−2.037
false−1.911
true−0.0314
false−4.830
false−3.373
false−2.159
false−1.757
false−0.1787
false−2.449
false−5.143
false−31.475
false−2.296
false−3.567
false−9.316
false−14.423
false−12.044
false−0.3743
false−1.780
false−2.740
false−1.122
false−36.189
false−7.948
false−4.158
false−1.310
false−14.368
false−3.375
false−1.916
false−0.7105
false−3.024
false−11.082
false−2.512
false−2.589
false−12.434
false−3.579
false−4.606
false−0.7513
false−19.297
false−1.321
false−27.348
false−7.502
false−18.102
false−4.464
false−0.6889
false−8.996
false−28.873
false−9.682
false−2.454
false−4.248

First 60 of 344 rows.

Most anomalous rows

RankRowABOD score (−angle variance)Most unusualBiggest score dropbill_lenbill_depflipper_lenbody_mass
1294−0.0009bill_len = 58 (robust z +1.9); 52% of its tail scorebill_len: falls 1.45 at its median5817.8001813,700
2186−0.0243body_mass = 6050 (robust z +2.2); 33% of its tail scoreno single feature lowers it59.600172306,050
315−0.0314bill_dep = 21.1 (robust z +1.7); 43% of its tail scorebill_len: falls 1.27 at its median34.60021.1001984,400
4315−0.0830body_mass = 2700 (robust z -1.5); 65% of its tail scorebody_mass: falls 0.492 at its median46.90016.6001922,700
5283−0.0924flipper_len = 178 (robust z -1.2); 47% of its tail scoreflipper_len: falls 4.74 at its median46.10018.2001783,250
6190−0.1072flipper_len = 219 (robust z +1.3); 37% of its tail scoreflipper_len: falls 0.0446 at its median44.40017.3002195,250
7232−0.1126body_mass = 5950 (robust z +2.1); 48% of its tail scorebill_len: falls 0.0141 at its median45.20016.4002235,950
8340−0.1163bill_len = 55.8 (robust z +1.6); 52% of its tail scorebill_len: falls 0.491 at its median55.80019.8002074,000
9143−0.1289bill_len = 32.1 (robust z -1.8); 49% of its tail scorebill_dep: falls 0.197 at its median32.10015.5001883,050
10314−0.1523bill_dep = 20.7 (robust z +1.5); 39% of its tail scorebill_dep: falls 0.191 at its median5220.7002104,800
1199−0.1756bill_len = 33.1 (robust z -1.6); 37% of its tail scoreno single feature lowers it33.10016.1001782,900
1220−0.1787bill_dep = 21.5 (robust z +1.9); 69% of its tail scorebill_dep: falls 1.35 at its median4621.5001944,200
13130−0.1855flipper_len = 210 (robust z +0.8); 32% of its tail scoreflipper_len: falls 20.4 at its median44.100182104,000
14293−0.2185bill_dep = 20 (robust z +1.2); 36% of its tail scorebody_mass: falls 4.73 at its median50.300201973,300
15325−0.2214bill_len = 51.5 (robust z +1.0); 34% of its tail scorebill_len: falls 1.91 at its median51.50018.7001873,250
16327−0.2401body_mass = 3325 (robust z -0.8); 40% of its tail scorebill_dep: falls 0.98 at its median48.10016.4001993,325
17308−0.2853bill_dep = 20.8 (robust z +1.6); 41% of its tail scorebill_len: falls 0.178 at its median54.20020.8002014,300
18170−0.2877body_mass = 6300 (robust z +2.5); 52% of its tail scoreno single feature lowers it49.20015.2002216,300
19324−0.2889bill_dep = 19.6 (robust z +1.0); 39% of its tail scorebody_mass: falls 1.41 at its median4919.6002124,300
2082−0.3298body_mass = 4700 (robust z +0.7); 35% of its tail scorebody_mass: falls 15.6 at its median42.90017.6001964,700
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 2907abc917de7413
# Dataset: ml_penguins (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_penguins.parquet", col_select = c("bill_len", "bill_dep", "flipper_len", "body_mass"))), c("bill_len", "bill_dep", "flipper_len", "body_mass"))
FEATURES <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    bill_len = "numeric",
    bill_dep = "numeric",
    flipper_len = "numeric",
    body_mass = "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 (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA)  # null when the score doesn't use it
if (n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Angle-based scores", min = 3, n = n)
k <- min(8, n - 1L)
extra_values$neighbors <- k
# FastABOD: variance of (a - x).(b - x) / (|a - x|^2 |b - x|^2) over neighbor pairs; score = -variance
.parts <- cs_ml_abod_parts(X, k)
scores <- cs_ml_abod_scores(.parts)
SCORE_LABEL <- "ABOD score (−angle variance)"
rescore <- function(Q, where0, col0) cs_ml_abod_query(X, k, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "abod")

# %% Flag anomalies
RULE <- "cutoff"
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.knn_outlier/penguins_abod_cutoff/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("bill_len", "bill_dep", "flipper_len", "body_mass")
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 = "Nearest-neighbor outlier 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

3 of 344 rows (0.9%) are flagged as anomalies (ABOD score (−angle variance) ≥ -0.0704).

Anomalies
3
Threshold
−0.0704

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

Most anomalous rows

RankRowABOD score (−angle variance)Most unusualBiggest score dropbill_lenbill_depflipper_lenbody_mass
1294−0.0009bill_len = 58 (robust z +1.9); 52% of its tail scorebill_len: falls 1.45 at its median5817.8001813,700
2186−0.0243body_mass = 6050 (robust z +2.2); 33% of its tail scoreno single feature lowers it59.600172306,050
315−0.0314bill_dep = 21.1 (robust z +1.7); 43% of its tail scorebill_len: falls 1.27 at its median34.60021.1001984,400
4315−0.0830body_mass = 2700 (robust z -1.5); 65% of its tail scorebody_mass: falls 0.492 at its median46.90016.6001922,700
5283−0.0924flipper_len = 178 (robust z -1.2); 47% of its tail scoreflipper_len: falls 4.74 at its median46.10018.2001783,250
6190−0.1072flipper_len = 219 (robust z +1.3); 37% of its tail scoreflipper_len: falls 0.0446 at its median44.40017.3002195,250
7232−0.1126body_mass = 5950 (robust z +2.1); 48% of its tail scorebill_len: falls 0.0141 at its median45.20016.4002235,950
8340−0.1163bill_len = 55.8 (robust z +1.6); 52% of its tail scorebill_len: falls 0.491 at its median55.80019.8002074,000
9143−0.1289bill_len = 32.1 (robust z -1.8); 49% of its tail scorebill_dep: falls 0.197 at its median32.10015.5001883,050
10314−0.1523bill_dep = 20.7 (robust z +1.5); 39% of its tail scorebill_dep: falls 0.191 at its median5220.7002104,800
1199−0.1756bill_len = 33.1 (robust z -1.6); 37% of its tail scoreno single feature lowers it33.10016.1001782,900
1220−0.1787bill_dep = 21.5 (robust z +1.9); 69% of its tail scorebill_dep: falls 1.35 at its median4621.5001944,200
13130−0.1855flipper_len = 210 (robust z +0.8); 32% of its tail scoreflipper_len: falls 20.4 at its median44.100182104,000
14293−0.2185bill_dep = 20 (robust z +1.2); 36% of its tail scorebody_mass: falls 4.73 at its median50.300201973,300
15325−0.2214bill_len = 51.5 (robust z +1.0); 34% of its tail scorebill_len: falls 1.91 at its median51.50018.7001873,250
16327−0.2401body_mass = 3325 (robust z -0.8); 40% of its tail scorebill_dep: falls 0.98 at its median48.10016.4001993,325
17308−0.2853bill_dep = 20.8 (robust z +1.6); 41% of its tail scorebill_len: falls 0.178 at its median54.20020.8002014,300
18170−0.2877body_mass = 6300 (robust z +2.5); 52% of its tail scoreno single feature lowers it49.20015.2002216,300
19324−0.2889bill_dep = 19.6 (robust z +1.0); 39% of its tail scorebody_mass: falls 1.41 at its median4919.6002124,300
2082−0.3298body_mass = 4700 (robust z +0.7); 35% of its tail scorebody_mass: falls 15.6 at its median42.90017.6001964,700
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 2907abc917de7413
# Dataset: ml_penguins (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 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_penguins.parquet", columns=["bill_len", "bill_dep", "flipper_len", "body_mass"]), ["bill_len", "bill_dep", "flipper_len", "body_mass"])
FEATURES = ["bill_len", "bill_dep", "flipper_len", "body_mass"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "bill_len": "numeric",
        "bill_dep": "numeric",
        "flipper_len": "numeric",
        "body_mass": "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 (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None}  # null when the score doesn't use it
if n < 3:
    cs_error("CS_E_TOO_FEW_ROWS", what="Angle-based scores", min=3, n=n)
k = min(8, n - 1)
extra_values["neighbors"] = k
# FastABOD: variance of (a - x)·(b - x) / (|a - x|² |b - x|²) over neighbor pairs; score = -variance
_parts = csax.abod_parts(X, k)
scores = csax.abod_scores(_parts)
SCORE_LABEL = "ABOD score (−angle variance)"
rescore = lambda Q, where, col: csax.abod_query(X, k, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "abod")

# %% Flag anomalies
RULE = "cutoff"
_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.knn_outlier/penguins_abod_cutoff/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 = ["bill_len", "bill_dep", "flipper_len", "body_mass", ]
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": "Nearest-neighbor outlier 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"}],
})
03

COF: when the normal data are a line

Read

LOF compares densities in round neighborhoods. If normal rows lie along a thin curve, a row slightly off the curve can have a normal-looking density. COF builds a chain from each row through its nearest neighbors and averages the link lengths along it (the chaining distance). COFk(x)\mathrm{COF}_k(x) compares that with its neighbors' chaining distances: above 1 means weaker connection.

The chain is the method. Replace it with a plain mean neighbor distance and you've built a different detector. Noise points that bridge two groups can reroute chains.

04

CBLOF: small clusters as suspects

Read

CBLOF first clusters the rows, splits clusters into large and small, and scores each row by distance: to its own center if its cluster is large, to the nearest large center if it's small. The weighted version multiplies by cluster size.

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

Here 34 rows sat in small clusters. That's the hidden assumption: small or remote clusters deserve suspicion. A legitimate minority gets flagged as a group, and a poor first clustering passes its errors straight into the scores.

05

Same data, a borrowed cutoff

Predict

Predict first

On the arrests data, you flag states whose COF is at least 1.50, a cutoff that sounded reasonable. How many get flagged?

Several statesNone
Reveal

None. The highest COF was 1.36, so no state reached the cutoff. COF's scale depends on the data and kk; flag a share or calibrate on normal rows instead.

Nearest-neighbor outlier scoresRecorded · Python and R agreeRecorded 2026-11-25 · 78 values compared
R

0 of 50 rows (0.0%) are flagged as anomalies (COF ≥ 1.5).

Anomalies
0
Threshold
1.500

Plots

COF distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyCOF
false0.9685
false1.363
false1.020
false1.245
false1.306
false1.322
false1.318
false1.349
false1.178
false0.9783
false1.295
false1.240
false0.9316
false0.9500
false0.7932
false0.9257
false1.193
false1.035
false0.8803
false0.9470
false1.080
false0.8602
false1.028
false0.9831
false1.264
false1.122
false0.9597
false1.125
false0.8411
false1.294
false0.9736
false0.9287
false1.123
false0.9992
false1.048
false0.9736
false1.140
false0.9441
false1.153
false0.9831
false1.069
false1.143
false1.099
false1.130
false1.257
false1.0000
false1.092
false1.150
false0.9256
false1.046

Most anomalous rows

RankRowCOFMost unusualBiggest score dropMurderAssaultUrbanPopRape
121.363Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.275 at its median102634844.500
281.349Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.307 at its median5.9002387215.800
361.322Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.0499 at its median7.9002047838.700
471.318Rape = 11.1 (robust z -1.0); 32% of its tail scoreRape: falls 0.364 at its median3.3001107711.100
551.306Rape = 40.6 (robust z +2.4); 29% of its tail scoreRape: falls 0.337 at its median92769140.600
6111.295Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.465 at its median5.300468320.200
7301.294UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.563 at its median7.4001598918.800
8251.264Rape = 28.2 (robust z +0.9); 38% of its tail scoreRape: falls 0.218 at its median91787028.200
9451.257UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.507 at its median2.200483211.200
1041.245UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.287 at its median8.8001905019.500
11121.240Murder = 2.6 (robust z -0.9); 34% of its tail scoreMurder: falls 0.367 at its median2.6001205414.200
12171.193UrbanPop = 52 (robust z -0.8); 31% of its tail scoreMurder: falls 0.341 at its median9.7001095216.300
1391.178Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.24 at its median15.4003358031.900
14391.153Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.208 at its median3.400174878.300
15481.150UrbanPop = 39 (robust z -1.5); 37% of its tail scoreno single feature lowers it5.70081399.300
16421.143Murder = 13.2 (robust z +1.1); 37% of its tail scoreRape: falls 0.132 at its median13.2001885926.900
17371.140Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.237 at its median4.9001596729.300
18441.130UrbanPop = 80 (robust z +0.8); 28% of its tail scoreMurder: falls 0.14 at its median3.2001208022.900
19281.125Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.215 at its median12.2002528146
20331.123Assault = 337 (robust z +1.6); 43% of its tail scoreRape: falls 0.0858 at its median133374516.100
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 479343b280732d04
# 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 (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA)  # null when the score doesn't use it
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Nearest-neighbor scores", min = 2, n = n)
k <- min(5, n - 1L)
extra_values$neighbors <- k
# COF: chaining distance along Tang et al.'s set-based nearest path, relative to the neighbors'
.parts <- cs_ml_cof_parts(X, k)
scores <- cs_ml_cof_scores(.parts)
SCORE_LABEL <- "COF"
rescore <- function(Q, where0, col0) cs_ml_cof_query(X, k, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "cof")

# %% Flag anomalies
RULE <- "cutoff"
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.knn_outlier/usarrests_cof_cutoff/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 = "Nearest-neighbor outlier 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

0 of 50 rows (0.0%) are flagged as anomalies (COF ≥ 1.5).

Anomalies
0
Threshold
1.500

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

Most anomalous rows

RankRowCOFMost unusualBiggest score dropMurderAssaultUrbanPopRape
121.363Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.275 at its median102634844.500
281.349Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.307 at its median5.9002387215.800
361.322Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.0499 at its median7.9002047838.700
471.318Rape = 11.1 (robust z -1.0); 32% of its tail scoreRape: falls 0.364 at its median3.3001107711.100
551.306Rape = 40.6 (robust z +2.4); 29% of its tail scoreRape: falls 0.337 at its median92769140.600
6111.295Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.465 at its median5.300468320.200
7301.294UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.563 at its median7.4001598918.800
8251.264Rape = 28.2 (robust z +0.9); 38% of its tail scoreRape: falls 0.218 at its median91787028.200
9451.257UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.507 at its median2.200483211.200
1041.245UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.287 at its median8.8001905019.500
11121.240Murder = 2.6 (robust z -0.9); 34% of its tail scoreMurder: falls 0.367 at its median2.6001205414.200
12171.193UrbanPop = 52 (robust z -0.8); 31% of its tail scoreMurder: falls 0.341 at its median9.7001095216.300
1391.178Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.24 at its median15.4003358031.900
14391.153Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.208 at its median3.400174878.300
15481.150UrbanPop = 39 (robust z -1.5); 37% of its tail scoreno single feature lowers it5.70081399.300
16421.143Murder = 13.2 (robust z +1.1); 37% of its tail scoreRape: falls 0.132 at its median13.2001885926.900
17371.140Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.237 at its median4.9001596729.300
18441.130UrbanPop = 80 (robust z +0.8); 28% of its tail scoreMurder: falls 0.14 at its median3.2001208022.900
19281.125Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.215 at its median12.2002528146
20331.123Assault = 337 (robust z +1.6); 43% of its tail scoreRape: falls 0.0858 at its median133374516.100
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 479343b280732d04
# 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

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 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 (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None}  # null when the score doesn't use it
if n < 2:
    cs_error("CS_E_TOO_FEW_ROWS", what="Nearest-neighbor scores", min=2, n=n)
k = min(5, n - 1)
extra_values["neighbors"] = k
# COF: chaining distance along Tang et al.'s set-based nearest path, relative to the neighbors'
_parts = csax.cof_parts(X, k)
scores = csax.cof_scores(_parts)
SCORE_LABEL = "COF"
rescore = lambda Q, where, col: csax.cof_query(X, k, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "cof")

# %% Flag anomalies
RULE = "cutoff"
_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.knn_outlier/usarrests_cof_cutoff/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": "Nearest-neighbor outlier 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"}],
})
06

SOS: nobody picks you

Read

SOS borrows t-SNE's affinities. Each row ii picks neighbors with probabilities pij∝exp⁡(−βidij2)p_{ij}\propto\exp(-\beta_i d_{ij}^2), with βi\beta_i tuned so every row has the same perplexity (effective number of neighbors). A row's score is the chance that no one picks it: sj=∏i≠j(1−pij)s_j=\prod_{i\ne j}(1-p_{ij}).

Nearest-neighbor outlier scoresRecorded · Python and R agreeRecorded 2026-11-25 · 78 values compared
R

8 of 150 rows (5.3%) are flagged as anomalies (SOS outlier probability ≥ 0.787).

Anomalies
8
Threshold
0.7866

Plots

SOS outlier probability distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalySOS outlier probability
false0.1451
false0.1872
false0.2696
false0.3053
false0.2473
false0.1907
false0.6391
false0.1132
false0.2572
false0.2577
false0.2620
false0.1840
false0.3741
false0.4495
false0.5483
false0.7803
false0.2239
false0.1413
false0.5156
false0.1492
false0.3377
false0.3843
true0.9277
false0.7349
false0.4437
false0.5007
false0.1675
false0.2229
false0.2249
false0.2907
false0.1676
false0.5071
false0.5162
false0.2434
false0.1425
false0.6357
false0.6855
false0.3322
false0.3039
false0.0991
false0.2330
true0.9990
false0.6440
true0.9044
false0.3968
false0.4207
false0.2597
false0.1584
false0.2158
false0.3687
false0.6190
false0.3647
false0.2863
false0.4409
false0.2684
false0.3437
false0.2815
false0.2427
false0.2245
false0.4340

First 60 of 150 rows.

Most anomalous rows

RankRowSOS outlier probabilityMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
1420.9990petal_length = 1.3 (robust z -1.6); 26% of its tail scoresepal_width: falls 0.617 at its median4.5002.3001.3000.3000
21070.9712sepal_width = 2.5 (robust z -1.1); 35% of its tail scoresepal_length: falls 0.401 at its median4.9002.5004.5001.700
3230.9277petal_length = 1 (robust z -1.8); 44% of its tail scoresepal_width: falls 0.451 at its median4.6003.60010.2000
41090.9128sepal_width = 2.5 (robust z -1.1); 29% of its tail scoresepal_width: falls 0.46 at its median6.7002.5005.8001.800
5440.9044petal_length = 1.6 (robust z -1.5); 22% of its tail scoreno single feature lowers it53.5001.6000.6000
6610.8713sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.24 at its median523.5001
71150.8530petal_width = 2.4 (robust z +1.1); 51% of its tail scorepetal_width: falls 0.156 at its median5.8002.8005.1002.400
81190.7866sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.397 at its median7.7002.6006.9002.300
9160.7803sepal_width = 4.4 (robust z +3.1); 61% of its tail scoreno single feature lowers it5.7004.4001.5000.4000
10240.7349petal_length = 1.7 (robust z -1.4); 24% of its tail scoreno single feature lowers it5.1003.3001.7000.5000
111140.7131sepal_width = 2.5 (robust z -1.1); 37% of its tail scoresepal_width: falls 0.226 at its median5.7002.50052
12630.6950sepal_width = 2.2 (robust z -1.8); 58% of its tail scorepetal_width: falls 0.252 at its median62.20041
13370.6855petal_length = 1.3 (robust z -1.6); 38% of its tail scoreno single feature lowers it5.5003.5001.3000.2000
14650.6707petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.492 at its median5.6002.9003.6001.300
15860.6686sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.492 at its median63.4004.5001.600
16770.6619sepal_length = 6.8 (robust z +1.0); 41% of its tail scoresepal_width: falls 0.386 at its median6.8002.8004.8001.400
17430.6440petal_length = 1.3 (robust z -1.6); 30% of its tail scoresepal_width: falls 0.362 at its median4.4003.2001.3000.2000
1870.6391petal_length = 1.4 (robust z -1.6); 25% of its tail scoresepal_width: falls 0.289 at its median4.6003.4001.4000.3000
19360.6357petal_length = 1.2 (robust z -1.7); 47% of its tail scoresepal_width: falls 0.153 at its median53.2001.2000.2000
201100.6220sepal_length = 7.2 (robust z +1.3); 23% of its tail scoreno single feature lowers it7.2003.6006.1002.500
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 086edc3021752402
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)


# %% 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_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width"))), c("sepal_length", "sepal_width", "petal_length", "petal_width"))
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
  df, FEATURES,
  kinds = list(
    sepal_length = "numeric",
    sepal_width = "numeric",
    petal_length = "numeric",
    petal_width = "numeric"
  ),
  levels = list(
  ),
  impute = IMPUTE,
  scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df))  # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L

# %% Scores (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA)  # null when the score doesn't use it
PERPLEXITY <- 6
if (n - 1 <= PERPLEXITY) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("SOS with perplexity %s", format(PERPLEXITY)), min = as.integer(floor(PERPLEXITY)) + 2L, n = n)
.parts <- cs_ml_sos_parts(X, PERPLEXITY)
scores <- exp(.parts$log_o)
SCORE_LABEL <- "SOS outlier probability"
extra_values$perplexity <- PERPLEXITY
rescore <- function(Q, where0, col0) cs_ml_sos_query(X, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "sos")

# %% 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.knn_outlier/iris_sos/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("sepal_length", "sepal_width", "petal_length", "petal_width")
why <- NULL
if (length(NUMERIC)) {
  F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
  med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
  for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
  why <- cs_ml_anomaly_explain(F_, top - 1L)
  for (rank in seq_len(min(10L, length(top)))) {
    values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
    values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
    values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
  }
  # 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 = "Nearest-neighbor outlier 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

8 of 150 rows (5.3%) are flagged as anomalies (SOS outlier probability ≥ 0.787).

Anomalies
8
Threshold
0.7866

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

Most anomalous rows

RankRowSOS outlier probabilityMost unusualBiggest score dropsepal_lengthsepal_widthpetal_lengthpetal_width
1420.9990petal_length = 1.3 (robust z -1.6); 26% of its tail scoresepal_width: falls 0.617 at its median4.5002.3001.3000.3000
21070.9712sepal_width = 2.5 (robust z -1.1); 35% of its tail scoresepal_length: falls 0.401 at its median4.9002.5004.5001.700
3230.9277petal_length = 1 (robust z -1.8); 44% of its tail scoresepal_width: falls 0.451 at its median4.6003.60010.2000
41090.9128sepal_width = 2.5 (robust z -1.1); 29% of its tail scoresepal_width: falls 0.46 at its median6.7002.5005.8001.800
5440.9044petal_length = 1.6 (robust z -1.5); 22% of its tail scoreno single feature lowers it53.5001.6000.6000
6610.8713sepal_width = 2 (robust z -2.2); 59% of its tail scoresepal_length: falls 0.24 at its median523.5001
71150.8530petal_width = 2.4 (robust z +1.1); 51% of its tail scorepetal_width: falls 0.156 at its median5.8002.8005.1002.400
81190.7866sepal_length = 7.7 (robust z +1.8); 27% of its tail scoresepal_width: falls 0.397 at its median7.7002.6006.9002.300
9160.7803sepal_width = 4.4 (robust z +3.1); 61% of its tail scoreno single feature lowers it5.7004.4001.5000.4000
10240.7349petal_length = 1.7 (robust z -1.4); 24% of its tail scoreno single feature lowers it5.1003.3001.7000.5000
111140.7131sepal_width = 2.5 (robust z -1.1); 37% of its tail scoresepal_width: falls 0.226 at its median5.7002.50052
12630.6950sepal_width = 2.2 (robust z -1.8); 58% of its tail scorepetal_width: falls 0.252 at its median62.20041
13370.6855petal_length = 1.3 (robust z -1.6); 38% of its tail scoreno single feature lowers it5.5003.5001.3000.2000
14650.6707petal_length = 3.6 (robust z -0.4); 29% of its tail scorepetal_length: falls 0.492 at its median5.6002.9003.6001.300
15860.6686sepal_width = 3.4 (robust z +0.9); 35% of its tail scoresepal_width: falls 0.492 at its median63.4004.5001.600
16770.6619sepal_length = 6.8 (robust z +1.0); 41% of its tail scoresepal_width: falls 0.386 at its median6.8002.8004.8001.400
17430.6440petal_length = 1.3 (robust z -1.6); 30% of its tail scoresepal_width: falls 0.362 at its median4.4003.2001.3000.2000
1870.6391petal_length = 1.4 (robust z -1.6); 25% of its tail scoresepal_width: falls 0.289 at its median4.6003.4001.4000.3000
19360.6357petal_length = 1.2 (robust z -1.7); 47% of its tail scoresepal_width: falls 0.153 at its median53.2001.2000.2000
201100.6220sepal_length = 7.2 (robust z +1.3); 23% of its tail scoreno single feature lowers it7.2003.6006.1002.500
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 086edc3021752402
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
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_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"])
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
    df,
    FEATURES,
    kinds={
        "sepal_length": "numeric",
        "sepal_width": "numeric",
        "petal_length": "numeric",
        "petal_width": "numeric",
    },
    levels={
    },
    impute=IMPUTE,
    scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df)  # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))

# %% Scores (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None}  # null when the score doesn't use it
PERPLEXITY = 6
if n - 1 <= PERPLEXITY:
    cs_error("CS_E_TOO_FEW_ROWS", what=f"SOS with perplexity {PERPLEXITY:g}", min=int(PERPLEXITY) + 2, n=n)
_parts = csax.sos_parts(X, PERPLEXITY)
scores = np.exp(_parts["log_o"])
SCORE_LABEL = "SOS outlier probability"
extra_values["perplexity"] = PERPLEXITY
rescore = lambda Q, where, col: csax.sos_query(X, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "sos")

# %% 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.knn_outlier/iris_sos/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 = ["sepal_length", "sepal_width", "petal_length", "petal_width", ]
why = None
if NUMERIC:
    _F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
    _med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
    _F = np.where(np.isnan(_F), _med[None, :], _F)
    why = _dx.explain_rows(_F, top)
    for rank in range(1, min(10, len(top)) + 1):
        values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
        values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
        values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
    # 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": "Nearest-neighbor outlier 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"}],
})

The perplexity here was 6. The score is a probability inside SOS's selection model, not a calibrated chance of being an anomaly. It builds an affinity for every pair of rows, so it scales with the square of the row count.

07

LOCI: check every scale

Read

LOCI compares, at many radii rr, how many rows sit within αr\alpha r of a row with the average count around its neighbors: the multigranularity deviation MDEF=1−n(x,αr)/n^(x,r,α)\mathrm{MDEF}=1-n(x,\alpha r)/\hat n(x,r,\alpha). A row is flagged when MDEF exceeds a multiple of its own standard deviation at some radius, three in the classic rule.

Nearest-neighbor outlier scoresRecorded · Python and R agreeRecorded 2026-11-25 · 78 values compared
R

4 of 50 rows (8.0%) are flagged as anomalies (LOCI (largest MDEF / σ) ≥ 3).

Anomalies
4
Threshold
3

Plots

LOCI (largest MDEF / σ) distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyLOCI (largest MDEF / σ)
false0.1268
false2.445
false0.8848
false−0.4023
false2.767
false0.9984
false0.3149
false−0.7388
true4.899
false1.369
false0.8193
false0.4478
false−0.0792
false−0.9882
false1.355
false−0.7858
false−0.1758
false0.7217
false1.815
false0.3470
false−0.0107
false0.6715
false0.4014
false2.035
false−0.9442
false−0.2575
false−0.2101
true4.364
false1.777
false0.2249
false0.3620
false0.4622
false2.259
true3.748
false−0.8787
false−1.135
false−0.8105
false−0.4773
false2.051
false1.518
false0.9018
false−0.1365
false−0.0544
false−0.1647
true4.899
false−1.367
false−0.6486
false1.955
false1.006
false−0.9127

Most anomalous rows

RankRowLOCI (largest MDEF / σ)Most unusualBiggest score dropMurderAssaultUrbanPopRape
194.899Assault = 335 (robust z +1.6); 35% of its tail scoreAssault: falls 3.67 at its median15.4003358031.900
2454.899UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 3.69 at its median2.200483211.200
3284.364Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 3.97 at its median12.2002528146
4343.748Rape = 7.3 (robust z -1.5); 27% of its tail scoreAssault: falls 1.59 at its median0.800045447.300
552.767Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 1.47 at its median92769140.600
622.445Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 1.77 at its median102634844.500
7332.259Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 1.26 at its median133374516.100
8392.051Rape = 8.3 (robust z -1.4); 36% of its tail scoreUrbanPop: falls 2.06 at its median3.400174878.300
9242.035Murder = 16.1 (robust z +1.6); 39% of its tail scoreUrbanPop: falls 0.887 at its median16.1002594417.100
10481.955UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 1.58 at its median5.70081399.300
11191.815Rape = 7.8 (robust z -1.4); 34% of its tail scoreMurder: falls 1.24 at its median2.10083517.800
12291.777Rape = 9.5 (robust z -1.2); 27% of its tail scoreMurder: falls 1.24 at its median2.10057569.500
13401.518Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.791 at its median14.4002794822.500
14101.369Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 2.45 at its median17.4002116025.800
15151.355Rape = 11.3 (robust z -1.0); 23% of its tail scoreMurder: falls 1.06 at its median2.200565711.300
16491.006Rape = 10.8 (robust z -1.1); 29% of its tail scoreAssault: falls 1.04 at its median2.600536610.800
1760.9984Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 1.87 at its median7.9002047838.700
18410.9018UrbanPop = 45 (robust z -1.2); 31% of its tail scoreUrbanPop: falls 0.687 at its median3.800864512.800
1930.8848Rape = 31 (robust z +1.3); 28% of its tail scoreAssault: falls 1.25 at its median8.1002948031
20110.8193Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 1.04 at its median5.300468320.200
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec fd1fad347f683197
# 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 (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA)  # null when the score doesn't use it
if (n < 20L) cs_error("CS_E_TOO_FEW_ROWS", what = "LOCI", min = 20L, n = n)
if (n > 500L) cs_error("CS_E_INVALID_OPTION", option = "Score", allowed = "another score above 500 rows (exact LOCI time grows with the cube of the rows)", value = sprintf("LOCI on %d rows", n))
.parts <- cs_ml_loci_parts(X)
scores <- cs_ml_loci_scores(.parts)
SCORE_LABEL <- "LOCI (largest MDEF / σ)"
rescore <- function(Q, where0, col0) cs_ml_loci_query(X, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "loci")

# %% Flag anomalies
RULE <- "cutoff"
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.knn_outlier/usarrests_loci_cutoff/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 = "Nearest-neighbor outlier 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

4 of 50 rows (8.0%) are flagged as anomalies (LOCI (largest MDEF / σ) ≥ 3).

Anomalies
4
Threshold
3

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

Most anomalous rows

RankRowLOCI (largest MDEF / σ)Most unusualBiggest score dropMurderAssaultUrbanPopRape
194.899Assault = 335 (robust z +1.6); 35% of its tail scoreAssault: falls 3.67 at its median15.4003358031.900
2454.899UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 3.69 at its median2.200483211.200
3284.364Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 3.97 at its median12.2002528146
4343.748Rape = 7.3 (robust z -1.5); 27% of its tail scoreAssault: falls 1.59 at its median0.800045447.300
552.767Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 1.47 at its median92769140.600
622.445Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 1.77 at its median102634844.500
7332.259Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 1.26 at its median133374516.100
8392.051Rape = 8.3 (robust z -1.4); 36% of its tail scoreUrbanPop: falls 2.06 at its median3.400174878.300
9242.035Murder = 16.1 (robust z +1.6); 39% of its tail scoreUrbanPop: falls 0.887 at its median16.1002594417.100
10481.955UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 1.58 at its median5.70081399.300
11191.815Rape = 7.8 (robust z -1.4); 34% of its tail scoreMurder: falls 1.24 at its median2.10083517.800
12291.777Rape = 9.5 (robust z -1.2); 27% of its tail scoreMurder: falls 1.24 at its median2.10057569.500
13401.518Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.791 at its median14.4002794822.500
14101.369Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 2.45 at its median17.4002116025.800
15151.355Rape = 11.3 (robust z -1.0); 23% of its tail scoreMurder: falls 1.06 at its median2.200565711.300
16491.006Rape = 10.8 (robust z -1.1); 29% of its tail scoreAssault: falls 1.04 at its median2.600536610.800
1760.9984Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 1.87 at its median7.9002047838.700
18410.9018UrbanPop = 45 (robust z -1.2); 31% of its tail scoreUrbanPop: falls 0.687 at its median3.800864512.800
1930.8848Rape = 31 (robust z +1.3); 28% of its tail scoreAssault: falls 1.25 at its median8.1002948031
20110.8193Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 1.04 at its median5.300468320.200
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec fd1fad347f683197
# 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

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 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 (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None}  # null when the score doesn't use it
if n < csax.LOCI_N_MIN:
    cs_error("CS_E_TOO_FEW_ROWS", what="LOCI", min=csax.LOCI_N_MIN, n=n)
if n > csax.LOCI_MAX_ROWS:
    cs_error("CS_E_INVALID_OPTION", option="Score", allowed=f"another score above {csax.LOCI_MAX_ROWS} rows (exact LOCI time grows with the cube of the rows)", value=f"LOCI on {n} rows")
_parts = csax.loci_parts(X)
scores = csax.loci_scores(_parts)
SCORE_LABEL = "LOCI (largest MDEF / σ)"
rescore = lambda Q, where, col: csax.loci_query(X, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "loci")

# %% Flag anomalies
RULE = "cutoff"
_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.knn_outlier/usarrests_loci_cutoff/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": "Nearest-neighbor outlier 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"}],
})

Checking every radius finds both isolated rows and small sparse groups, and tells you at which scale. But searching many radii for every row is not a test with a controlled error rate: the "three" rule sets a flag, not a guarantee.

08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
ABOD (UCL052)Runs in CodeSplash: Nearest-neighbor outlier scores, Angle-based (FastABOD)
COF (UCL053)Runs in CodeSplash: Nearest-neighbor outlier scores, COF
CBLOF (UCL054)Runs in CodeSplash: Cluster-based local outlier factor (CBLOF)
SOS (UCL062)Runs in CodeSplash: Nearest-neighbor outlier scores, SOS
LOCI (UCL065)Runs in CodeSplash: Nearest-neighbor outlier scores, LOCI
09

Check your understanding

Checkpoint

Check yourself

In ABOD, what does a low variance of angles mean for a row?

Show the answer

Answer: b

From inside a cloud, pairs of points surround you at all angles. From outside, the angles cluster.

Check yourself

Why does ABOD need deliberate feature scaling?

Show the answer

Answer: a

Angles aren't invariant to stretching one axis. Choose the scaling for the question, then keep it fixed.

Check yourself

Normal machine readings lie along a thin curved path. Which score is built for rows just off that path?

Show the answer

Answer: b

Round neighborhoods mix the path with empty space. COF's chaining distance follows the path, so a row off it connects poorly.

Check yourself

A library computes "COF" as the mean distance to the k nearest neighbors divided by the neighbors' means. Is that COF?

Show the answer

Answer: b

The path construction is what lets COF follow elongated shapes. Check what an implementation computes before comparing results.

Check yourself

CBLOF flags all forty members of a small cluster. What should you check?

Show the answer

Answer: b

CBLOF scores the cluster's size and distance, not each row's oddness. Audit cluster-level flags separately from point-level ones.

Check yourself

How does the first clustering affect CBLOF?

Show the answer

Answer: a

Report the clusterer and its stability with the anomaly results, and try the weighted and unweighted versions.

Check yourself

What is an SOS score?

Show the answer

Answer: b

Rows nobody would pick are outliers. The probability lives inside the selection model; it isn't calibrated against real anomalies.

Check yourself

What does SOS's perplexity setting do?

Show the answer

Answer: a

Each row's β is tuned to hit the perplexity, so dense and sparse regions get comparable affinities. Check the ranking across a few perplexities.

Check yourself

What does LOCI's multi-radius search add?

Show the answer

Answer: b

Comparing counts across radii catches isolated rows and small sparse groups alike.

Check yourself

LOCI flags rows whose deviation exceeds three standard deviations at some radius. Is that a test with a 0.1% false-alarm rate?

Show the answer

Answer: b

Searching many scales multiplies chances to cross the line. Calibrate false alarms on reference data if you need a rate.

10

Do it on your own data

In the app

Under Spot anomalies, open Nearest-neighbor outlier scores and switch Score between FastABOD, COF, SOS and LOCI on the same rows; open Cluster-based local outlier factor (CBLOF) and look at the small clusters before you read the flags.

Concepts in this lesson