CDiscover · discover.knn_outlier
Nearest-neighbor outlier scores
Which rows are far from, or poorly connected to, their nearest neighbors?
Seven anomaly scores built from each row's nearest neighbors (Euclidean distance on standardized features): the distance to the kth neighbor or the mean or median of the k distances, angle-based outlier detection (FastABOD), the connectivity-based outlier factor (COF), stochastic outlier selection (SOS) and the local correlation integral (LOCI). Both engines run the same twin, with exact distances and neighbor ties broken by row order.
A real result
Example “Usarrests kth”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).
- Anomalies
- 5
- Threshold
- 1.696
Plots
View data
| Anomaly | kth-neighbor distance |
|---|---|
| false | 1.296 |
| true | 2.360 |
| false | 1.224 |
| false | 1.303 |
| true | 1.696 |
| false | 1.413 |
| false | 1.087 |
| false | 1.567 |
| true | 1.767 |
| false | 1.599 |
| false | 1.398 |
| false | 0.8672 |
| false | 1.357 |
| false | 0.8498 |
| false | 0.8672 |
| false | 0.7666 |
| false | 1.191 |
| false | 1.329 |
| false | 0.8572 |
| false | 1.303 |
| false | 1.145 |
| false | 1.274 |
| false | 0.9845 |
| false | 1.643 |
| false | 1.177 |
| false | 0.8947 |
| false | 0.8569 |
| true | 1.946 |
| false | 0.9343 |
| false | 1.471 |
| false | 1.346 |
| false | 1.346 |
| true | 2.075 |
| false | 1.064 |
| false | 0.9824 |
| false | 0.7441 |
| false | 1.253 |
| false | 0.8569 |
| false | 1.654 |
| false | 1.411 |
| false | 0.9975 |
| false | 1.365 |
| false | 1.346 |
| false | 1.250 |
| false | 1.689 |
| false | 0.9874 |
| false | 1.152 |
| false | 1.289 |
| false | 1.046 |
| false | 0.8989 |
Most anomalous rows
| Rank | Row | kth-neighbor distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.360 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.881 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 33 | 2.075 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.514 at its median | 13 | 337 | 45 | 16.100 |
| 3 | 28 | 1.946 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.522 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 9 | 1.767 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.241 at its median | 15.400 | 335 | 80 | 31.900 |
| 5 | 5 | 1.696 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.257 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 45 | 1.689 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.654 at its median | 2.200 | 48 | 32 | 11.200 |
| 7 | 39 | 1.654 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 0.324 at its median | 3.400 | 174 | 87 | 8.300 |
| 8 | 24 | 1.643 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.0783 at its median | 16.100 | 259 | 44 | 17.100 |
| 9 | 10 | 1.599 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.479 at its median | 17.400 | 211 | 60 | 25.800 |
| 10 | 8 | 1.567 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.703 at its median | 5.900 | 238 | 72 | 15.800 |
| 11 | 30 | 1.471 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.841 at its median | 7.400 | 159 | 89 | 18.800 |
| 12 | 6 | 1.413 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.355 at its median | 7.900 | 204 | 78 | 38.700 |
| 13 | 40 | 1.411 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.131 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 11 | 1.398 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.386 at its median | 5.300 | 46 | 83 | 20.200 |
| 15 | 42 | 1.365 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Murder: falls 0.283 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 13 | 1.357 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | UrbanPop: falls 0.214 at its median | 10.400 | 249 | 83 | 24 |
| 17 | 43 | 1.346 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.214 at its median | 12.700 | 201 | 80 | 25.500 |
| 18 | 31 | 1.346 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Assault: falls 0.0137 at its median | 11.400 | 285 | 70 | 32.100 |
| 19 | 32 | 1.346 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.262 at its median | 11.100 | 254 | 86 | 26.100 |
| 20 | 18 | 1.329 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.0502 at its median | 15.400 | 249 | 66 | 22.200 |
5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).
- Anomalies
- 5
- Threshold
- 1.696
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | kth-neighbor distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.360 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.881 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 33 | 2.075 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.514 at its median | 13 | 337 | 45 | 16.100 |
| 3 | 28 | 1.946 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.522 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 9 | 1.767 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.241 at its median | 15.400 | 335 | 80 | 31.900 |
| 5 | 5 | 1.696 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.257 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 45 | 1.689 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.654 at its median | 2.200 | 48 | 32 | 11.200 |
| 7 | 39 | 1.654 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 0.324 at its median | 3.400 | 174 | 87 | 8.300 |
| 8 | 24 | 1.643 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.0783 at its median | 16.100 | 259 | 44 | 17.100 |
| 9 | 10 | 1.599 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.479 at its median | 17.400 | 211 | 60 | 25.800 |
| 10 | 8 | 1.567 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.703 at its median | 5.900 | 238 | 72 | 15.800 |
| 11 | 30 | 1.471 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.841 at its median | 7.400 | 159 | 89 | 18.800 |
| 12 | 6 | 1.413 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.355 at its median | 7.900 | 204 | 78 | 38.700 |
| 13 | 40 | 1.411 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.131 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 11 | 1.398 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.386 at its median | 5.300 | 46 | 83 | 20.200 |
| 15 | 42 | 1.365 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Murder: falls 0.283 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 13 | 1.357 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | UrbanPop: falls 0.214 at its median | 10.400 | 249 | 83 | 24 |
| 17 | 43 | 1.346 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.214 at its median | 12.700 | 201 | 80 | 25.500 |
| 18 | 31 | 1.346 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Assault: falls 0.0137 at its median | 11.400 | 285 | 70 | 32.100 |
| 19 | 32 | 1.346 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.262 at its median | 11.100 | 254 | 86 | 26.100 |
| 20 | 18 | 1.329 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.0502 at its median | 15.400 | 249 | 66 | 22.200 |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Usarrests kthml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Pima meanml_pima · features: glu, bp, bmi, age
- Iris median unscaledml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Penguins abod mixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass
- Usarrests cof cutoffml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Iris sosml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Usarrests loci cutoffml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Airquality kth missing cutoffml_airquality · features: Ozone, solar radiation, Wind, Temp
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Featuresnumeric / categorical / boolean · 1–200 columns
- Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Choices you make
model
- Scoredefault kth
How each row's neighbors are turned into one anomaly score.
- Distance to the kth neighbor(default) — The classic kNN detector: far from its kth nearest row means isolated.
- Mean distance to k neighbors — Averages the k neighbor distances; steadier than the kth distance alone.
- Median distance to k neighbors — The middle of the k neighbor distances; robust to one very near or far neighbor.
- Angle-based (FastABOD) — Low variance of the angles to neighbor pairs means the row sits outside the data; score is minus that variance.
- Connectivity-based outlier factor (COF) — Chaining distance along the nearest path through the neighbors, relative to theirs; well above 1 is weakly connected.
- Stochastic outlier selection (SOS) — Probability that no other row picks this one as a neighbor, with bandwidths set by perplexity.
- Local correlation integral (LOCI) — Largest standardized drop in neighbor count across all radii (MDEF / σ); exact, so at most 500 rows.
- Neighbors (k)default 10
Neighbors each row is compared with. Capped at the number of rows minus one.
- Perplexitydefault 4.5
Effective number of neighbors each row spreads its affinity over; must be below the number of rows minus one.
preprocess
- Standardize featuresdefault on
Mean 0, SD 1 (population SD) so no feature dominates the distances.
options
- Flag anomalies bydefault share
Flag a fixed share of the most unusual rows, or every row whose score passes a cutoff.
- Share of rows (the highest scores)(default) — Flags a set share of rows with the highest scores; pick it when you know how many you can review.
- Score cutoff — Flags rows at or above a cutoff; leave it empty for the score's usual cutoff.
- Share flaggeddefault 0.05
Share of rows to flag as anomalies (0.05 flags the most unusual 5%).
- Score cutoffdefault —
Empty: COF 1.5, SOS 0.5, LOCI 3; distances median + 3 MADs of the scores; ABOD the same rule on log variance.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_flagged
- How many independent units the analysis used; it sets precision and power.
- threshold
- The probability above which the model predicts the positive class; 0.5 is rarely the best choice.
- score_check
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_max
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- score_mean
- A built-in check that CodeSplash's own recomputation from the engine's predictions matches the score the engine reported.
- neighbors
- Distance from a row to its kth nearest other row (or the mean or median of its k neighbor distances).
- perplexity
- The effective number of neighbors each row spreads its affinity over in SOS; it must stay below the number of rows minus one.
Per group, level or term: top_row[<rank>], top_score[<rank>], why_feature[<rank>], why_z[<rank>], why_share[<rank>], drop_feature[<rank>], drop_score[<rank>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-9). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Both engines run the twin codesplash.ml.anomaly_ext ↔ codesplashr::cs_ml_* (distances accumulated column by column, exactly k neighbors with distance ties broken by row order). SOS sets each bandwidth by bisection on log β to a 1e-12 width; the other scores are exact.
- Conventions against PyOD 3: kth/mean/median match KNN; FastABOD with k neighbors matches PyOD's ABOD(n_neighbors = k + 1), which counts the row itself and skips it; COF builds Tang et al.'s greedy set-based nearest path, where PyOD orders the path by distance from the row; SOS uses squared distances (the paper's affinity) where PyOD's code uses plain distances; LOCI scores each row by its largest MDEF/σ over all critical radii (α = 1/2, n̂ ≥ 20), where PyOD keeps the last radius it visits — rows flagged at MDEF > 3σ are the same.
The exact script CodeSplash ran for example “Usarrests kth” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 7df4f7819d6700bf
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"Murder": "numeric",
"Assault": "numeric",
"UrbanPop": "numeric",
"Rape": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
# %% Scores (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None} # null when the score doesn't use it
if n < 2:
cs_error("CS_E_TOO_FEW_ROWS", what="Nearest-neighbor scores", min=2, n=n)
k = min(5, n - 1)
extra_values["neighbors"] = k
METHOD = "kth"
scores = csax.knn_scores(X, k, METHOD)
SCORE_LABEL = "kth-neighbor distance"
rescore = lambda Q, where, col: csax.knn_query(X, k, METHOD, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth")
# %% Flag anomalies
RULE = "share"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.1, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.knn_outlier/usarrests_kth/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["Murder", "Assault", "UrbanPop", "Rape", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Nearest-neighbor outlier scores",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
The exact script CodeSplash ran for example “Usarrests kth” · R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 7df4f7819d6700bf
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = c("Murder", "Assault", "UrbanPop", "Rape"))), c("Murder", "Assault", "UrbanPop", "Rape"))
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
Murder = "numeric",
Assault = "numeric",
UrbanPop = "numeric",
Rape = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
# %% Scores (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA) # null when the score doesn't use it
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Nearest-neighbor scores", min = 2, n = n)
k <- min(5, n - 1L)
extra_values$neighbors <- k
METHOD <- "kth"
scores <- cs_ml_knn_scores(X, k, METHOD)
SCORE_LABEL <- "kth-neighbor distance"
rescore <- function(Q, where0, col0) cs_ml_knn_query(X, k, METHOD, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth")
# %% Flag anomalies
RULE <- "share"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.1, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.knn_outlier/usarrests_kth/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("Murder", "Assault", "UrbanPop", "Rape")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Nearest-neighbor outlier scores",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
Sources
- Ramaswamy S, Rastogi R, Shim K (2000). Efficient algorithms for mining outliers from large data sets. SIGMOD 2000, 427–438.
- Kriegel H-P, Schubert M, Zimek A (2008). Angle-based outlier detection in high-dimensional data. KDD 2008, 444–452.
- Tang J, Chen Z, Fu AW, Cheung DW (2002). Enhancing effectiveness of outlier detections for low density patterns. PAKDD 2002, 535–548.
- Janssens JHM, Huszár F, Postma EO, van den Herik HJ (2012). Stochastic outlier selection. Tilburg University TiCC TR 2012-001.
- Papadimitriou S, Kitagawa H, Gibbons PB, Faloutsos C (2003). LOCI: fast outlier detection using the local correlation integral. ICDE 2003, 315–326.
From the CodeSplash method registry · discover.knn_outlier v1.0.0.