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.
What runs in CodeSplash
- Nearest-neighbor outlier scores Verified in Python and R
- Local outlier factor Verified in Python and R
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
One idea, seven scores
ReadEvery 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.
Seven scores at a glance
Read| Score | A row is unusual if… | Higher means | Usual 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 away | more isolated | median + 3 MADs |
| Mean or median distance | its k neighbors are far on average | more isolated | median + 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 vary | more outside the data | the 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 theirs | weaker connection | 1.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 neighbor | more probable outlier | 0.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 do | bigger 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.
The plain distance
In the app5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).
- Anomalies
- 5
- Threshold
- 1.696
Plots
View data
| Anomaly | kth-neighbor distance |
|---|---|
| false | 1.296 |
| true | 2.360 |
| false | 1.224 |
| false | 1.303 |
| true | 1.696 |
| false | 1.413 |
| false | 1.087 |
| false | 1.567 |
| true | 1.767 |
| false | 1.599 |
| false | 1.398 |
| false | 0.8672 |
| false | 1.357 |
| false | 0.8498 |
| false | 0.8672 |
| false | 0.7666 |
| false | 1.191 |
| false | 1.329 |
| false | 0.8572 |
| false | 1.303 |
| false | 1.145 |
| false | 1.274 |
| false | 0.9845 |
| false | 1.643 |
| false | 1.177 |
| false | 0.8947 |
| false | 0.8569 |
| true | 1.946 |
| false | 0.9343 |
| false | 1.471 |
| false | 1.346 |
| false | 1.346 |
| true | 2.075 |
| false | 1.064 |
| false | 0.9824 |
| false | 0.7441 |
| false | 1.253 |
| false | 0.8569 |
| false | 1.654 |
| false | 1.411 |
| false | 0.9975 |
| false | 1.365 |
| false | 1.346 |
| false | 1.250 |
| false | 1.689 |
| false | 0.9874 |
| false | 1.152 |
| false | 1.289 |
| false | 1.046 |
| false | 0.8989 |
Most anomalous rows
| Rank | Row | kth-neighbor distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.360 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.881 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 33 | 2.075 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.514 at its median | 13 | 337 | 45 | 16.100 |
| 3 | 28 | 1.946 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.522 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 9 | 1.767 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.241 at its median | 15.400 | 335 | 80 | 31.900 |
| 5 | 5 | 1.696 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.257 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 45 | 1.689 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.654 at its median | 2.200 | 48 | 32 | 11.200 |
| 7 | 39 | 1.654 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 0.324 at its median | 3.400 | 174 | 87 | 8.300 |
| 8 | 24 | 1.643 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.0783 at its median | 16.100 | 259 | 44 | 17.100 |
| 9 | 10 | 1.599 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.479 at its median | 17.400 | 211 | 60 | 25.800 |
| 10 | 8 | 1.567 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.703 at its median | 5.900 | 238 | 72 | 15.800 |
| 11 | 30 | 1.471 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.841 at its median | 7.400 | 159 | 89 | 18.800 |
| 12 | 6 | 1.413 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.355 at its median | 7.900 | 204 | 78 | 38.700 |
| 13 | 40 | 1.411 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.131 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 11 | 1.398 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.386 at its median | 5.300 | 46 | 83 | 20.200 |
| 15 | 42 | 1.365 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Murder: falls 0.283 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 13 | 1.357 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | UrbanPop: falls 0.214 at its median | 10.400 | 249 | 83 | 24 |
| 17 | 43 | 1.346 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.214 at its median | 12.700 | 201 | 80 | 25.500 |
| 18 | 31 | 1.346 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Assault: falls 0.0137 at its median | 11.400 | 285 | 70 | 32.100 |
| 19 | 32 | 1.346 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.262 at its median | 11.100 | 254 | 86 | 26.100 |
| 20 | 18 | 1.329 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.0502 at its median | 15.400 | 249 | 66 | 22.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"))
))
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
| Rank | Row | kth-neighbor distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.360 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.881 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 33 | 2.075 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.514 at its median | 13 | 337 | 45 | 16.100 |
| 3 | 28 | 1.946 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.522 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 9 | 1.767 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.241 at its median | 15.400 | 335 | 80 | 31.900 |
| 5 | 5 | 1.696 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.257 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 45 | 1.689 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.654 at its median | 2.200 | 48 | 32 | 11.200 |
| 7 | 39 | 1.654 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 0.324 at its median | 3.400 | 174 | 87 | 8.300 |
| 8 | 24 | 1.643 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.0783 at its median | 16.100 | 259 | 44 | 17.100 |
| 9 | 10 | 1.599 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.479 at its median | 17.400 | 211 | 60 | 25.800 |
| 10 | 8 | 1.567 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.703 at its median | 5.900 | 238 | 72 | 15.800 |
| 11 | 30 | 1.471 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.841 at its median | 7.400 | 159 | 89 | 18.800 |
| 12 | 6 | 1.413 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.355 at its median | 7.900 | 204 | 78 | 38.700 |
| 13 | 40 | 1.411 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.131 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 11 | 1.398 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.386 at its median | 5.300 | 46 | 83 | 20.200 |
| 15 | 42 | 1.365 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Murder: falls 0.283 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 13 | 1.357 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | UrbanPop: falls 0.214 at its median | 10.400 | 249 | 83 | 24 |
| 17 | 43 | 1.346 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.214 at its median | 12.700 | 201 | 80 | 25.500 |
| 18 | 31 | 1.346 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Assault: falls 0.0137 at its median | 11.400 | 285 | 70 | 32.100 |
| 19 | 32 | 1.346 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.262 at its median | 11.100 | 254 | 86 | 26.100 |
| 20 | 18 | 1.329 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.0502 at its median | 15.400 | 249 | 66 | 22.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.
Angles: ABOD
PredictPredict 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?
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.
Chains: COF
ReadLOF 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'.
0 of 50 rows (0.0%) are flagged as anomalies (COF ≥ 1.5).
- Anomalies
- 0
- Threshold
- 1.500
Plots
View data
| Anomaly | COF |
|---|---|
| false | 0.9685 |
| false | 1.363 |
| false | 1.020 |
| false | 1.245 |
| false | 1.306 |
| false | 1.322 |
| false | 1.318 |
| false | 1.349 |
| false | 1.178 |
| false | 0.9783 |
| false | 1.295 |
| false | 1.240 |
| false | 0.9316 |
| false | 0.9500 |
| false | 0.7932 |
| false | 0.9257 |
| false | 1.193 |
| false | 1.035 |
| false | 0.8803 |
| false | 0.9470 |
| false | 1.080 |
| false | 0.8602 |
| false | 1.028 |
| false | 0.9831 |
| false | 1.264 |
| false | 1.122 |
| false | 0.9597 |
| false | 1.125 |
| false | 0.8411 |
| false | 1.294 |
| false | 0.9736 |
| false | 0.9287 |
| false | 1.123 |
| false | 0.9992 |
| false | 1.048 |
| false | 0.9736 |
| false | 1.140 |
| false | 0.9441 |
| false | 1.153 |
| false | 0.9831 |
| false | 1.069 |
| false | 1.143 |
| false | 1.099 |
| false | 1.130 |
| false | 1.257 |
| false | 1.0000 |
| false | 1.092 |
| false | 1.150 |
| false | 0.9256 |
| false | 1.046 |
Most anomalous rows
| Rank | Row | COF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1.363 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.275 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 1.349 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.307 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 6 | 1.322 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.0499 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 7 | 1.318 | Rape = 11.1 (robust z -1.0); 32% of its tail score | Rape: falls 0.364 at its median | 3.300 | 110 | 77 | 11.100 |
| 5 | 5 | 1.306 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 0.337 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 11 | 1.295 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.465 at its median | 5.300 | 46 | 83 | 20.200 |
| 7 | 30 | 1.294 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.563 at its median | 7.400 | 159 | 89 | 18.800 |
| 8 | 25 | 1.264 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.218 at its median | 9 | 178 | 70 | 28.200 |
| 9 | 45 | 1.257 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.507 at its median | 2.200 | 48 | 32 | 11.200 |
| 10 | 4 | 1.245 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.287 at its median | 8.800 | 190 | 50 | 19.500 |
| 11 | 12 | 1.240 | Murder = 2.6 (robust z -0.9); 34% of its tail score | Murder: falls 0.367 at its median | 2.600 | 120 | 54 | 14.200 |
| 12 | 17 | 1.193 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.341 at its median | 9.700 | 109 | 52 | 16.300 |
| 13 | 9 | 1.178 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.24 at its median | 15.400 | 335 | 80 | 31.900 |
| 14 | 39 | 1.153 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.208 at its median | 3.400 | 174 | 87 | 8.300 |
| 15 | 48 | 1.150 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | no single feature lowers it | 5.700 | 81 | 39 | 9.300 |
| 16 | 42 | 1.143 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Rape: falls 0.132 at its median | 13.200 | 188 | 59 | 26.900 |
| 17 | 37 | 1.140 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.237 at its median | 4.900 | 159 | 67 | 29.300 |
| 18 | 44 | 1.130 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 0.14 at its median | 3.200 | 120 | 80 | 22.900 |
| 19 | 28 | 1.125 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.215 at its median | 12.200 | 252 | 81 | 46 |
| 20 | 33 | 1.123 | Assault = 337 (robust z +1.6); 43% of its tail score | Rape: falls 0.0858 at its median | 13 | 337 | 45 | 16.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"))
))
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
| Rank | Row | COF | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 1.363 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.275 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 1.349 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.307 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 6 | 1.322 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.0499 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 7 | 1.318 | Rape = 11.1 (robust z -1.0); 32% of its tail score | Rape: falls 0.364 at its median | 3.300 | 110 | 77 | 11.100 |
| 5 | 5 | 1.306 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 0.337 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 11 | 1.295 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.465 at its median | 5.300 | 46 | 83 | 20.200 |
| 7 | 30 | 1.294 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.563 at its median | 7.400 | 159 | 89 | 18.800 |
| 8 | 25 | 1.264 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 0.218 at its median | 9 | 178 | 70 | 28.200 |
| 9 | 45 | 1.257 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.507 at its median | 2.200 | 48 | 32 | 11.200 |
| 10 | 4 | 1.245 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.287 at its median | 8.800 | 190 | 50 | 19.500 |
| 11 | 12 | 1.240 | Murder = 2.6 (robust z -0.9); 34% of its tail score | Murder: falls 0.367 at its median | 2.600 | 120 | 54 | 14.200 |
| 12 | 17 | 1.193 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Murder: falls 0.341 at its median | 9.700 | 109 | 52 | 16.300 |
| 13 | 9 | 1.178 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.24 at its median | 15.400 | 335 | 80 | 31.900 |
| 14 | 39 | 1.153 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.208 at its median | 3.400 | 174 | 87 | 8.300 |
| 15 | 48 | 1.150 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | no single feature lowers it | 5.700 | 81 | 39 | 9.300 |
| 16 | 42 | 1.143 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Rape: falls 0.132 at its median | 13.200 | 188 | 59 | 26.900 |
| 17 | 37 | 1.140 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.237 at its median | 4.900 | 159 | 67 | 29.300 |
| 18 | 44 | 1.130 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 0.14 at its median | 3.200 | 120 | 80 | 22.900 |
| 19 | 28 | 1.125 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.215 at its median | 12.200 | 252 | 81 | 46 |
| 20 | 33 | 1.123 | Assault = 337 (robust z +1.6); 43% of its tail score | Rape: falls 0.0858 at its median | 13 | 337 | 45 | 16.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.
Selection: SOS
ReadSOS 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.
Every radius: LOCI
ReadLOCI 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".
4 of 50 rows (8.0%) are flagged as anomalies (LOCI (largest MDEF / σ) ≥ 3).
- Anomalies
- 4
- Threshold
- 3
Plots
View data
| Anomaly | LOCI (largest MDEF / σ) |
|---|---|
| false | 0.1268 |
| false | 2.445 |
| false | 0.8848 |
| false | −0.4023 |
| false | 2.767 |
| false | 0.9984 |
| false | 0.3149 |
| false | −0.7388 |
| true | 4.899 |
| false | 1.369 |
| false | 0.8193 |
| false | 0.4478 |
| false | −0.0792 |
| false | −0.9882 |
| false | 1.355 |
| false | −0.7858 |
| false | −0.1758 |
| false | 0.7217 |
| false | 1.815 |
| false | 0.3470 |
| false | −0.0107 |
| false | 0.6715 |
| false | 0.4014 |
| false | 2.035 |
| false | −0.9442 |
| false | −0.2575 |
| false | −0.2101 |
| true | 4.364 |
| false | 1.777 |
| false | 0.2249 |
| false | 0.3620 |
| false | 0.4622 |
| false | 2.259 |
| true | 3.748 |
| false | −0.8787 |
| false | −1.135 |
| false | −0.8105 |
| false | −0.4773 |
| false | 2.051 |
| false | 1.518 |
| false | 0.9018 |
| false | −0.1365 |
| false | −0.0544 |
| false | −0.1647 |
| true | 4.899 |
| false | −1.367 |
| false | −0.6486 |
| false | 1.955 |
| false | 1.006 |
| false | −0.9127 |
Most anomalous rows
| Rank | Row | LOCI (largest MDEF / σ) | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 9 | 4.899 | Assault = 335 (robust z +1.6); 35% of its tail score | Assault: falls 3.67 at its median | 15.400 | 335 | 80 | 31.900 |
| 2 | 45 | 4.899 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 3.69 at its median | 2.200 | 48 | 32 | 11.200 |
| 3 | 28 | 4.364 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 3.97 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 34 | 3.748 | Rape = 7.3 (robust z -1.5); 27% of its tail score | Assault: falls 1.59 at its median | 0.8000 | 45 | 44 | 7.300 |
| 5 | 5 | 2.767 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 1.47 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 2 | 2.445 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 1.77 at its median | 10 | 263 | 48 | 44.500 |
| 7 | 33 | 2.259 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 1.26 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 39 | 2.051 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 2.06 at its median | 3.400 | 174 | 87 | 8.300 |
| 9 | 24 | 2.035 | Murder = 16.1 (robust z +1.6); 39% of its tail score | UrbanPop: falls 0.887 at its median | 16.100 | 259 | 44 | 17.100 |
| 10 | 48 | 1.955 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | UrbanPop: falls 1.58 at its median | 5.700 | 81 | 39 | 9.300 |
| 11 | 19 | 1.815 | Rape = 7.8 (robust z -1.4); 34% of its tail score | Murder: falls 1.24 at its median | 2.100 | 83 | 51 | 7.800 |
| 12 | 29 | 1.777 | Rape = 9.5 (robust z -1.2); 27% of its tail score | Murder: falls 1.24 at its median | 2.100 | 57 | 56 | 9.500 |
| 13 | 40 | 1.518 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.791 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 10 | 1.369 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 2.45 at its median | 17.400 | 211 | 60 | 25.800 |
| 15 | 15 | 1.355 | Rape = 11.3 (robust z -1.0); 23% of its tail score | Murder: falls 1.06 at its median | 2.200 | 56 | 57 | 11.300 |
| 16 | 49 | 1.006 | Rape = 10.8 (robust z -1.1); 29% of its tail score | Assault: falls 1.04 at its median | 2.600 | 53 | 66 | 10.800 |
| 17 | 6 | 0.9984 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 1.87 at its median | 7.900 | 204 | 78 | 38.700 |
| 18 | 41 | 0.9018 | UrbanPop = 45 (robust z -1.2); 31% of its tail score | UrbanPop: falls 0.687 at its median | 3.800 | 86 | 45 | 12.800 |
| 19 | 3 | 0.8848 | Rape = 31 (robust z +1.3); 28% of its tail score | Assault: falls 1.25 at its median | 8.100 | 294 | 80 | 31 |
| 20 | 11 | 0.8193 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.04 at its median | 5.300 | 46 | 83 | 20.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"))
))
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
| Rank | Row | LOCI (largest MDEF / σ) | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 9 | 4.899 | Assault = 335 (robust z +1.6); 35% of its tail score | Assault: falls 3.67 at its median | 15.400 | 335 | 80 | 31.900 |
| 2 | 45 | 4.899 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 3.69 at its median | 2.200 | 48 | 32 | 11.200 |
| 3 | 28 | 4.364 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 3.97 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 34 | 3.748 | Rape = 7.3 (robust z -1.5); 27% of its tail score | Assault: falls 1.59 at its median | 0.8000 | 45 | 44 | 7.300 |
| 5 | 5 | 2.767 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 1.47 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 2 | 2.445 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 1.77 at its median | 10 | 263 | 48 | 44.500 |
| 7 | 33 | 2.259 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 1.26 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 39 | 2.051 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 2.06 at its median | 3.400 | 174 | 87 | 8.300 |
| 9 | 24 | 2.035 | Murder = 16.1 (robust z +1.6); 39% of its tail score | UrbanPop: falls 0.887 at its median | 16.100 | 259 | 44 | 17.100 |
| 10 | 48 | 1.955 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | UrbanPop: falls 1.58 at its median | 5.700 | 81 | 39 | 9.300 |
| 11 | 19 | 1.815 | Rape = 7.8 (robust z -1.4); 34% of its tail score | Murder: falls 1.24 at its median | 2.100 | 83 | 51 | 7.800 |
| 12 | 29 | 1.777 | Rape = 9.5 (robust z -1.2); 27% of its tail score | Murder: falls 1.24 at its median | 2.100 | 57 | 56 | 9.500 |
| 13 | 40 | 1.518 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.791 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 10 | 1.369 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 2.45 at its median | 17.400 | 211 | 60 | 25.800 |
| 15 | 15 | 1.355 | Rape = 11.3 (robust z -1.0); 23% of its tail score | Murder: falls 1.06 at its median | 2.200 | 56 | 57 | 11.300 |
| 16 | 49 | 1.006 | Rape = 10.8 (robust z -1.1); 29% of its tail score | Assault: falls 1.04 at its median | 2.600 | 53 | 66 | 10.800 |
| 17 | 6 | 0.9984 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 1.87 at its median | 7.900 | 204 | 78 | 38.700 |
| 18 | 41 | 0.9018 | UrbanPop = 45 (robust z -1.2); 31% of its tail score | UrbanPop: falls 0.687 at its median | 3.800 | 86 | 45 | 12.800 |
| 19 | 3 | 0.8848 | Rape = 31 (robust z +1.3); 28% of its tail score | Assault: falls 1.25 at its median | 8.100 | 294 | 80 | 31 |
| 20 | 11 | 0.8193 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.04 at its median | 5.300 | 46 | 83 | 20.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.
LoOP: LOF on a 0–1 scale
In the appLocal 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.
5 of 50 rows (10.0%) are flagged as anomalies (LoOP ≥ 0.371).
- Anomalies
- 5
- Threshold
- 0.3707
Plots
View data
| Anomaly | LoOP |
|---|---|
| false | 0 |
| true | 0.7783 |
| false | 0.0539 |
| false | 0.2647 |
| false | 0.1538 |
| false | 0.0609 |
| false | 0.0542 |
| true | 0.7356 |
| true | 0.3707 |
| false | 0.0806 |
| false | 0.3651 |
| false | 0.0968 |
| false | 0 |
| false | 0 |
| false | 0 |
| false | 0 |
| false | 0.2797 |
| false | 0 |
| false | 0 |
| false | 0.0448 |
| false | 0 |
| false | 0 |
| false | 0.1303 |
| false | 0.0955 |
| false | 0.2516 |
| false | 0 |
| false | 0 |
| false | 0.2783 |
| false | 0 |
| false | 0.3557 |
| false | 0 |
| false | 0 |
| true | 0.4230 |
| false | 0.1373 |
| false | 0.1274 |
| false | 0 |
| false | 0.3005 |
| false | 0.1757 |
| false | 0.2922 |
| false | 0 |
| false | 0.0043 |
| false | 0.0968 |
| false | 0.0375 |
| false | 0.1208 |
| true | 0.4470 |
| false | 0.1177 |
| false | 0.1003 |
| false | 0.2144 |
| false | 0.0393 |
| false | 0.1572 |
Most anomalous rows
| Rank | Row | LoOP | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 0.7783 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.778 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 0.7356 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.69 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 45 | 0.4470 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.447 at its median | 2.200 | 48 | 32 | 11.200 |
| 4 | 33 | 0.4230 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.246 at its median | 13 | 337 | 45 | 16.100 |
| 5 | 9 | 0.3707 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.229 at its median | 15.400 | 335 | 80 | 31.900 |
| 6 | 11 | 0.3651 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.365 at its median | 5.300 | 46 | 83 | 20.200 |
| 7 | 30 | 0.3557 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.356 at its median | 7.400 | 159 | 89 | 18.800 |
| 8 | 37 | 0.3005 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.287 at its median | 4.900 | 159 | 67 | 29.300 |
| 9 | 39 | 0.2922 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.224 at its median | 3.400 | 174 | 87 | 8.300 |
| 10 | 17 | 0.2797 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Assault: falls 0.0989 at its median | 9.700 | 109 | 52 | 16.300 |
| 11 | 28 | 0.2783 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.278 at its median | 12.200 | 252 | 81 | 46 |
| 12 | 4 | 0.2647 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.197 at its median | 8.800 | 190 | 50 | 19.500 |
| 13 | 25 | 0.2516 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Murder: falls 0.117 at its median | 9 | 178 | 70 | 28.200 |
| 14 | 48 | 0.2144 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | no single feature lowers it | 5.700 | 81 | 39 | 9.300 |
| 15 | 38 | 0.1757 | Rape = 14.9 (robust z -0.6); 30% of its tail score | Assault: falls 0.176 at its median | 6.300 | 106 | 72 | 14.900 |
| 16 | 50 | 0.1572 | Rape = 15.6 (robust z -0.5); 34% of its tail score | Rape: falls 0.142 at its median | 6.800 | 161 | 60 | 15.600 |
| 17 | 5 | 0.1538 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.154 at its median | 9 | 276 | 91 | 40.600 |
| 18 | 34 | 0.1373 | Rape = 7.3 (robust z -1.5); 27% of its tail score | no single feature lowers it | 0.8000 | 45 | 44 | 7.300 |
| 19 | 23 | 0.1303 | Murder = 2.7 (robust z -0.8); 32% of its tail score | no single feature lowers it | 2.700 | 72 | 66 | 14.900 |
| 20 | 35 | 0.1274 | UrbanPop = 75 (robust z +0.5); 33% of its tail score | UrbanPop: falls 0.127 at its median | 7.300 | 120 | 75 | 21.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"))
))
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
| Rank | Row | LoOP | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 0.7783 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.778 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 8 | 0.7356 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.69 at its median | 5.900 | 238 | 72 | 15.800 |
| 3 | 45 | 0.4470 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.447 at its median | 2.200 | 48 | 32 | 11.200 |
| 4 | 33 | 0.4230 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.246 at its median | 13 | 337 | 45 | 16.100 |
| 5 | 9 | 0.3707 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.229 at its median | 15.400 | 335 | 80 | 31.900 |
| 6 | 11 | 0.3651 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.365 at its median | 5.300 | 46 | 83 | 20.200 |
| 7 | 30 | 0.3557 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.356 at its median | 7.400 | 159 | 89 | 18.800 |
| 8 | 37 | 0.3005 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 0.287 at its median | 4.900 | 159 | 67 | 29.300 |
| 9 | 39 | 0.2922 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 0.224 at its median | 3.400 | 174 | 87 | 8.300 |
| 10 | 17 | 0.2797 | UrbanPop = 52 (robust z -0.8); 31% of its tail score | Assault: falls 0.0989 at its median | 9.700 | 109 | 52 | 16.300 |
| 11 | 28 | 0.2783 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.278 at its median | 12.200 | 252 | 81 | 46 |
| 12 | 4 | 0.2647 | UrbanPop = 50 (robust z -0.9); 40% of its tail score | UrbanPop: falls 0.197 at its median | 8.800 | 190 | 50 | 19.500 |
| 13 | 25 | 0.2516 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Murder: falls 0.117 at its median | 9 | 178 | 70 | 28.200 |
| 14 | 48 | 0.2144 | UrbanPop = 39 (robust z -1.5); 37% of its tail score | no single feature lowers it | 5.700 | 81 | 39 | 9.300 |
| 15 | 38 | 0.1757 | Rape = 14.9 (robust z -0.6); 30% of its tail score | Assault: falls 0.176 at its median | 6.300 | 106 | 72 | 14.900 |
| 16 | 50 | 0.1572 | Rape = 15.6 (robust z -0.5); 34% of its tail score | Rape: falls 0.142 at its median | 6.800 | 161 | 60 | 15.600 |
| 17 | 5 | 0.1538 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.154 at its median | 9 | 276 | 91 | 40.600 |
| 18 | 34 | 0.1373 | Rape = 7.3 (robust z -1.5); 27% of its tail score | no single feature lowers it | 0.8000 | 45 | 44 | 7.300 |
| 19 | 23 | 0.1303 | Murder = 2.7 (robust z -0.8); 32% of its tail score | no single feature lowers it | 2.700 | 72 | 66 | 14.900 |
| 20 | 35 | 0.1274 | UrbanPop = 75 (robust z +0.5); 33% of its tail score | UrbanPop: falls 0.127 at its median | 7.300 | 120 | 75 | 21.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.
Check your understanding
CheckpointCheck 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.
Do it on your own data
In the appIn Spot anomalies, pick Nearest-neighbor outlier scores and try two scores on the same features. Rows both scores flag deserve a look first.
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])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)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