Skip to content

Neighbors, angles and chains: more anomaly scores

Seven ways to turn a row's nearest neighbors into an anomaly score, from plain distances to angles, chains, selection probabilities and multi-scale counts, plus LoOP's 0–1 version of LOF.

Applied ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Choose between distance, angle, chaining and multi-scale neighbor scores for a question
  • Read each score's direction and its usual cutoff
  • Explain what LoOP adds to LOF and why it is not a calibrated probability

Read first

01

One idea, seven scores

Read

Every detector in Nearest-neighbor outlier scores starts the same way: standardize the features, measure exact distances, and find each row's nearest other rows. Ties are broken by row order, so Python and R pick the same neighbors. What differs is how the neighbors become one number.

02

Seven scores at a glance

Read
ScoreA row is unusual if…Higher meansUsual cutoff
kth distancekNN outlier scoreDistance from a row to its kth nearest other row (or the mean or median of its k neighbor distances).its kth neighbor is far awaymore isolatedmedian + 3 MADs
Mean or median distanceits k neighbors are far on averagemore isolatedmedian + 3 MADs
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 angles to its neighbor pairs barely varymore outside the datathe same rule on log variance
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.the nearest path through its neighbors is long compared with theirsweaker connection1.5
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.no other row would pick it as a neighbormore probable outlier0.5
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.at some radius it has far fewer neighbors than its neighbors dobigger drop, in σ3

The cutoff column only matters when Flag anomalies by is Score cutoff and you leave the cutoff empty. With the default fixed share, every score flags the same number of rows; they pick different rows.

03

The plain distance

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

5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).

Anomalies
5
Threshold
1.696

Plots

kth-neighbor distance distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
Anomalykth-neighbor distance
false1.296
true2.360
false1.224
false1.303
true1.696
false1.413
false1.087
false1.567
true1.767
false1.599
false1.398
false0.8672
false1.357
false0.8498
false0.8672
false0.7666
false1.191
false1.329
false0.8572
false1.303
false1.145
false1.274
false0.9845
false1.643
false1.177
false0.8947
false0.8569
true1.946
false0.9343
false1.471
false1.346
false1.346
true2.075
false1.064
false0.9824
false0.7441
false1.253
false0.8569
false1.654
false1.411
false0.9975
false1.365
false1.346
false1.250
false1.689
false0.9874
false1.152
false1.289
false1.046
false0.8989

Most anomalous rows

RankRowkth-neighbor distanceMost unusualBiggest score dropMurderAssaultUrbanPopRape
122.360Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.881 at its median102634844.500
2332.075Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.514 at its median133374516.100
3281.946Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.522 at its median12.2002528146
491.767Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.241 at its median15.4003358031.900
551.696Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.257 at its median92769140.600
6451.689UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.654 at its median2.200483211.200
7391.654Rape = 8.3 (robust z -1.4); 36% of its tail scoreUrbanPop: falls 0.324 at its median3.400174878.300
8241.643Murder = 16.1 (robust z +1.6); 39% of its tail scoreRape: falls 0.0783 at its median16.1002594417.100
9101.599Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.479 at its median17.4002116025.800
1081.567Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.703 at its median5.9002387215.800
11301.471UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.841 at its median7.4001598918.800
1261.413Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.355 at its median7.9002047838.700
13401.411Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.131 at its median14.4002794822.500
14111.398Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.386 at its median5.300468320.200
15421.365Murder = 13.2 (robust z +1.1); 37% of its tail scoreMurder: falls 0.283 at its median13.2001885926.900
16131.357UrbanPop = 83 (robust z +1.0); 36% of its tail scoreUrbanPop: falls 0.214 at its median10.4002498324
17431.346Murder = 12.7 (robust z +1.0); 33% of its tail scoreMurder: falls 0.214 at its median12.7002018025.500
18311.346Rape = 32.1 (robust z +1.4); 32% of its tail scoreAssault: falls 0.0137 at its median11.4002857032.100
19321.346UrbanPop = 86 (robust z +1.1); 38% of its tail scoreUrbanPop: falls 0.262 at its median11.1002548626.100
20181.329Murder = 15.4 (robust z +1.5); 47% of its tail scoreMurder: falls 0.0502 at its median15.4002496622.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 7df4f7819d6700bf
# 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
METHOD <- "kth"
scores <- cs_ml_knn_scores(X, k, METHOD)
SCORE_LABEL <- "kth-neighbor distance"
rescore <- function(Q, where0, col0) cs_ml_knn_query(X, k, METHOD, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth")

# %% 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.1, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.knn_outlier/usarrests_kth/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

5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).

Anomalies
5
Threshold
1.696

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

Most anomalous rows

RankRowkth-neighbor distanceMost unusualBiggest score dropMurderAssaultUrbanPopRape
122.360Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.881 at its median102634844.500
2332.075Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.514 at its median133374516.100
3281.946Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.522 at its median12.2002528146
491.767Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.241 at its median15.4003358031.900
551.696Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.257 at its median92769140.600
6451.689UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.654 at its median2.200483211.200
7391.654Rape = 8.3 (robust z -1.4); 36% of its tail scoreUrbanPop: falls 0.324 at its median3.400174878.300
8241.643Murder = 16.1 (robust z +1.6); 39% of its tail scoreRape: falls 0.0783 at its median16.1002594417.100
9101.599Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.479 at its median17.4002116025.800
1081.567Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.703 at its median5.9002387215.800
11301.471UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.841 at its median7.4001598918.800
1261.413Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 0.355 at its median7.9002047838.700
13401.411Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.131 at its median14.4002794822.500
14111.398Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.386 at its median5.300468320.200
15421.365Murder = 13.2 (robust z +1.1); 37% of its tail scoreMurder: falls 0.283 at its median13.2001885926.900
16131.357UrbanPop = 83 (robust z +1.0); 36% of its tail scoreUrbanPop: falls 0.214 at its median10.4002498324
17431.346Murder = 12.7 (robust z +1.0); 33% of its tail scoreMurder: falls 0.214 at its median12.7002018025.500
18311.346Rape = 32.1 (robust z +1.4); 32% of its tail scoreAssault: falls 0.0137 at its median11.4002857032.100
19321.346UrbanPop = 86 (robust z +1.1); 38% of its tail scoreUrbanPop: falls 0.262 at its median11.1002548626.100
20181.329Murder = 15.4 (robust z +1.5); 47% of its tail scoreMurder: falls 0.0502 at its median15.4002496622.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 7df4f7819d6700bf
# 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
METHOD = "kth"
scores = csax.knn_scores(X, k, METHOD)
SCORE_LABEL = "kth-neighbor distance"
rescore = lambda Q, where, col: csax.knn_query(X, k, METHOD, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth")

# %% 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.1, _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_kth/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"}],
})

With k = 5 on US arrests, the most isolated state's fifth neighbor is 2.36 standard units away, and the share rule flags 5 of 50 states.

The kth distance looks at one neighbor, so it reacts to a gap right at k. The mean of the k distances is steadier, and the median ignores one very near or very far neighbor. If a small group of outliers sit together, a k smaller than the group makes them each other's neighbors and hides them. That is the same masking you met with robust covariance.

04

Angles: ABOD

Predict

Predict first

ABOD's score is minus the variance of the angles to pairs of neighbors. Is the most unusual penguin's score close to 0 or very negative?

Close to 0Very negative
Reveal

Close to 0: here the largest score is −0.00092 and the mean is −5.52. From inside the data, neighbors lie in every direction and the angles vary a lot. From outside, they all lie roughly one way, so the variance is small and minus the variance is near 0.

Angles keep their contrast in many dimensions, where distances start to look alike. The price is pairs: k neighbors make k(k − 1)/2 angles per row.

05

Chains: COF

Read

LOF assumes normal rows fill a round neighborhood. When normal rows form a thin line, a row on the line looks sparse to LOF. COF instead walks the shortest chain through the neighbors (Tang et al.'s set-based nearest path) and compares the row's average link length with its neighbors'.

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

With the usual cutoff of 1.5, COF flags 0 states: the largest COF is 1.36. A cutoff lets the answer be "nothing stands out", which a fixed share never can.

06

Selection: SOS

Read

SOS gives every row a bandwidth so that it spreads its attention over about perplexity neighbors, then asks how likely it is that no row picks a given row. On iris with perplexity 6, the share rule flags 8 flowers, every one with an outlier probability of at least 0.79.

The probability comes from the model's own assumptions. It ranks rows well, but it isn't the chance that a row is an error.

07

Every radius: LOCI

Read

LOCI compares the number of rows within a small radius of a row with the same count around its neighbors, and repeats that at every radius where the counts change. The score is the largest standardized drop, so a cutoff of 3 means "fewer neighbors than expected by more than 3 standard deviations at some scale".

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

On US arrests 4 states cross 3. Looking at every radius is exact but slow: the work grows with the cube of the rows, so CodeSplash runs LOCI on up to 500 rows and suggests another score above that.

08

LoOP: LOF on a 0–1 scale

In the app

Local outlier factor now has a second score. LoOPLocal outlier probability (LoOP)A 0–1 outlier score from the same neighborhoods as LOF, scaled by how unusual the local density ratios are across the data. uses the same neighborhoods but scales the density comparison by how unusual such comparisons are across the whole table, then maps it to 0–1.

Local outlier factorRecorded · Python and R agreeRecorded 2026-11-25 · 77 values compared
R

5 of 50 rows (10.0%) are flagged as anomalies (LoOP ≥ 0.371).

Anomalies
5
Threshold
0.3707

Plots

LoOP distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyLoOP
false0
true0.7783
false0.0539
false0.2647
false0.1538
false0.0609
false0.0542
true0.7356
true0.3707
false0.0806
false0.3651
false0.0968
false0
false0
false0
false0
false0.2797
false0
false0
false0.0448
false0
false0
false0.1303
false0.0955
false0.2516
false0
false0
false0.2783
false0
false0.3557
false0
false0
true0.4230
false0.1373
false0.1274
false0
false0.3005
false0.1757
false0.2922
false0
false0.0043
false0.0968
false0.0375
false0.1208
true0.4470
false0.1177
false0.1003
false0.2144
false0.0393
false0.1572

Most anomalous rows

RankRowLoOPMost unusualBiggest score dropMurderAssaultUrbanPopRape
120.7783Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.778 at its median102634844.500
280.7356Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.69 at its median5.9002387215.800
3450.4470UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.447 at its median2.200483211.200
4330.4230Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.246 at its median133374516.100
590.3707Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.229 at its median15.4003358031.900
6110.3651Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.365 at its median5.300468320.200
7300.3557UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.356 at its median7.4001598918.800
8370.3005Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.287 at its median4.9001596729.300
9390.2922Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.224 at its median3.400174878.300
10170.2797UrbanPop = 52 (robust z -0.8); 31% of its tail scoreAssault: falls 0.0989 at its median9.7001095216.300
11280.2783Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.278 at its median12.2002528146
1240.2647UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.197 at its median8.8001905019.500
13250.2516Rape = 28.2 (robust z +0.9); 38% of its tail scoreMurder: falls 0.117 at its median91787028.200
14480.2144UrbanPop = 39 (robust z -1.5); 37% of its tail scoreno single feature lowers it5.70081399.300
15380.1757Rape = 14.9 (robust z -0.6); 30% of its tail scoreAssault: falls 0.176 at its median6.3001067214.900
16500.1572Rape = 15.6 (robust z -0.5); 34% of its tail scoreRape: falls 0.142 at its median6.8001616015.600
1750.1538Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.154 at its median92769140.600
18340.1373Rape = 7.3 (robust z -1.5); 27% of its tail scoreno single feature lowers it0.800045447.300
19230.1303Murder = 2.7 (robust z -0.8); 32% of its tail scoreno single feature lowers it2.700726614.900
20350.1274UrbanPop = 75 (robust z +0.5); 33% of its tail scoreUrbanPop: falls 0.127 at its median7.3001207521.400
The exact R script · R R version 4.5.1 (2025-06-13)
# Local outlier factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lof 1.3.0 · spec 9238cdb0e1ddc8b3
# 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
if (nrow(df) < 2L) cs_error("CS_E_TOO_FEW_ROWS", what = "Local outlier scores", min = 2L, n = nrow(df))
k <- min(5, nrow(df) - 1L)
# LoOP (Kriegel et al. 2009) on the same tie-inclusive neighborhoods (twin: codesplash.ml.anomaly_ext.loop)
LAM <- 3
.loop_parts <- cs_ml_loop_parts(X, k, LAM)
scores <- cs_ml_loop_scores(.loop_parts)
SCORE_LABEL <- "LoOP"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = k)
DEFAULT_CUTOFF <- 0.5
rescore <- function(Q, where0, col0) cs_ml_loop_query(X, k, LAM, .loop_parts, Q, where0)  # the other rows as fitted

# %% 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.1, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows)  # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.lof/usarrests_loop/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 = "Local outlier factor",
  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

5 of 50 rows (10.0%) are flagged as anomalies (LoOP ≥ 0.371).

Anomalies
5
Threshold
0.3707

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

Most anomalous rows

RankRowLoOPMost unusualBiggest score dropMurderAssaultUrbanPopRape
120.7783Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 0.778 at its median102634844.500
280.7356Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 0.69 at its median5.9002387215.800
3450.4470UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 0.447 at its median2.200483211.200
4330.4230Assault = 337 (robust z +1.6); 43% of its tail scoreAssault: falls 0.246 at its median133374516.100
590.3707Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 0.229 at its median15.4003358031.900
6110.3651Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 0.365 at its median5.300468320.200
7300.3557UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 0.356 at its median7.4001598918.800
8370.3005Rape = 29.3 (robust z +1.1); 40% of its tail scoreRape: falls 0.287 at its median4.9001596729.300
9390.2922Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 0.224 at its median3.400174878.300
10170.2797UrbanPop = 52 (robust z -0.8); 31% of its tail scoreAssault: falls 0.0989 at its median9.7001095216.300
11280.2783Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 0.278 at its median12.2002528146
1240.2647UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 0.197 at its median8.8001905019.500
13250.2516Rape = 28.2 (robust z +0.9); 38% of its tail scoreMurder: falls 0.117 at its median91787028.200
14480.2144UrbanPop = 39 (robust z -1.5); 37% of its tail scoreno single feature lowers it5.70081399.300
15380.1757Rape = 14.9 (robust z -0.6); 30% of its tail scoreAssault: falls 0.176 at its median6.3001067214.900
16500.1572Rape = 15.6 (robust z -0.5); 34% of its tail scoreRape: falls 0.142 at its median6.8001616015.600
1750.1538Rape = 40.6 (robust z +2.4); 29% of its tail scoreUrbanPop: falls 0.154 at its median92769140.600
18340.1373Rape = 7.3 (robust z -1.5); 27% of its tail scoreno single feature lowers it0.800045447.300
19230.1303Murder = 2.7 (robust z -0.8); 32% of its tail scoreno single feature lowers it2.700726614.900
20350.1274UrbanPop = 75 (robust z +0.5); 33% of its tail scoreUrbanPop: falls 0.127 at its median7.3001207521.400
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Local outlier factor
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.lof 1.3.0 · spec 9238cdb0e1ddc8b3
# 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.ml import anomaly as csanom
from codesplash.ml import embed as csembed

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

# %% Scores
if len(df) < 2:
    cs.cs_error("CS_E_TOO_FEW_ROWS", what="Local outlier scores", min=2, n=len(df))
k = min(5, len(df) - 1)
# LoOP (Kriegel et al. 2009) on the same tie-inclusive neighborhoods (twin: codesplashr::cs_ml_loop)
from codesplash.ml import anomaly_ext as csax

LAM = 3
_loop_parts = csax.loop_parts(X, k, LAM)
scores = csax.loop_scores(_loop_parts)
SCORE_LABEL = "LoOP"
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": k}
DEFAULT_CUTOFF = 0.5
rescore = lambda Q, where, col: csax.loop_query(X, k, LAM, _loop_parts, Q, where)  # the other rows as fitted

# %% 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.1, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.lof/usarrests_loop/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": "Local outlier factor",
    "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"}],
})

Its largest score on US arrests is 0.78. Leave the cutoff empty with Score cutoff and LoOP flags rows at 0.5 or above; on Pima that is 22 of 532 rows. λ (default 3) sets how strict the scaling is.

09

Check your understanding

Checkpoint

Check yourself

Six fraudulent accounts sit close together, far from everyone else. You score them with the distance to the 3rd neighbor. What is the risk?

Show the answer

Answer: a

With k smaller than the group, each account's neighbors are other fraudulent accounts. Raise k above the group size, or use a score that compares densities across scales such as LOCI.

Check yourself

Two rows have ABOD scores of −0.0009 and −5.5. Which one is more unusual?

Show the answer

Answer: a

The score is minus the angle variance. A row outside the data sees its neighbors in a narrow cone, so the variance is tiny and the score is close to 0.

Check yourself

You switch to Score cutoff and leave the value empty. Which score uses 3 as its cutoff?

Show the answer

Answer: c

LOCI's score is a deviation in standard deviations, so 3 is the paper's rule. COF uses 1.5 (about 1 is typical) and SOS 0.5 (a probability).

Check yourself

LoOP gives a row 0.92. What can you say?

Show the answer

Answer: b

LoOP's 0–1 scale makes rows comparable and gives a natural cutoff, but the number comes from a modeling assumption, not from known errors.

10

Do it on your own data

In the app

In Spot anomalies, pick Nearest-neighbor outlier scores and try two scores on the same features. Rows both scores flag deserve a look first.

Python
import pandas as pd
from pyod.models.knn import KNN
from sklearn.preprocessing import StandardScaler

df = pd.read_csv("usarrests.csv")
X = StandardScaler().fit_transform(df[["Murder", "Assault", "UrbanPop", "Rape"]])
kth = KNN(n_neighbors=5, method="largest").fit(X).decision_scores_
print(kth.round(3)[:5])
R
df <- read.csv("usarrests.csv")
X <- scale(df[, c("Murder", "Assault", "UrbanPop", "Rape")])
X <- X * sqrt(nrow(X) / (nrow(X) - 1))  # population SD, as the app and scikit-learn use
round(head(dbscan::kNNdist(X, k = 5)), 3)
11

Recap

Recap
  • All seven scores start from exact nearest neighbors; they differ in what they make of them.
  • Know each score's direction and usual cutoff before you read a flag.
  • LoOP puts LOF on a 0–1 scale; it ranks rows, it doesn't measure a real-world probability.

Concepts in this lesson