Angles, chains, clusters, selection and scale: five more anomaly scores
ABOD looks at the spread of angles, COF at chains of neighbors, CBLOF at small clusters, SOS at who would pick a row as a neighbor, and LOCI at counts across radii. What each one sees that plain distance misses, and its blind spot.
What runs in CodeSplash
- UCL052Angle-Based Outlier Detection (ABOD) Runs in CodeSplash
- UCL053Connectivity-Based Outlier Factor (COF) Runs in CodeSplash
- UCL054Cluster-Based Local Outlier Factor (CBLOF) Runs in CodeSplash
- UCL062Stochastic Outlier Selection (SOS) Runs in CodeSplash
- UCL065Local Correlation Integral (LOCI) Runs in CodeSplash
- Nearest-neighbor outlier scores Verified in Python and R
- Cluster-based local outlier factor (CBLOF) Verified in Python and R
You will be able to
- Explain why an outlier sees the other rows within a narrow range of angles
- Say when chaining distance (COF) beats density ratios (LOF)
- Name CBLOF's hidden assumption about small clusters
- Read SOS and LOCI scores without treating them as tested probabilities
Beyond "far from the neighbors"
ReadDistance and density scores ask how far a row is from its neighbors. The five scores here look at the shape of the neighborhood instead:
| Score | Looks at |
|---|---|
| ABODAngle-based outlier detection (ABOD)Variance of the weighted angles from a row to pairs of its neighbors; a small variance means the row sits outside. | the spread of angles from the row to pairs of others |
| COFConnectivity-based outlier factor (COF)A row's average chaining distance along the nearest path through its neighbors, relative to theirs; well above 1 is weakly connected. | how well the row chains to its neighbors |
| CBLOFCluster-based local outlier factor (CBLOF)k-means clusters split into large (normal) and small ones; each row scores its distance to its own large center or the nearest one. | which cluster the row is in, and how big it is |
| SOSStochastic outlier selection (SOS)Probability that no other row picks this one as a neighbor, with each row's bandwidth set to a target perplexity. | how likely other rows are to pick it as a neighbor |
| LOCILocal correlation integral (LOCI)Compares a row's neighbor count in a small radius with its neighbors' counts, at every radius; flags a drop beyond 3 standard deviations. | neighbor counts compared across many radii |
Each catches a case plain distance misses, and each brings its own blind spot.
ABOD: a narrow view of the crowd
ReadStand inside a cloud and the other points surround you: angles to pairs of them vary widely. Stand outside it and they all lie in one direction: the angles barely vary. ABOD scores a row by the variance of weighted angle terms
Low variance means outlying. FastABOD uses only the neighbors. The weights are part of the definition, scaling changes angles, and libraries differ in sign: in the app, higher still means more anomalous.
3 of 344 rows (0.9%) are flagged as anomalies (ABOD score (−angle variance) ≥ -0.0704).
- Anomalies
- 3
- Threshold
- −0.0704
Plots
View data
| Anomaly | ABOD score (−angle variance) |
|---|---|
| false | −9.682 |
| false | −8.354 |
| false | −4.767 |
| false | −1.581 |
| false | −3.606 |
| false | −2.609 |
| false | −6.905 |
| false | −0.8142 |
| false | −5.126 |
| false | −1.606 |
| false | −12.130 |
| false | −4.729 |
| false | −2.037 |
| false | −1.911 |
| true | −0.0314 |
| false | −4.830 |
| false | −3.373 |
| false | −2.159 |
| false | −1.757 |
| false | −0.1787 |
| false | −2.449 |
| false | −5.143 |
| false | −31.475 |
| false | −2.296 |
| false | −3.567 |
| false | −9.316 |
| false | −14.423 |
| false | −12.044 |
| false | −0.3743 |
| false | −1.780 |
| false | −2.740 |
| false | −1.122 |
| false | −36.189 |
| false | −7.948 |
| false | −4.158 |
| false | −1.310 |
| false | −14.368 |
| false | −3.375 |
| false | −1.916 |
| false | −0.7105 |
| false | −3.024 |
| false | −11.082 |
| false | −2.512 |
| false | −2.589 |
| false | −12.434 |
| false | −3.579 |
| false | −4.606 |
| false | −0.7513 |
| false | −19.297 |
| false | −1.321 |
| false | −27.348 |
| false | −7.502 |
| false | −18.102 |
| false | −4.464 |
| false | −0.6889 |
| false | −8.996 |
| false | −28.873 |
| false | −9.682 |
| false | −2.454 |
| false | −4.248 |
First 60 of 344 rows.
Most anomalous rows
| Rank | Row | ABOD score (−angle variance) | Most unusual | Biggest score drop | bill_len | bill_dep | flipper_len | body_mass |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | −0.0009 | bill_len = 58 (robust z +1.9); 52% of its tail score | bill_len: falls 1.45 at its median | 58 | 17.800 | 181 | 3,700 |
| 2 | 186 | −0.0243 | body_mass = 6050 (robust z +2.2); 33% of its tail score | no single feature lowers it | 59.600 | 17 | 230 | 6,050 |
| 3 | 15 | −0.0314 | bill_dep = 21.1 (robust z +1.7); 43% of its tail score | bill_len: falls 1.27 at its median | 34.600 | 21.100 | 198 | 4,400 |
| 4 | 315 | −0.0830 | body_mass = 2700 (robust z -1.5); 65% of its tail score | body_mass: falls 0.492 at its median | 46.900 | 16.600 | 192 | 2,700 |
| 5 | 283 | −0.0924 | flipper_len = 178 (robust z -1.2); 47% of its tail score | flipper_len: falls 4.74 at its median | 46.100 | 18.200 | 178 | 3,250 |
| 6 | 190 | −0.1072 | flipper_len = 219 (robust z +1.3); 37% of its tail score | flipper_len: falls 0.0446 at its median | 44.400 | 17.300 | 219 | 5,250 |
| 7 | 232 | −0.1126 | body_mass = 5950 (robust z +2.1); 48% of its tail score | bill_len: falls 0.0141 at its median | 45.200 | 16.400 | 223 | 5,950 |
| 8 | 340 | −0.1163 | bill_len = 55.8 (robust z +1.6); 52% of its tail score | bill_len: falls 0.491 at its median | 55.800 | 19.800 | 207 | 4,000 |
| 9 | 143 | −0.1289 | bill_len = 32.1 (robust z -1.8); 49% of its tail score | bill_dep: falls 0.197 at its median | 32.100 | 15.500 | 188 | 3,050 |
| 10 | 314 | −0.1523 | bill_dep = 20.7 (robust z +1.5); 39% of its tail score | bill_dep: falls 0.191 at its median | 52 | 20.700 | 210 | 4,800 |
| 11 | 99 | −0.1756 | bill_len = 33.1 (robust z -1.6); 37% of its tail score | no single feature lowers it | 33.100 | 16.100 | 178 | 2,900 |
| 12 | 20 | −0.1787 | bill_dep = 21.5 (robust z +1.9); 69% of its tail score | bill_dep: falls 1.35 at its median | 46 | 21.500 | 194 | 4,200 |
| 13 | 130 | −0.1855 | flipper_len = 210 (robust z +0.8); 32% of its tail score | flipper_len: falls 20.4 at its median | 44.100 | 18 | 210 | 4,000 |
| 14 | 293 | −0.2185 | bill_dep = 20 (robust z +1.2); 36% of its tail score | body_mass: falls 4.73 at its median | 50.300 | 20 | 197 | 3,300 |
| 15 | 325 | −0.2214 | bill_len = 51.5 (robust z +1.0); 34% of its tail score | bill_len: falls 1.91 at its median | 51.500 | 18.700 | 187 | 3,250 |
| 16 | 327 | −0.2401 | body_mass = 3325 (robust z -0.8); 40% of its tail score | bill_dep: falls 0.98 at its median | 48.100 | 16.400 | 199 | 3,325 |
| 17 | 308 | −0.2853 | bill_dep = 20.8 (robust z +1.6); 41% of its tail score | bill_len: falls 0.178 at its median | 54.200 | 20.800 | 201 | 4,300 |
| 18 | 170 | −0.2877 | body_mass = 6300 (robust z +2.5); 52% of its tail score | no single feature lowers it | 49.200 | 15.200 | 221 | 6,300 |
| 19 | 324 | −0.2889 | bill_dep = 19.6 (robust z +1.0); 39% of its tail score | body_mass: falls 1.41 at its median | 49 | 19.600 | 212 | 4,300 |
| 20 | 82 | −0.3298 | body_mass = 4700 (robust z +0.7); 35% of its tail score | body_mass: falls 15.6 at its median | 42.900 | 17.600 | 196 | 4,700 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 2907abc917de7413
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = c("bill_len", "bill_dep", "flipper_len", "body_mass"))), c("bill_len", "bill_dep", "flipper_len", "body_mass"))
FEATURES <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
body_mass = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
# %% Scores (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA) # null when the score doesn't use it
if (n < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "Angle-based scores", min = 3, n = n)
k <- min(8, n - 1L)
extra_values$neighbors <- k
# FastABOD: variance of (a - x).(b - x) / (|a - x|^2 |b - x|^2) over neighbor pairs; score = -variance
.parts <- cs_ml_abod_parts(X, k)
scores <- cs_ml_abod_scores(.parts)
SCORE_LABEL <- "ABOD score (−angle variance)"
rescore <- function(Q, where0, col0) cs_ml_abod_query(X, k, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "abod")
# %% Flag anomalies
RULE <- "cutoff"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.knn_outlier/penguins_abod_cutoff/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("bill_len", "bill_dep", "flipper_len", "body_mass")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Nearest-neighbor outlier scores",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
3 of 344 rows (0.9%) are flagged as anomalies (ABOD score (−angle variance) ≥ -0.0704).
- Anomalies
- 3
- Threshold
- −0.0704
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | ABOD score (−angle variance) | Most unusual | Biggest score drop | bill_len | bill_dep | flipper_len | body_mass |
|---|---|---|---|---|---|---|---|---|
| 1 | 294 | −0.0009 | bill_len = 58 (robust z +1.9); 52% of its tail score | bill_len: falls 1.45 at its median | 58 | 17.800 | 181 | 3,700 |
| 2 | 186 | −0.0243 | body_mass = 6050 (robust z +2.2); 33% of its tail score | no single feature lowers it | 59.600 | 17 | 230 | 6,050 |
| 3 | 15 | −0.0314 | bill_dep = 21.1 (robust z +1.7); 43% of its tail score | bill_len: falls 1.27 at its median | 34.600 | 21.100 | 198 | 4,400 |
| 4 | 315 | −0.0830 | body_mass = 2700 (robust z -1.5); 65% of its tail score | body_mass: falls 0.492 at its median | 46.900 | 16.600 | 192 | 2,700 |
| 5 | 283 | −0.0924 | flipper_len = 178 (robust z -1.2); 47% of its tail score | flipper_len: falls 4.74 at its median | 46.100 | 18.200 | 178 | 3,250 |
| 6 | 190 | −0.1072 | flipper_len = 219 (robust z +1.3); 37% of its tail score | flipper_len: falls 0.0446 at its median | 44.400 | 17.300 | 219 | 5,250 |
| 7 | 232 | −0.1126 | body_mass = 5950 (robust z +2.1); 48% of its tail score | bill_len: falls 0.0141 at its median | 45.200 | 16.400 | 223 | 5,950 |
| 8 | 340 | −0.1163 | bill_len = 55.8 (robust z +1.6); 52% of its tail score | bill_len: falls 0.491 at its median | 55.800 | 19.800 | 207 | 4,000 |
| 9 | 143 | −0.1289 | bill_len = 32.1 (robust z -1.8); 49% of its tail score | bill_dep: falls 0.197 at its median | 32.100 | 15.500 | 188 | 3,050 |
| 10 | 314 | −0.1523 | bill_dep = 20.7 (robust z +1.5); 39% of its tail score | bill_dep: falls 0.191 at its median | 52 | 20.700 | 210 | 4,800 |
| 11 | 99 | −0.1756 | bill_len = 33.1 (robust z -1.6); 37% of its tail score | no single feature lowers it | 33.100 | 16.100 | 178 | 2,900 |
| 12 | 20 | −0.1787 | bill_dep = 21.5 (robust z +1.9); 69% of its tail score | bill_dep: falls 1.35 at its median | 46 | 21.500 | 194 | 4,200 |
| 13 | 130 | −0.1855 | flipper_len = 210 (robust z +0.8); 32% of its tail score | flipper_len: falls 20.4 at its median | 44.100 | 18 | 210 | 4,000 |
| 14 | 293 | −0.2185 | bill_dep = 20 (robust z +1.2); 36% of its tail score | body_mass: falls 4.73 at its median | 50.300 | 20 | 197 | 3,300 |
| 15 | 325 | −0.2214 | bill_len = 51.5 (robust z +1.0); 34% of its tail score | bill_len: falls 1.91 at its median | 51.500 | 18.700 | 187 | 3,250 |
| 16 | 327 | −0.2401 | body_mass = 3325 (robust z -0.8); 40% of its tail score | bill_dep: falls 0.98 at its median | 48.100 | 16.400 | 199 | 3,325 |
| 17 | 308 | −0.2853 | bill_dep = 20.8 (robust z +1.6); 41% of its tail score | bill_len: falls 0.178 at its median | 54.200 | 20.800 | 201 | 4,300 |
| 18 | 170 | −0.2877 | body_mass = 6300 (robust z +2.5); 52% of its tail score | no single feature lowers it | 49.200 | 15.200 | 221 | 6,300 |
| 19 | 324 | −0.2889 | bill_dep = 19.6 (robust z +1.0); 39% of its tail score | body_mass: falls 1.41 at its median | 49 | 19.600 | 212 | 4,300 |
| 20 | 82 | −0.3298 | body_mass = 4700 (robust z +0.7); 35% of its tail score | body_mass: falls 15.6 at its median | 42.900 | 17.600 | 196 | 4,700 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 2907abc917de7413
# Dataset: ml_penguins (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=["bill_len", "bill_dep", "flipper_len", "body_mass"]), ["bill_len", "bill_dep", "flipper_len", "body_mass"])
FEATURES = ["bill_len", "bill_dep", "flipper_len", "body_mass"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"body_mass": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
# %% Scores (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None} # null when the score doesn't use it
if n < 3:
cs_error("CS_E_TOO_FEW_ROWS", what="Angle-based scores", min=3, n=n)
k = min(8, n - 1)
extra_values["neighbors"] = k
# FastABOD: variance of (a - x)·(b - x) / (|a - x|² |b - x|²) over neighbor pairs; score = -variance
_parts = csax.abod_parts(X, k)
scores = csax.abod_scores(_parts)
SCORE_LABEL = "ABOD score (−angle variance)"
rescore = lambda Q, where, col: csax.abod_query(X, k, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "abod")
# %% Flag anomalies
RULE = "cutoff"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.knn_outlier/penguins_abod_cutoff/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["bill_len", "bill_dep", "flipper_len", "body_mass", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Nearest-neighbor outlier scores",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
COF: when the normal data are a line
ReadLOF compares densities in round neighborhoods. If normal rows lie along a thin curve, a row slightly off the curve can have a normal-looking density. COF builds a chain from each row through its nearest neighbors and averages the link lengths along it (the chaining distance). compares that with its neighbors' chaining distances: above 1 means weaker connection.
The chain is the method. Replace it with a plain mean neighbor distance and you've built a different detector. Noise points that bridge two groups can reroute chains.
CBLOF: small clusters as suspects
ReadCBLOF first clusters the rows, splits clusters into large and small, and scores each row by distance: to its own center if its cluster is large, to the nearest large center if it's small. The weighted version multiplies by cluster size.
27 of 532 rows (5.1%) are flagged as anomalies (CBLOF ≥ 2.12).
- Anomalies
- 27
- Threshold
- 2.122
Plots
View data
| Anomaly | CBLOF |
|---|---|
| false | 1.052 |
| false | 1.623 |
| false | 1.342 |
| true | 2.184 |
| false | 0.2784 |
| false | 0.8656 |
| false | 1.039 |
| true | 2.122 |
| false | 0.9245 |
| false | 1.645 |
| true | 2.382 |
| false | 1.019 |
| false | 1.766 |
| false | 1.340 |
| false | 0.9519 |
| false | 1.161 |
| false | 0.4317 |
| false | 0.9100 |
| false | 1.403 |
| false | 1.403 |
| false | 1.198 |
| false | 0.7893 |
| false | 1.333 |
| false | 0.8556 |
| false | 0.7801 |
| false | 1.386 |
| false | 0.3454 |
| false | 1.296 |
| false | 0.9592 |
| false | 0.4228 |
| false | 1.337 |
| false | 1.053 |
| false | 0.9260 |
| false | 0.8523 |
| false | 0.6392 |
| false | 1.534 |
| false | 1.257 |
| false | 1.543 |
| false | 0.7702 |
| false | 0.5867 |
| false | 1.168 |
| false | 0.7996 |
| false | 1.130 |
| false | 1.212 |
| false | 0.8299 |
| false | 0.9515 |
| false | 0.8024 |
| false | 1.043 |
| false | 0.6946 |
| false | 1.940 |
| false | 0.6907 |
| false | 1.189 |
| false | 1.012 |
| false | 0.5513 |
| false | 0.8019 |
| false | 1.254 |
| false | 0.7621 |
| false | 1.783 |
| false | 1.520 |
| false | 1.513 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | glu | bp | bmi | age |
|---|---|---|---|---|---|---|---|---|
| 1 | 279 | 4.942 | bmi = 67.1 (robust z +5.2); 47% of its tail score | bmi: falls 2.59 at its median | 129 | 110 | 67.100 | 26 |
| 2 | 398 | 3.855 | bmi = 59.4 (robust z +4.0); 54% of its tail score | bmi: falls 2.81 at its median | 180 | 78 | 59.400 | 25 |
| 3 | 257 | 3.790 | bp = 30 (robust z -3.5); 40% of its tail score | bmi: falls 1.17 at its median | 88 | 30 | 55 | 26 |
| 4 | 492 | 3.661 | bmi = 57.3 (robust z +3.7); 45% of its tail score | bmi: falls 1.67 at its median | 123 | 100 | 57.300 | 22 |
| 5 | 358 | 2.948 | age = 65 (robust z +4.2); 40% of its tail score | bp: falls 0.76 at its median | 103 | 108 | 39.200 | 65 |
| 6 | 208 | 2.940 | bp = 30 (robust z -3.5); 52% of its tail score | bp: falls 1.67 at its median | 103 | 30 | 43.300 | 33 |
| 7 | 255 | 2.937 | bmi = 53.2 (robust z +3.1); 54% of its tail score | bmi: falls 2.08 at its median | 162 | 76 | 53.200 | 25 |
| 8 | 307 | 2.925 | bmi = 52.3 (robust z +3.0); 42% of its tail score | bmi: falls 0.999 at its median | 165 | 90 | 52.300 | 23 |
| 9 | 462 | 2.914 | bp = 24 (robust z -4.0); 52% of its tail score | bp: falls 1.97 at its median | 89 | 24 | 27.800 | 21 |
| 10 | 491 | 2.753 | bp = 106 (robust z +2.9); 37% of its tail score | bp: falls 1.55 at its median | 68 | 106 | 35.500 | 47 |
| 11 | 403 | 2.671 | age = 81 (robust z +6.0); 62% of its tail score | age: falls 1.59 at its median | 134 | 74 | 25.900 | 81 |
| 12 | 111 | 2.548 | bp = 110 (robust z +3.2); 46% of its tail score | bp: falls 1.31 at its median | 189 | 110 | 28.500 | 37 |
| 13 | 221 | 2.492 | bp = 110 (robust z +3.2); 38% of its tail score | bp: falls 0.433 at its median | 171 | 110 | 45.400 | 54 |
| 14 | 493 | 2.423 | bmi = 49.6 (robust z +2.5); 52% of its tail score | bmi: falls 1.61 at its median | 162 | 76 | 49.600 | 26 |
| 15 | 11 | 2.382 | bp = 40 (robust z -2.7); 49% of its tail score | bp: falls 0.824 at its median | 137 | 40 | 43.100 | 33 |
| 16 | 301 | 2.334 | glu = 179 (robust z +2.2); 28% of its tail score | bp: falls 0.622 at its median | 179 | 90 | 44.100 | 23 |
| 17 | 432 | 2.314 | age = 60 (robust z +3.6); 32% of its tail score | bmi: falls 0.835 at its median | 129 | 90 | 19.600 | 60 |
| 18 | 522 | 2.303 | bmi = 49.3 (robust z +2.5); 41% of its tail score | bmi: falls 0.745 at its median | 147 | 94 | 49.300 | 27 |
| 19 | 140 | 2.277 | bmi = 46.8 (robust z +2.1); 46% of its tail score | bmi: falls 1.17 at its median | 100 | 88 | 46.800 | 31 |
| 20 | 248 | 2.240 | bmi = 49.7 (robust z +2.6); 48% of its tail score | bmi: falls 0.954 at its median | 122 | 90 | 49.700 | 31 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec d723e36b4b661f8a
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("glu", "bp", "bmi", "age"))), c("glu", "bp", "bmi", "age"))
FEATURES <- c("glu", "bp", "bmi", "age")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
glu = "numeric",
bp = "numeric",
bmi = "numeric",
age = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K <- 8
SEED <- 42
if (nrow(df) <= K) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("CBLOF with %d clusters", K), min = K + 1L, n = nrow(df))
.km <- cs_ml_kmeans_fit(X, K, cs_rng(SEED), n_init = 10)
labels <- as.integer(cs_ml_canonical(.km$labels)) # 1..k by size, ties by first row
k_found <- max(labels)
centers <- do.call(rbind, lapply(seq_len(k_found), function(c) .km$centers[.km$labels[which(labels == c)[1]] + 1L, ]))
sizes <- tabulate(labels, nbins = k_found)
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
.split <- cs_ml_cblof_split(labels, 0.9, 5)
n_large <- .split$n_large
if (!.split$split) warnings <- c(warnings, "No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED <- FALSE
scores <- cs_ml_cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL <- "CBLOF"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(clusters = k_found, n_large = n_large, small_rows = sum(labels > n_large))
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth") # median + 3 scaled MADs
rescore <- function(Q, where0, col0) {
lab <- cs_ml_nearest_center(Q, centers) # the fitted clusters, no refit
cs_ml_cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
}
# %% Flag anomalies
RULE <- "share"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.cblof/pima_default/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("glu", "bp", "bmi", "age")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Cluster-based local outlier factor (CBLOF)",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
27 of 532 rows (5.1%) are flagged as anomalies (CBLOF ≥ 2.12).
- Anomalies
- 27
- Threshold
- 2.122
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | CBLOF | Most unusual | Biggest score drop | glu | bp | bmi | age |
|---|---|---|---|---|---|---|---|---|
| 1 | 279 | 4.942 | bmi = 67.1 (robust z +5.2); 47% of its tail score | bmi: falls 2.59 at its median | 129 | 110 | 67.100 | 26 |
| 2 | 398 | 3.855 | bmi = 59.4 (robust z +4.0); 54% of its tail score | bmi: falls 2.81 at its median | 180 | 78 | 59.400 | 25 |
| 3 | 257 | 3.790 | bp = 30 (robust z -3.5); 40% of its tail score | bmi: falls 1.17 at its median | 88 | 30 | 55 | 26 |
| 4 | 492 | 3.661 | bmi = 57.3 (robust z +3.7); 45% of its tail score | bmi: falls 1.67 at its median | 123 | 100 | 57.300 | 22 |
| 5 | 358 | 2.948 | age = 65 (robust z +4.2); 40% of its tail score | bp: falls 0.76 at its median | 103 | 108 | 39.200 | 65 |
| 6 | 208 | 2.940 | bp = 30 (robust z -3.5); 52% of its tail score | bp: falls 1.67 at its median | 103 | 30 | 43.300 | 33 |
| 7 | 255 | 2.937 | bmi = 53.2 (robust z +3.1); 54% of its tail score | bmi: falls 2.08 at its median | 162 | 76 | 53.200 | 25 |
| 8 | 307 | 2.925 | bmi = 52.3 (robust z +3.0); 42% of its tail score | bmi: falls 0.999 at its median | 165 | 90 | 52.300 | 23 |
| 9 | 462 | 2.914 | bp = 24 (robust z -4.0); 52% of its tail score | bp: falls 1.97 at its median | 89 | 24 | 27.800 | 21 |
| 10 | 491 | 2.753 | bp = 106 (robust z +2.9); 37% of its tail score | bp: falls 1.55 at its median | 68 | 106 | 35.500 | 47 |
| 11 | 403 | 2.671 | age = 81 (robust z +6.0); 62% of its tail score | age: falls 1.59 at its median | 134 | 74 | 25.900 | 81 |
| 12 | 111 | 2.548 | bp = 110 (robust z +3.2); 46% of its tail score | bp: falls 1.31 at its median | 189 | 110 | 28.500 | 37 |
| 13 | 221 | 2.492 | bp = 110 (robust z +3.2); 38% of its tail score | bp: falls 0.433 at its median | 171 | 110 | 45.400 | 54 |
| 14 | 493 | 2.423 | bmi = 49.6 (robust z +2.5); 52% of its tail score | bmi: falls 1.61 at its median | 162 | 76 | 49.600 | 26 |
| 15 | 11 | 2.382 | bp = 40 (robust z -2.7); 49% of its tail score | bp: falls 0.824 at its median | 137 | 40 | 43.100 | 33 |
| 16 | 301 | 2.334 | glu = 179 (robust z +2.2); 28% of its tail score | bp: falls 0.622 at its median | 179 | 90 | 44.100 | 23 |
| 17 | 432 | 2.314 | age = 60 (robust z +3.6); 32% of its tail score | bmi: falls 0.835 at its median | 129 | 90 | 19.600 | 60 |
| 18 | 522 | 2.303 | bmi = 49.3 (robust z +2.5); 41% of its tail score | bmi: falls 0.745 at its median | 147 | 94 | 49.300 | 27 |
| 19 | 140 | 2.277 | bmi = 46.8 (robust z +2.1); 46% of its tail score | bmi: falls 1.17 at its median | 100 | 88 | 46.800 | 31 |
| 20 | 248 | 2.240 | bmi = 49.7 (robust z +2.6); 48% of its tail score | bmi: falls 0.954 at its median | 122 | 90 | 49.700 | 31 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Cluster-based local outlier factor (CBLOF)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cblof 1.0.0 · spec d723e36b4b661f8a
# Dataset: ml_pima (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import cluster as csc
from codesplash.ml import embed as csembed
from codesplash.stats.rng import Rng
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["glu", "bp", "bmi", "age"]), ["glu", "bp", "bmi", "age"])
FEATURES = ["glu", "bp", "bmi", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"glu": "numeric",
"bp": "numeric",
"bmi": "numeric",
"age": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
# %% Clusters (shared k-means twin: host k-means++ starts on the shared stream, Lloyd to convergence)
K = 8
SEED = 42
if len(df) <= K:
cs_error("CS_E_TOO_FEW_ROWS", what=f"CBLOF with {K} clusters", min=K + 1, n=len(df))
_raw, _centers, _ = csc.kmeans_fit(X, K, Rng(SEED), n_init=10)
labels = csc.canonical(_raw) # 1..k by size, ties by first row
k_found = int(labels.max())
centers = np.vstack([_centers[int(_raw[np.flatnonzero(labels == c)[0]])] for c in range(1, k_found + 1)])
sizes = np.bincount(labels, minlength=k_found + 1)[1:]
# %% Scores (He et al. 2003; the large/small split as in PyOD's CBLOF)
n_large, _split = csax.cblof_split(labels, 0.9, 5)
if not _split:
warnings.append("No boundary met the α or β rule, so every cluster counts as large (each row is scored by the distance to its own center).")
WEIGHTED = False
scores = csax.cblof_scores(X, labels, centers, sizes, n_large, WEIGHTED)
SCORE_LABEL = "CBLOF"
ENGINE_PACKAGES = ("scikit-learn", "numpy", "pandas")
extra_values = {"clusters": k_found, "n_large": int(n_large), "small_rows": int(np.sum(labels > n_large))}
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth") # median + 3 scaled MADs
def rescore(Q, where, col):
lab = csax.nearest_center(Q, centers) # the fitted clusters, no refit
return csax.cblof_scores(Q, lab, centers, sizes, n_large, WEIGHTED)
# %% Flag anomalies
RULE = "share"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.cblof/pima_default/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["glu", "bp", "bmi", "age", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Cluster-based local outlier factor (CBLOF)",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
Here 34 rows sat in small clusters. That's the hidden assumption: small or remote clusters deserve suspicion. A legitimate minority gets flagged as a group, and a poor first clustering passes its errors straight into the scores.
Same data, a borrowed cutoff
PredictPredict first
On the arrests data, you flag states whose COF is at least 1.50, a cutoff that sounded reasonable. How many get flagged?
Reveal
None. The highest COF was 1.36, so no state reached the cutoff. COF's scale depends on the data and ; flag a share or calibrate on normal rows instead.
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"}],
})
SOS: nobody picks you
ReadSOS borrows t-SNE's affinities. Each row picks neighbors with probabilities , with tuned so every row has the same perplexity (effective number of neighbors). A row's score is the chance that no one picks it: .
8 of 150 rows (5.3%) are flagged as anomalies (SOS outlier probability ≥ 0.787).
- Anomalies
- 8
- Threshold
- 0.7866
Plots
View data
| Anomaly | SOS outlier probability |
|---|---|
| false | 0.1451 |
| false | 0.1872 |
| false | 0.2696 |
| false | 0.3053 |
| false | 0.2473 |
| false | 0.1907 |
| false | 0.6391 |
| false | 0.1132 |
| false | 0.2572 |
| false | 0.2577 |
| false | 0.2620 |
| false | 0.1840 |
| false | 0.3741 |
| false | 0.4495 |
| false | 0.5483 |
| false | 0.7803 |
| false | 0.2239 |
| false | 0.1413 |
| false | 0.5156 |
| false | 0.1492 |
| false | 0.3377 |
| false | 0.3843 |
| true | 0.9277 |
| false | 0.7349 |
| false | 0.4437 |
| false | 0.5007 |
| false | 0.1675 |
| false | 0.2229 |
| false | 0.2249 |
| false | 0.2907 |
| false | 0.1676 |
| false | 0.5071 |
| false | 0.5162 |
| false | 0.2434 |
| false | 0.1425 |
| false | 0.6357 |
| false | 0.6855 |
| false | 0.3322 |
| false | 0.3039 |
| false | 0.0991 |
| false | 0.2330 |
| true | 0.9990 |
| false | 0.6440 |
| true | 0.9044 |
| false | 0.3968 |
| false | 0.4207 |
| false | 0.2597 |
| false | 0.1584 |
| false | 0.2158 |
| false | 0.3687 |
| false | 0.6190 |
| false | 0.3647 |
| false | 0.2863 |
| false | 0.4409 |
| false | 0.2684 |
| false | 0.3437 |
| false | 0.2815 |
| false | 0.2427 |
| false | 0.2245 |
| false | 0.4340 |
First 60 of 150 rows.
Most anomalous rows
| Rank | Row | SOS outlier probability | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 42 | 0.9990 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 0.617 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 107 | 0.9712 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 0.401 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 23 | 0.9277 | petal_length = 1 (robust z -1.8); 44% of its tail score | sepal_width: falls 0.451 at its median | 4.600 | 3.600 | 1 | 0.2000 |
| 4 | 109 | 0.9128 | sepal_width = 2.5 (robust z -1.1); 29% of its tail score | sepal_width: falls 0.46 at its median | 6.700 | 2.500 | 5.800 | 1.800 |
| 5 | 44 | 0.9044 | petal_length = 1.6 (robust z -1.5); 22% of its tail score | no single feature lowers it | 5 | 3.500 | 1.600 | 0.6000 |
| 6 | 61 | 0.8713 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.24 at its median | 5 | 2 | 3.500 | 1 |
| 7 | 115 | 0.8530 | petal_width = 2.4 (robust z +1.1); 51% of its tail score | petal_width: falls 0.156 at its median | 5.800 | 2.800 | 5.100 | 2.400 |
| 8 | 119 | 0.7866 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.397 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 9 | 16 | 0.7803 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | no single feature lowers it | 5.700 | 4.400 | 1.500 | 0.4000 |
| 10 | 24 | 0.7349 | petal_length = 1.7 (robust z -1.4); 24% of its tail score | no single feature lowers it | 5.100 | 3.300 | 1.700 | 0.5000 |
| 11 | 114 | 0.7131 | sepal_width = 2.5 (robust z -1.1); 37% of its tail score | sepal_width: falls 0.226 at its median | 5.700 | 2.500 | 5 | 2 |
| 12 | 63 | 0.6950 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | petal_width: falls 0.252 at its median | 6 | 2.200 | 4 | 1 |
| 13 | 37 | 0.6855 | petal_length = 1.3 (robust z -1.6); 38% of its tail score | no single feature lowers it | 5.500 | 3.500 | 1.300 | 0.2000 |
| 14 | 65 | 0.6707 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 0.492 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 15 | 86 | 0.6686 | sepal_width = 3.4 (robust z +0.9); 35% of its tail score | sepal_width: falls 0.492 at its median | 6 | 3.400 | 4.500 | 1.600 |
| 16 | 77 | 0.6619 | sepal_length = 6.8 (robust z +1.0); 41% of its tail score | sepal_width: falls 0.386 at its median | 6.800 | 2.800 | 4.800 | 1.400 |
| 17 | 43 | 0.6440 | petal_length = 1.3 (robust z -1.6); 30% of its tail score | sepal_width: falls 0.362 at its median | 4.400 | 3.200 | 1.300 | 0.2000 |
| 18 | 7 | 0.6391 | petal_length = 1.4 (robust z -1.6); 25% of its tail score | sepal_width: falls 0.289 at its median | 4.600 | 3.400 | 1.400 | 0.3000 |
| 19 | 36 | 0.6357 | petal_length = 1.2 (robust z -1.7); 47% of its tail score | sepal_width: falls 0.153 at its median | 5 | 3.200 | 1.200 | 0.2000 |
| 20 | 110 | 0.6220 | sepal_length = 7.2 (robust z +1.3); 23% of its tail score | no single feature lowers it | 7.200 | 3.600 | 6.100 | 2.500 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 086edc3021752402
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = c("sepal_length", "sepal_width", "petal_length", "petal_width"))), c("sepal_length", "sepal_width", "petal_length", "petal_width"))
FEATURES <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
sepal_length = "numeric",
sepal_width = "numeric",
petal_length = "numeric",
petal_width = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
# %% Scores (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA) # null when the score doesn't use it
PERPLEXITY <- 6
if (n - 1 <= PERPLEXITY) cs_error("CS_E_TOO_FEW_ROWS", what = sprintf("SOS with perplexity %s", format(PERPLEXITY)), min = as.integer(floor(PERPLEXITY)) + 2L, n = n)
.parts <- cs_ml_sos_parts(X, PERPLEXITY)
scores <- exp(.parts$log_o)
SCORE_LABEL <- "SOS outlier probability"
extra_values$perplexity <- PERPLEXITY
rescore <- function(Q, where0, col0) cs_ml_sos_query(X, .parts, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "sos")
# %% Flag anomalies
RULE <- "share"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.05, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.knn_outlier/iris_sos/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("sepal_length", "sepal_width", "petal_length", "petal_width")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Nearest-neighbor outlier scores",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
8 of 150 rows (5.3%) are flagged as anomalies (SOS outlier probability ≥ 0.787).
- Anomalies
- 8
- Threshold
- 0.7866
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | SOS outlier probability | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 42 | 0.9990 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 0.617 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 107 | 0.9712 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 0.401 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 3 | 23 | 0.9277 | petal_length = 1 (robust z -1.8); 44% of its tail score | sepal_width: falls 0.451 at its median | 4.600 | 3.600 | 1 | 0.2000 |
| 4 | 109 | 0.9128 | sepal_width = 2.5 (robust z -1.1); 29% of its tail score | sepal_width: falls 0.46 at its median | 6.700 | 2.500 | 5.800 | 1.800 |
| 5 | 44 | 0.9044 | petal_length = 1.6 (robust z -1.5); 22% of its tail score | no single feature lowers it | 5 | 3.500 | 1.600 | 0.6000 |
| 6 | 61 | 0.8713 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_length: falls 0.24 at its median | 5 | 2 | 3.500 | 1 |
| 7 | 115 | 0.8530 | petal_width = 2.4 (robust z +1.1); 51% of its tail score | petal_width: falls 0.156 at its median | 5.800 | 2.800 | 5.100 | 2.400 |
| 8 | 119 | 0.7866 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.397 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 9 | 16 | 0.7803 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | no single feature lowers it | 5.700 | 4.400 | 1.500 | 0.4000 |
| 10 | 24 | 0.7349 | petal_length = 1.7 (robust z -1.4); 24% of its tail score | no single feature lowers it | 5.100 | 3.300 | 1.700 | 0.5000 |
| 11 | 114 | 0.7131 | sepal_width = 2.5 (robust z -1.1); 37% of its tail score | sepal_width: falls 0.226 at its median | 5.700 | 2.500 | 5 | 2 |
| 12 | 63 | 0.6950 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | petal_width: falls 0.252 at its median | 6 | 2.200 | 4 | 1 |
| 13 | 37 | 0.6855 | petal_length = 1.3 (robust z -1.6); 38% of its tail score | no single feature lowers it | 5.500 | 3.500 | 1.300 | 0.2000 |
| 14 | 65 | 0.6707 | petal_length = 3.6 (robust z -0.4); 29% of its tail score | petal_length: falls 0.492 at its median | 5.600 | 2.900 | 3.600 | 1.300 |
| 15 | 86 | 0.6686 | sepal_width = 3.4 (robust z +0.9); 35% of its tail score | sepal_width: falls 0.492 at its median | 6 | 3.400 | 4.500 | 1.600 |
| 16 | 77 | 0.6619 | sepal_length = 6.8 (robust z +1.0); 41% of its tail score | sepal_width: falls 0.386 at its median | 6.800 | 2.800 | 4.800 | 1.400 |
| 17 | 43 | 0.6440 | petal_length = 1.3 (robust z -1.6); 30% of its tail score | sepal_width: falls 0.362 at its median | 4.400 | 3.200 | 1.300 | 0.2000 |
| 18 | 7 | 0.6391 | petal_length = 1.4 (robust z -1.6); 25% of its tail score | sepal_width: falls 0.289 at its median | 4.600 | 3.400 | 1.400 | 0.3000 |
| 19 | 36 | 0.6357 | petal_length = 1.2 (robust z -1.7); 47% of its tail score | sepal_width: falls 0.153 at its median | 5 | 3.200 | 1.200 | 0.2000 |
| 20 | 110 | 0.6220 | sepal_length = 7.2 (robust z +1.3); 23% of its tail score | no single feature lowers it | 7.200 | 3.600 | 6.100 | 2.500 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 086edc3021752402
# Dataset: ml_iris (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"])
FEATURES = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"sepal_length": "numeric",
"sepal_width": "numeric",
"petal_length": "numeric",
"petal_width": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
# %% Scores (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None} # null when the score doesn't use it
PERPLEXITY = 6
if n - 1 <= PERPLEXITY:
cs_error("CS_E_TOO_FEW_ROWS", what=f"SOS with perplexity {PERPLEXITY:g}", min=int(PERPLEXITY) + 2, n=n)
_parts = csax.sos_parts(X, PERPLEXITY)
scores = np.exp(_parts["log_o"])
SCORE_LABEL = "SOS outlier probability"
extra_values["perplexity"] = PERPLEXITY
rescore = lambda Q, where, col: csax.sos_query(X, _parts, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "sos")
# %% Flag anomalies
RULE = "share"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.05, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.knn_outlier/iris_sos/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["sepal_length", "sepal_width", "petal_length", "petal_width", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Nearest-neighbor outlier scores",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
The perplexity here was 6. The score is a probability inside SOS's selection model, not a calibrated chance of being an anomaly. It builds an affinity for every pair of rows, so it scales with the square of the row count.
LOCI: check every scale
ReadLOCI compares, at many radii , how many rows sit within of a row with the average count around its neighbors: the multigranularity deviation . A row is flagged when MDEF exceeds a multiple of its own standard deviation at some radius, three in the classic rule.
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"}],
})
Checking every radius finds both isolated rows and small sparse groups, and tells you at which scale. But searching many radii for every row is not a test with a controlled error rate: the "three" rule sets a flag, not a guarantee.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| ABOD (UCL052) | Runs in CodeSplash: Nearest-neighbor outlier scores, Angle-based (FastABOD) |
| COF (UCL053) | Runs in CodeSplash: Nearest-neighbor outlier scores, COF |
| CBLOF (UCL054) | Runs in CodeSplash: Cluster-based local outlier factor (CBLOF) |
| SOS (UCL062) | Runs in CodeSplash: Nearest-neighbor outlier scores, SOS |
| LOCI (UCL065) | Runs in CodeSplash: Nearest-neighbor outlier scores, LOCI |
Check your understanding
CheckpointCheck yourself
In ABOD, what does a low variance of angles mean for a row?
Show the answer
Answer: b
From inside a cloud, pairs of points surround you at all angles. From outside, the angles cluster.
Check yourself
Why does ABOD need deliberate feature scaling?
Show the answer
Answer: a
Angles aren't invariant to stretching one axis. Choose the scaling for the question, then keep it fixed.
Check yourself
Normal machine readings lie along a thin curved path. Which score is built for rows just off that path?
Show the answer
Answer: b
Round neighborhoods mix the path with empty space. COF's chaining distance follows the path, so a row off it connects poorly.
Check yourself
A library computes "COF" as the mean distance to the k nearest neighbors divided by the neighbors' means. Is that COF?
Show the answer
Answer: b
The path construction is what lets COF follow elongated shapes. Check what an implementation computes before comparing results.
Check yourself
CBLOF flags all forty members of a small cluster. What should you check?
Show the answer
Answer: b
CBLOF scores the cluster's size and distance, not each row's oddness. Audit cluster-level flags separately from point-level ones.
Check yourself
How does the first clustering affect CBLOF?
Show the answer
Answer: a
Report the clusterer and its stability with the anomaly results, and try the weighted and unweighted versions.
Check yourself
What is an SOS score?
Show the answer
Answer: b
Rows nobody would pick are outliers. The probability lives inside the selection model; it isn't calibrated against real anomalies.
Check yourself
What does SOS's perplexity setting do?
Show the answer
Answer: a
Each row's β is tuned to hit the perplexity, so dense and sparse regions get comparable affinities. Check the ranking across a few perplexities.
Check yourself
What does LOCI's multi-radius search add?
Show the answer
Answer: b
Comparing counts across radii catches isolated rows and small sparse groups alike.
Check yourself
LOCI flags rows whose deviation exceeds three standard deviations at some radius. Is that a test with a 0.1% false-alarm rate?
Show the answer
Answer: b
Searching many scales multiplies chances to cross the line. Calibrate false alarms on reference data if you need a rate.
Do it on your own data
In the appUnder Spot anomalies, open Nearest-neighbor outlier scores and switch Score between FastABOD, COF, SOS and LOCI on the same rows; open Cluster-based local outlier factor (CBLOF) and look at the small clusters before you read the flags.
Concepts in this lesson