CDiscover · discover.kde
Kernel density anomaly scores
Which rows sit where the data are thinnest?
A kernel density estimate over the (standardized) design: a Gaussian bump on every row, with one bandwidth per column from Scott's or Silverman's rule or a factor you set. Each row is scored by minus its leave-one-out log density — the row is left out of its own estimate — so the highest scores are the rows with the fewest close neighbors in every direction at once. No randomness; both engines run the same twin.
A real result
Example “Pima scott”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
27 of 532 rows (5.1%) are flagged as anomalies (Low-density score ≥ 13.1).
- Anomalies
- 27
- Threshold
- 13.144
Plots
View data
| Anomaly | Low-density score |
|---|---|
| false | 7.160 |
| false | 12.658 |
| false | 8.962 |
| false | 9.034 |
| false | 6.870 |
| false | 8.927 |
| false | 7.096 |
| true | 13.293 |
| false | 9.601 |
| false | 10.583 |
| true | 21.917 |
| false | 8.848 |
| true | 14.525 |
| true | 15.663 |
| false | 9.868 |
| false | 7.583 |
| false | 8.201 |
| false | 10.183 |
| false | 9.176 |
| false | 7.740 |
| false | 6.926 |
| false | 9.117 |
| false | 9.090 |
| false | 6.800 |
| false | 6.667 |
| false | 11.474 |
| false | 7.001 |
| false | 8.923 |
| false | 7.841 |
| false | 6.835 |
| false | 9.023 |
| false | 7.501 |
| false | 7.819 |
| false | 8.496 |
| false | 9.183 |
| false | 10.929 |
| false | 8.379 |
| false | 8.549 |
| false | 8.617 |
| false | 7.349 |
| false | 9.930 |
| false | 8.585 |
| false | 8.391 |
| false | 7.063 |
| false | 6.950 |
| false | 8.057 |
| false | 7.704 |
| false | 12.598 |
| false | 8.061 |
| false | 9.800 |
| false | 7.298 |
| false | 6.595 |
| false | 8.396 |
| false | 6.902 |
| false | 6.712 |
| false | 9.646 |
| false | 8.427 |
| false | 9.364 |
| false | 9.555 |
| true | 14.076 |
First 60 of 532 rows.
Most anomalous rows
| Rank | Row | Low-density score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 53.975 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 42.4 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 29.044 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 16.2 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 11 | 21.917 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 11.2 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 279 | 20.248 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 7 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 5 | 221 | 18.697 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 7.28 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 6 | 403 | 17.054 | age = 81 (robust z +6.0); 44% of its tail score | age: falls 7.85 at its median | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 7 | 358 | 16.494 | age = 65 (robust z +4.2); 31% of its tail score | bp: falls 6.16 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 8 | 491 | 16.106 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 6.2 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 9 | 492 | 15.876 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 4.48 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 257 | 15.791 | bp = 30 (robust z -3.5); 30% of its tail score | bp: falls 2.72 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 11 | 14 | 15.663 | npreg = 12 (robust z +3.4); 19% of its tail score | npreg: falls 4.88 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 12 | 432 | 15.163 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 3.26 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 13 | 218 | 14.578 | ped = 1.39 (robust z +3.7); 27% of its tail score | age: falls 3.19 at its median | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
| 14 | 13 | 14.525 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 5.36 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 15 | 208 | 14.387 | bp = 30 (robust z -3.5); 35% of its tail score | bp: falls 6.27 at its median | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 16 | 60 | 14.076 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.96 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 111 | 13.944 | bp = 110 (robust z +3.2); 36% of its tail score | bp: falls 4.19 at its median | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 18 | 417 | 13.666 | age = 58 (robust z +3.4); 21% of its tail score | bmi: falls 2.82 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 19 | 530 | 13.652 | age = 63 (robust z +3.9); 29% of its tail score | age: falls 2.42 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 20 | 272 | 13.648 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 1.47 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
27 of 532 rows (5.1%) are flagged as anomalies (Low-density score ≥ 13.1).
- Anomalies
- 27
- Threshold
- 13.144
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | Low-density score | Most unusual | Biggest score drop | npreg | glu | bp | skin | bmi | ped | age |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 157 | 53.975 | skin = 99 (robust z +6.7); 34% of its tail score | skin: falls 42.4 at its median | 2 | 197 | 70 | 99 | 34.700 | 0.5750 | 62 |
| 2 | 398 | 29.044 | ped = 2.42 (robust z +7.6); 26% of its tail score | ped: falls 16.2 at its median | 0 | 180 | 78 | 63 | 59.400 | 2.420 | 25 |
| 3 | 11 | 21.917 | ped = 2.288 (robust z +7.1); 29% of its tail score | ped: falls 11.2 at its median | 0 | 137 | 40 | 35 | 43.100 | 2.288 | 33 |
| 4 | 279 | 20.248 | bmi = 67.1 (robust z +5.2); 33% of its tail score | bmi: falls 7 at its median | 0 | 129 | 110 | 46 | 67.100 | 0.3190 | 26 |
| 5 | 221 | 18.697 | bp = 110 (robust z +3.2); 28% of its tail score | bp: falls 7.28 at its median | 9 | 171 | 110 | 24 | 45.400 | 0.7210 | 54 |
| 6 | 403 | 17.054 | age = 81 (robust z +6.0); 44% of its tail score | age: falls 7.85 at its median | 9 | 134 | 74 | 33 | 25.900 | 0.4600 | 81 |
| 7 | 358 | 16.494 | age = 65 (robust z +4.2); 31% of its tail score | bp: falls 6.16 at its median | 5 | 103 | 108 | 37 | 39.200 | 0.3050 | 65 |
| 8 | 491 | 16.106 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 6.2 at its median | 10 | 68 | 106 | 23 | 35.500 | 0.2850 | 47 |
| 9 | 492 | 15.876 | bmi = 57.3 (robust z +3.7); 33% of its tail score | bmi: falls 4.48 at its median | 3 | 123 | 100 | 35 | 57.300 | 0.8800 | 22 |
| 10 | 257 | 15.791 | bp = 30 (robust z -3.5); 30% of its tail score | bp: falls 2.72 at its median | 1 | 88 | 30 | 42 | 55 | 0.4960 | 26 |
| 11 | 14 | 15.663 | npreg = 12 (robust z +3.4); 19% of its tail score | npreg: falls 4.88 at its median | 12 | 92 | 62 | 7 | 27.600 | 0.9260 | 44 |
| 12 | 432 | 15.163 | age = 60 (robust z +3.6); 19% of its tail score | skin: falls 3.26 at its median | 6 | 129 | 90 | 7 | 19.600 | 0.5820 | 60 |
| 13 | 218 | 14.578 | ped = 1.39 (robust z +3.7); 27% of its tail score | age: falls 3.19 at its median | 4 | 111 | 72 | 47 | 37.100 | 1.390 | 56 |
| 14 | 13 | 14.525 | age = 59 (robust z +3.5); 28% of its tail score | age: falls 5.36 at its median | 1 | 189 | 60 | 23 | 30.100 | 0.3980 | 59 |
| 15 | 208 | 14.387 | bp = 30 (robust z -3.5); 35% of its tail score | bp: falls 6.27 at its median | 1 | 103 | 30 | 38 | 43.300 | 0.1830 | 33 |
| 16 | 60 | 14.076 | bp = 106 (robust z +2.9); 26% of its tail score | bp: falls 3.96 at its median | 8 | 167 | 106 | 46 | 37.600 | 0.1650 | 43 |
| 17 | 111 | 13.944 | bp = 110 (robust z +3.2); 36% of its tail score | bp: falls 4.19 at its median | 4 | 189 | 110 | 31 | 28.500 | 0.6800 | 37 |
| 18 | 417 | 13.666 | age = 58 (robust z +3.4); 21% of its tail score | bmi: falls 2.82 at its median | 0 | 173 | 78 | 32 | 46.500 | 1.159 | 58 |
| 19 | 530 | 13.652 | age = 63 (robust z +3.9); 29% of its tail score | age: falls 2.42 at its median | 10 | 101 | 76 | 48 | 32.900 | 0.1710 | 63 |
| 20 | 272 | 13.648 | npreg = 17 (robust z +5.1); 36% of its tail score | npreg: falls 1.47 at its median | 17 | 163 | 72 | 41 | 40.900 | 0.8170 | 47 |
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
- Pima scottml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Usarrests silvermanml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Penguins mixed fixedml_penguins · features: island, bill_len, bill_dep, flipper_len, body_mass
- Iris unscaled cutoffml_iris · features: sepal_length, sepal_width, petal_length, petal_width
- Airquality missingml_airquality · features: Ozone, solar radiation, Wind, Temp
- Degenerate n1ml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Degenerate n2ml_pima · features: npreg, glu, bp, skin, bmi, ped, age
- Degenerate infml_pima · features: npreg, glu, bp, skin, bmi, ped, age
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–50 columns
- Columns used to describe each row. Numbers are standardized; categories become indicator columns.
Choices you make
model
- Bandwidth ruledefault scott
How wide each row's bump is, relative to each column's spread.
- Scott's rule(default) — Factor n^(-1/(d+4)) times each column's SD; the usual default for roughly normal data.
- Silverman's rule — Factor (4/(d+2))^(1/(d+4)) n^(-1/(d+4)) times each column's SD; slightly wider bumps than Scott in most cases.
- Factor you set — Each column's bandwidth is your factor times its SD; smaller factors make the density bumpier.
- Bandwidth factordefault 0.5
Each column's bandwidth as a multiple of its SD (0.5 = half an SD).
preprocess
- Standardize featuresdefault on
Mean 0, SD 1 (population SD) before the density; bandwidths follow each column's SD either way.
options
- Flag anomalies bydefault share
Flag a fixed share of the lowest-density 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 whose low-density score (minus the log density) is above the value you set.
- Share flaggeddefault 0.05
Share of rows to flag as anomalies (0.05 flags the most unusual 5%).
- Score cutoffdefault 10
Rows whose low-density score is above this are flagged; each +1 means a density e times thinner.
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.
- bandwidth_factor
- How wide each row's Gaussian bump is, as a multiple of each column's SD; smaller is bumpier.
- n_dims
- How wide each row's Gaussian bump is, as a multiple of each column's SD; smaller is bumpier.
- mean_log_density
- Minus the row's leave-one-out log density: higher means fewer close neighbors in every direction at once.
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 10 decimals (relative tolerance 1e-9). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Both engines run the density twin (codesplash.ml.density_kde ↔ codesplashr::cs_ml_kde_*): product Gaussian kernel, bandwidth = rule factor × population SD per design column, leave-one-out log density by log-sum-exp. Columns with no spread are left out of the density in both, with a warning.
The exact script CodeSplash ran for example “Pima scott” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kernel density anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kde 1.0.0 · spec eb69a79d8c0ca1f2
# 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, cs_warning
from codesplash.ml import anomaly as csanom
from codesplash.ml import density_kde as cskde
from codesplash.ml import embed as csembed
# %% Data
from codesplash.errors import check_finite_columns
check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]), ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]) # ±Inf stops the run
IMPUTE = "median"
SCALE = "standard"
FEATURES = ["npreg", "glu", "bp", "skin", "bmi", "ped", "age"]
df = pd.read_parquet("tests/parity/fixtures/ml_pima.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"npreg": "numeric",
"glu": "numeric",
"bp": "numeric",
"skin": "numeric",
"bmi": "numeric",
"ped": "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))
# %% Density and scores
if len(df) < 3:
cs_error("CS_E_TOO_FEW_ROWS", what="A kernel density estimate", min=3, n=len(df))
kde = cskde.fit(X, "scott", 0.5)
if kde["d"] == 0:
cs_error("CS_E_CONSTANT", column=FEATURES[0])
_dropped = [fitted.names[c] for c in range(X.shape[1]) if c not in set(kde["keep"].tolist())]
if _dropped:
warnings.append(f"{len(_dropped)} design column{'s' if len(_dropped) != 1 else ''} with no spread left out of the density: {', '.join(_dropped[:5])}{'…' if len(_dropped) > 5 else ''}.")
# Minus the leave-one-out log density: the row itself is left out of its own estimate.
scores = cskde.scores(X, kde)
SCORE_LABEL = "Low-density score"
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {
"bandwidth_factor": kde["factor"],
"n_dims": int(kde["d"]),
"mean_log_density": float(-np.mean(scores)),
}
rescore = lambda Q, where, col: cskde.rescore(X, kde, Q, where, col) # the other rows held fixed
# %% Flag anomalies
RULE = "share"
_cutoff = 10
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.kde/pima_scott/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 = ["npreg", "glu", "bp", "skin", "bmi", "ped", "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": "Kernel density anomaly 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 “Pima scott” · R version 4.5.1 (2025-06-13)
# Kernel density anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kde 1.0.0 · spec eb69a79d8c0ca1f2
# 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
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_pima.parquet", col_select = c("npreg", "glu", "bp", "skin", "bmi", "ped", "age"))), c("npreg", "glu", "bp", "skin", "bmi", "ped", "age")) # ±Inf stops the run
IMPUTE <- "median"
SCALE <- "standard"
FEATURES <- c("npreg", "glu", "bp", "skin", "bmi", "ped", "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(
npreg = "numeric",
glu = "numeric",
bp = "numeric",
skin = "numeric",
bmi = "numeric",
ped = "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
# %% Density and scores
if (nrow(df) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "A kernel density estimate", min = 3L, n = nrow(df))
kde <- cs_ml_kde_fit(X, "scott", 0.5)
if (kde$d == 0) cs_error("CS_E_CONSTANT", column = FEATURES[1])
dropped_ <- cs_ml_design_names(fitted)[setdiff(seq_len(ncol(X)) - 1L, kde$keep) + 1L]
if (length(dropped_)) {
warnings <- c(warnings, sprintf("%d design column%s with no spread left out of the density: %s%s.", length(dropped_),
if (length(dropped_) != 1) "s" else "", paste(utils::head(dropped_, 5), collapse = ", "),
if (length(dropped_) > 5) "…" else ""))
}
# Minus the leave-one-out log density: the row itself is left out of its own estimate.
scores <- cs_ml_kde_scores(X, kde)
SCORE_LABEL <- "Low-density score"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(bandwidth_factor = kde$factor, n_dims = kde$d, mean_log_density = -mean(scores))
rescore <- function(Q, where0, col0) cs_ml_kde_rescore(X, kde, Q, where0, col0) # the other rows held fixed
# %% Flag anomalies
RULE <- "share"
cutoff_ <- 10
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.kde/pima_scott/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("npreg", "glu", "bp", "skin", "bmi", "ped", "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 = "Kernel density anomaly 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
- Silverman BW (1986). Density estimation for statistics and data analysis. Chapman & Hall.
- Scott DW (2015). Multivariate density estimation: theory, practice, and visualization, 2nd ed. Wiley.
- Latecki LJ, Lazarevic A, Pokrajac D (2007). Outlier detection with kernel density functions. MLDM 2007, 61–75.
From the CodeSplash method registry · discover.kde v1.0.0.