Skip to content

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.

Verified in Python and R Python and R agree to 6 decimals Also called kNN outlier, k nearest neighbor anomaly, ABOD…

A real result

Example “Usarrests kth”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

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

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

Anomalies
5
Threshold
1.696

Plots

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

Most anomalous rows

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

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

Anomalies
5
Threshold
1.696

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

Most anomalous rows

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

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.
Python

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

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.