Anomaly scores from density and distance: KDE, copulas, MCD, kNN, LOF and LoOP
Six ways to say a row sits where the data are thin, globally or locally. What each score assumes about normal data, why units and neighbors change the answer, and why none of these scores is a probability until you check it.
What runs in CodeSplash
- UCL046Kernel density estimation (KDE) Runs in CodeSplash
- UCL047Gaussian copula density model Partly runs in CodeSplash
- UCL050Local Outlier Factor (LOF) Runs in CodeSplash
- UCL051Local Outlier Probabilities (LoOP) Runs in CodeSplash
- UCL058Minimum Covariance Determinant Mahalanobis detector Runs in CodeSplash
- UCL061K-nearest-neighbor distance detector Runs in CodeSplash
- Kernel density anomaly scores Verified in Python and R
- Synthetic data — Gaussian copula Verified in Python and R
- Robust covariance (MCD) outliers Verified in Python and R
- Nearest-neighbor outlier scores Verified in Python and R
- Local outlier factor Verified in Python and R
You will be able to
- Contrast global scores (KDE, copula, MCD) with local ones (kNN distance, LOF, LoOP)
- Explain why a density cutoff depends on units and dimension
- Explain masking and why a robust covariance flags rows an ordinary one misses
- Say what LoOP's 0-to-1 scale does and doesn't promise
Thin data, two scales
ReadMost anomaly scores say the same thing in different words: this row sits where the data are thin. They differ in where they look.
- Global scores compare each row with one model of all normal data: a kernel density, a copula, one robust ellipse.
- Local scores compare each row with its own neighbors: distance to the -th neighbor, LOF, LoOP.
A global score misses a row that is odd only for its neighborhood; a local score can wave through a whole odd cluster. And every score here is a ranking first. Turning it into an alarm needs calibration, the topic of the last lesson in this unit.
Kernel density: units matter
ReadA kernel density estimate puts a small bump on every row: . The KDE scoreLow-density scoreMinus the row's leave-one-out log density: higher means fewer close neighbors in every direction at once. is the negative log density, with the row left out of its own estimate. The bandwidth trades bias for variance; the kernel matters less.
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 |
The exact R script · R 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"))
))
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 |
The exact Python script · Python 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"}],
})
A density has units: one per unit of each column, raised to the dimension. That's why a cutoff can't be carried from one table to another, and why density estimates get unreliable as columns pile up.
A cutoff from somewhere else
PredictPredict first
You score iris in its raw centimeters with a kernel density and flag rows whose score passes a cutoff someone used on another table. How many rows get flagged?
Reveal
Every row: all 150 of them. The score's scale depends on the units and the number of columns, so a borrowed cutoff means nothing. Flag a share, or calibrate the cutoff on held-out normal rows of this table.
150 of 150 rows (100.0%) are flagged as anomalies (Low-density score ≥ 2).
- Anomalies
- 150
- Threshold
- 2
Plots
View data
| Anomaly | Low-density score |
|---|---|
| true | 2.448 |
| true | 2.854 |
| true | 2.555 |
| true | 2.709 |
| true | 2.558 |
| true | 3.273 |
| true | 2.699 |
| true | 2.399 |
| true | 3.389 |
| true | 2.667 |
| true | 2.842 |
| true | 2.477 |
| true | 2.858 |
| true | 3.366 |
| true | 4.037 |
| true | 5.295 |
| true | 3.280 |
| true | 2.444 |
| true | 3.451 |
| true | 2.916 |
| true | 2.752 |
| true | 2.741 |
| true | 3.136 |
| true | 2.687 |
| true | 2.573 |
| true | 2.935 |
| true | 2.467 |
| true | 2.487 |
| true | 2.487 |
| true | 2.554 |
| true | 2.626 |
| true | 2.778 |
| true | 3.951 |
| true | 4.203 |
| true | 2.627 |
| true | 2.558 |
| true | 2.876 |
| true | 2.676 |
| true | 3.116 |
| true | 2.422 |
| true | 2.456 |
| true | 7.490 |
| true | 2.925 |
| true | 2.789 |
| true | 3.053 |
| true | 2.854 |
| true | 2.935 |
| true | 2.628 |
| true | 2.756 |
| true | 2.428 |
| true | 3.491 |
| true | 2.888 |
| true | 2.997 |
| true | 3.464 |
| true | 2.607 |
| true | 2.549 |
| true | 3.138 |
| true | 4.043 |
| true | 2.781 |
| true | 3.280 |
First 60 of 150 rows.
Most anomalous rows
| Rank | Row | Low-density score | Most unusual | Biggest score drop | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 42 | 7.490 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 4.56 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.581 | sepal_length = 7.9 (robust z +2.0); 40% of its tail score | sepal_width: falls 1.39 at its median | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 118 | 5.421 | sepal_length = 7.7 (robust z +1.8); 28% of its tail score | sepal_width: falls 1.43 at its median | 7.700 | 3.800 | 6.700 | 2.200 |
| 4 | 16 | 5.295 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | sepal_width: falls 0.84 at its median | 5.700 | 4.400 | 1.500 | 0.4000 |
| 5 | 61 | 5.190 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_width: falls 0.713 at its median | 5 | 2 | 3.500 | 1 |
| 6 | 119 | 5.155 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.882 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 7 | 110 | 5.098 | sepal_length = 7.2 (robust z +1.3); 23% of its tail score | sepal_width: falls 1.47 at its median | 7.200 | 3.600 | 6.100 | 2.500 |
| 8 | 107 | 4.602 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 1.56 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 9 | 123 | 4.229 | sepal_length = 7.7 (robust z +1.8); 34% of its tail score | sepal_width: falls 0.126 at its median | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 136 | 4.214 | sepal_length = 7.7 (robust z +1.8); 37% of its tail score | sepal_length: falls 0.316 at its median | 7.700 | 3 | 6.100 | 2.300 |
| 11 | 34 | 4.203 | sepal_width = 4.2 (robust z +2.7); 50% of its tail score | sepal_width: falls 0.448 at its median | 5.500 | 4.200 | 1.400 | 0.2000 |
| 12 | 63 | 4.101 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | sepal_width: falls 1.04 at its median | 6 | 2.200 | 4 | 1 |
| 13 | 120 | 4.049 | sepal_width = 2.2 (robust z -1.8); 56% of its tail score | sepal_width: falls 1.58 at its median | 6 | 2.200 | 5 | 1.500 |
| 14 | 58 | 4.043 | sepal_width = 2.4 (robust z -1.3); 40% of its tail score | sepal_length: falls 0.577 at its median | 4.900 | 2.400 | 3.300 | 1 |
| 15 | 15 | 4.037 | sepal_width = 4 (robust z +2.2); 39% of its tail score | no single feature lowers it | 5.800 | 4 | 1.200 | 0.2000 |
| 16 | 69 | 4.012 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | sepal_width: falls 1.62 at its median | 6.200 | 2.200 | 4.500 | 1.500 |
| 17 | 94 | 4.004 | sepal_width = 2.3 (robust z -1.6); 45% of its tail score | sepal_length: falls 0.291 at its median | 5 | 2.300 | 3.300 | 1 |
| 18 | 106 | 3.979 | sepal_length = 7.6 (robust z +1.7); 35% of its tail score | no single feature lowers it | 7.600 | 3 | 6.600 | 2.100 |
| 19 | 33 | 3.951 | sepal_width = 4.1 (robust z +2.5); 39% of its tail score | sepal_width: falls 0.822 at its median | 5.200 | 4.100 | 1.500 | 0.1000 |
| 20 | 109 | 3.910 | sepal_width = 2.5 (robust z -1.1); 29% of its tail score | sepal_width: falls 1.22 at its median | 6.700 | 2.500 | 5.800 | 1.800 |
The exact R script · R 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 f49dbac3a1daaa59
# 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
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")) # ±Inf stops the run
IMPUTE <- "median"
SCALE <- "none"
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
# %% 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 <- "cutoff"
cutoff_ <- 2
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/iris_unscaled_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("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 = "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"))
))
150 of 150 rows (100.0%) are flagged as anomalies (Low-density score ≥ 2).
- Anomalies
- 150
- Threshold
- 2
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 | sepal_length | sepal_width | petal_length | petal_width |
|---|---|---|---|---|---|---|---|---|
| 1 | 42 | 7.490 | petal_length = 1.3 (robust z -1.6); 26% of its tail score | sepal_width: falls 4.56 at its median | 4.500 | 2.300 | 1.300 | 0.3000 |
| 2 | 132 | 5.581 | sepal_length = 7.9 (robust z +2.0); 40% of its tail score | sepal_width: falls 1.39 at its median | 7.900 | 3.800 | 6.400 | 2 |
| 3 | 118 | 5.421 | sepal_length = 7.7 (robust z +1.8); 28% of its tail score | sepal_width: falls 1.43 at its median | 7.700 | 3.800 | 6.700 | 2.200 |
| 4 | 16 | 5.295 | sepal_width = 4.4 (robust z +3.1); 61% of its tail score | sepal_width: falls 0.84 at its median | 5.700 | 4.400 | 1.500 | 0.4000 |
| 5 | 61 | 5.190 | sepal_width = 2 (robust z -2.2); 59% of its tail score | sepal_width: falls 0.713 at its median | 5 | 2 | 3.500 | 1 |
| 6 | 119 | 5.155 | sepal_length = 7.7 (robust z +1.8); 27% of its tail score | sepal_width: falls 0.882 at its median | 7.700 | 2.600 | 6.900 | 2.300 |
| 7 | 110 | 5.098 | sepal_length = 7.2 (robust z +1.3); 23% of its tail score | sepal_width: falls 1.47 at its median | 7.200 | 3.600 | 6.100 | 2.500 |
| 8 | 107 | 4.602 | sepal_width = 2.5 (robust z -1.1); 35% of its tail score | sepal_length: falls 1.56 at its median | 4.900 | 2.500 | 4.500 | 1.700 |
| 9 | 123 | 4.229 | sepal_length = 7.7 (robust z +1.8); 34% of its tail score | sepal_width: falls 0.126 at its median | 7.700 | 2.800 | 6.700 | 2 |
| 10 | 136 | 4.214 | sepal_length = 7.7 (robust z +1.8); 37% of its tail score | sepal_length: falls 0.316 at its median | 7.700 | 3 | 6.100 | 2.300 |
| 11 | 34 | 4.203 | sepal_width = 4.2 (robust z +2.7); 50% of its tail score | sepal_width: falls 0.448 at its median | 5.500 | 4.200 | 1.400 | 0.2000 |
| 12 | 63 | 4.101 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | sepal_width: falls 1.04 at its median | 6 | 2.200 | 4 | 1 |
| 13 | 120 | 4.049 | sepal_width = 2.2 (robust z -1.8); 56% of its tail score | sepal_width: falls 1.58 at its median | 6 | 2.200 | 5 | 1.500 |
| 14 | 58 | 4.043 | sepal_width = 2.4 (robust z -1.3); 40% of its tail score | sepal_length: falls 0.577 at its median | 4.900 | 2.400 | 3.300 | 1 |
| 15 | 15 | 4.037 | sepal_width = 4 (robust z +2.2); 39% of its tail score | no single feature lowers it | 5.800 | 4 | 1.200 | 0.2000 |
| 16 | 69 | 4.012 | sepal_width = 2.2 (robust z -1.8); 58% of its tail score | sepal_width: falls 1.62 at its median | 6.200 | 2.200 | 4.500 | 1.500 |
| 17 | 94 | 4.004 | sepal_width = 2.3 (robust z -1.6); 45% of its tail score | sepal_length: falls 0.291 at its median | 5 | 2.300 | 3.300 | 1 |
| 18 | 106 | 3.979 | sepal_length = 7.6 (robust z +1.7); 35% of its tail score | no single feature lowers it | 7.600 | 3 | 6.600 | 2.100 |
| 19 | 33 | 3.951 | sepal_width = 4.1 (robust z +2.5); 39% of its tail score | sepal_width: falls 0.822 at its median | 5.200 | 4.100 | 1.500 | 0.1000 |
| 20 | 109 | 3.910 | sepal_width = 2.5 (robust z -1.1); 29% of its tail score | sepal_width: falls 1.22 at its median | 6.700 | 2.500 | 5.800 | 1.800 |
The exact Python script · Python 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 f49dbac3a1daaa59
# 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, 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_iris.parquet", columns=["sepal_length", "sepal_width", "petal_length", "petal_width"]), ["sepal_length", "sepal_width", "petal_length", "petal_width"]) # ±Inf stops the run
IMPUTE = "median"
SCALE = "none"
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))
# %% 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 = "cutoff"
_cutoff = 2
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/iris_unscaled_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 = ["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": "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"}],
})
Copula density: unusual combinations
ReadA Gaussian copulaGaussian copulaKeeps each column's own distribution and ties the columns together with the correlations of a multivariate normal. separates each column's own distribution from how the columns move together. Each value becomes a normal score through its rank, , and a correlation matrix ties them. The dependence part of the log density, , is low for a row whose combination is rare even when each value is ordinary.
320 synthetic rows over 8 columns from 320 training rows with a Gaussian copula. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.052 and categories by a mean total variation of 0.038.
- Synthetic rows
- 320
- Mean KS distance
- 0.0520
- Mean TV distance
- 0.0375
- Rows copied from the data
- 0
Plots
View data
| Density | Source | age |
|---|---|---|
| 0.0230 | real | 18.950 |
| 0.0016 | real | 20.850 |
| 0.0049 | real | 22.750 |
| 0.0148 | real | 24.650 |
| 0.0148 | real | 26.550 |
| 0.0181 | real | 28.450 |
| 0.0197 | real | 30.350 |
| 0.0296 | real | 32.250 |
| 0.0362 | real | 34.150 |
| 0.0115 | real | 36.050 |
| 0.0362 | real | 37.950 |
| 0.0313 | real | 39.850 |
| 0.0296 | real | 41.750 |
| 0.0280 | real | 43.650 |
| 0.0280 | real | 45.550 |
| 0.0181 | real | 47.450 |
| 0.0164 | real | 49.350 |
| 0.0197 | real | 51.250 |
| 0.0362 | real | 53.150 |
| 0.0148 | real | 55.050 |
| 0.0164 | real | 56.950 |
| 0.0181 | real | 58.850 |
| 0.0082 | real | 60.750 |
| 0.0164 | real | 62.650 |
| 0.0049 | real | 64.550 |
| 0.0115 | real | 66.450 |
| 0.0066 | real | 68.350 |
| 0.0049 | real | 70.250 |
| 0.0016 | real | 72.150 |
| 0.0049 | real | 74.050 |
| 0.0164 | synthetic | 18.950 |
| 0 | synthetic | 20.850 |
| 0.0033 | synthetic | 22.750 |
| 0.0164 | synthetic | 24.650 |
| 0.0164 | synthetic | 26.550 |
| 0.0148 | synthetic | 28.450 |
| 0.0214 | synthetic | 30.350 |
| 0.0197 | synthetic | 32.250 |
| 0.0313 | synthetic | 34.150 |
| 0.0082 | synthetic | 36.050 |
| 0.0395 | synthetic | 37.950 |
| 0.0378 | synthetic | 39.850 |
| 0.0263 | synthetic | 41.750 |
| 0.0280 | synthetic | 43.650 |
| 0.0280 | synthetic | 45.550 |
| 0.0197 | synthetic | 47.450 |
| 0.0132 | synthetic | 49.350 |
| 0.0214 | synthetic | 51.250 |
| 0.0428 | synthetic | 53.150 |
| 0.0247 | synthetic | 55.050 |
| 0.0214 | synthetic | 56.950 |
| 0.0181 | synthetic | 58.850 |
| 0.0082 | synthetic | 60.750 |
| 0.0115 | synthetic | 62.650 |
| 0.0082 | synthetic | 64.550 |
| 0.0148 | synthetic | 66.450 |
| 0.0066 | synthetic | 68.350 |
| 0.0033 | synthetic | 70.250 |
| 0.0033 | synthetic | 72.150 |
| 0.0016 | synthetic | 74.050 |
View data
| Density | Source | annual income |
|---|---|---|
| 3.010e-6 | real | 6851.93 |
| 1.605e-5 | real | 10141.74 |
| 2.107e-5 | real | 13431.55 |
| 2.408e-5 | real | 16721.36 |
| 3.511e-5 | real | 20011.17 |
| 4.113e-5 | real | 23300.98 |
| 2.809e-5 | real | 26590.79 |
| 2.408e-5 | real | 29880.60 |
| 2.508e-5 | real | 33170.41 |
| 1.605e-5 | real | 36460.22 |
| 1.605e-5 | real | 39750.03 |
| 1.505e-5 | real | 43039.84 |
| 1.003e-5 | real | 46329.65 |
| 5.016e-6 | real | 49619.46 |
| 6.019e-6 | real | 52909.27 |
| 4.013e-6 | real | 56199.07 |
| 4.013e-6 | real | 59488.88 |
| 4.013e-6 | real | 62778.69 |
| 1.003e-6 | real | 66068.50 |
| 1.003e-6 | real | 69358.31 |
| 1.003e-6 | real | 72648.12 |
| 0 | real | 75937.93 |
| 1.003e-6 | real | 79227.74 |
| 1.003e-6 | real | 82517.55 |
| 0 | real | 85807.36 |
| 0 | real | 89097.17 |
| 0 | real | 92386.98 |
| 0 | real | 95676.79 |
| 0 | real | 98966.60 |
| 1.003e-6 | real | 102256.41 |
| 4.000e-6 | synthetic | 6851.93 |
| 9.999e-6 | synthetic | 10141.74 |
| 1.800e-5 | synthetic | 13431.55 |
| 3.100e-5 | synthetic | 16721.36 |
| 3.200e-5 | synthetic | 20011.17 |
| 3.200e-5 | synthetic | 23300.98 |
| 3.300e-5 | synthetic | 26590.79 |
| 2.000e-5 | synthetic | 29880.60 |
| 3.100e-5 | synthetic | 33170.41 |
| 2.100e-5 | synthetic | 36460.22 |
| 1.400e-5 | synthetic | 39750.03 |
| 9.999e-6 | synthetic | 43039.84 |
| 1.300e-5 | synthetic | 46329.65 |
| 5.999e-6 | synthetic | 49619.46 |
| 4.999e-6 | synthetic | 52909.27 |
| 4.000e-6 | synthetic | 56199.07 |
| 7.999e-6 | synthetic | 59488.88 |
| 6.999e-6 | synthetic | 62778.69 |
| 2.000e-6 | synthetic | 66068.50 |
| 0 | synthetic | 69358.31 |
| 0 | synthetic | 72648.12 |
| 9.999e-7 | synthetic | 75937.93 |
| 0 | synthetic | 79227.74 |
| 0 | synthetic | 82517.55 |
| 0 | synthetic | 85807.36 |
| 9.999e-7 | synthetic | 89097.17 |
| 0 | synthetic | 92386.98 |
| 0 | synthetic | 95676.79 |
| 0 | synthetic | 98966.60 |
| 9.999e-7 | synthetic | 102256.41 |
View data
| Density | Source | tenure_months |
|---|---|---|
| 0.0938 | real | 0.7667 |
| 0.0224 | real | 2.300 |
| 0.0183 | real | 3.833 |
| 0.0306 | real | 5.367 |
| 0.0204 | real | 6.900 |
| 0.0265 | real | 8.433 |
| 0.0204 | real | 9.967 |
| 0.0530 | real | 11.500 |
| 0.0183 | real | 13.033 |
| 0.0510 | real | 14.567 |
| 0.0183 | real | 16.100 |
| 0.0367 | real | 17.633 |
| 0.0224 | real | 19.167 |
| 0.0448 | real | 20.700 |
| 0.0469 | real | 22.233 |
| 0.0082 | real | 23.767 |
| 0.0306 | real | 25.300 |
| 0.0061 | real | 26.833 |
| 0.0183 | real | 28.367 |
| 0.0041 | real | 29.900 |
| 0.0143 | real | 31.433 |
| 0.0061 | real | 32.967 |
| 0.0183 | real | 34.500 |
| 0.0020 | real | 36.033 |
| 0.0041 | real | 37.567 |
| 0 | real | 39.100 |
| 0.0061 | real | 40.633 |
| 0.0041 | real | 42.167 |
| 0.0020 | real | 43.700 |
| 0.0041 | real | 45.233 |
| 0.0836 | synthetic | 0.7667 |
| 0.0245 | synthetic | 2.300 |
| 0.0143 | synthetic | 3.833 |
| 0.0224 | synthetic | 5.367 |
| 0.0163 | synthetic | 6.900 |
| 0.0265 | synthetic | 8.433 |
| 0.0204 | synthetic | 9.967 |
| 0.0510 | synthetic | 11.500 |
| 0.0122 | synthetic | 13.033 |
| 0.0591 | synthetic | 14.567 |
| 0.0122 | synthetic | 16.100 |
| 0.0408 | synthetic | 17.633 |
| 0.0285 | synthetic | 19.167 |
| 0.0387 | synthetic | 20.700 |
| 0.0632 | synthetic | 22.233 |
| 0.0082 | synthetic | 23.767 |
| 0.0387 | synthetic | 25.300 |
| 0.0082 | synthetic | 26.833 |
| 0.0204 | synthetic | 28.367 |
| 0.0020 | synthetic | 29.900 |
| 0.0245 | synthetic | 31.433 |
| 0.0102 | synthetic | 32.967 |
| 0.0061 | synthetic | 34.500 |
| 0.0041 | synthetic | 36.033 |
| 0.0041 | synthetic | 37.567 |
| 0 | synthetic | 39.100 |
| 0.0020 | synthetic | 40.633 |
| 0.0041 | synthetic | 42.167 |
| 0.0061 | synthetic | 43.700 |
| 0 | synthetic | 45.233 |
View data
| Density | Source | signup |
|---|---|---|
| 0.0005 | real | 17582.23 |
| 0.0007 | real | 17654.70 |
| 0.0005 | real | 17727.17 |
| 0.0005 | real | 17799.63 |
| 0.0004 | real | 17872.10 |
| 0.0005 | real | 17944.57 |
| 0.0006 | real | 18017.03 |
| 0.0004 | real | 18089.50 |
| 0.0005 | real | 18161.97 |
| 0.0005 | real | 18234.43 |
| 0.0001 | real | 18306.90 |
| 0.0009 | real | 18379.37 |
| 0.0006 | real | 18451.83 |
| 0.0003 | real | 18524.30 |
| 0.0005 | real | 18596.77 |
| 0.0004 | real | 18669.23 |
| 0.0002 | real | 18741.70 |
| 0.0005 | real | 18814.17 |
| 0.0006 | real | 18886.63 |
| 0.0005 | real | 18959.10 |
| 0.0005 | real | 19031.57 |
| 0.0005 | real | 19104.03 |
| 0.0003 | real | 19176.50 |
| 0.0006 | real | 19248.97 |
| 0.0004 | real | 19321.43 |
| 0.0003 | real | 19393.90 |
| 0.0002 | real | 19466.37 |
| 0.0005 | real | 19538.83 |
| 0.0003 | real | 19611.30 |
| 0.0004 | real | 19683.77 |
| 0.0006 | synthetic | 17582.23 |
| 0.0006 | synthetic | 17654.70 |
| 0.0004 | synthetic | 17727.17 |
| 0.0005 | synthetic | 17799.63 |
| 0.0005 | synthetic | 17872.10 |
| 0.0005 | synthetic | 17944.57 |
| 0.0006 | synthetic | 18017.03 |
| 0.0005 | synthetic | 18089.50 |
| 0.0007 | synthetic | 18161.97 |
| 0.0005 | synthetic | 18234.43 |
| 0.0002 | synthetic | 18306.90 |
| 0.0010 | synthetic | 18379.37 |
| 0.0009 | synthetic | 18451.83 |
| 0.0004 | synthetic | 18524.30 |
| 0.0003 | synthetic | 18596.77 |
| 0.0003 | synthetic | 18669.23 |
| 0.0001 | synthetic | 18741.70 |
| 0.0005 | synthetic | 18814.17 |
| 0.0007 | synthetic | 18886.63 |
| 0.0004 | synthetic | 18959.10 |
| 0.0004 | synthetic | 19031.57 |
| 0.0003 | synthetic | 19104.03 |
| 0.0004 | synthetic | 19176.50 |
| 0.0006 | synthetic | 19248.97 |
| 0.0003 | synthetic | 19321.43 |
| 0.0004 | synthetic | 19393.90 |
| 0.0002 | synthetic | 19466.37 |
| 0.0002 | synthetic | 19538.83 |
| 0.0002 | synthetic | 19611.30 |
| 0.0003 | synthetic | 19683.77 |
View data
| plan | Share | Source |
|---|---|---|
| basic | 0.3563 | real |
| plus | 0.3969 | real |
| premium | 0.2469 | real |
| basic | 0.3031 | synthetic |
| plus | 0.4031 | synthetic |
| premium | 0.2938 | synthetic |
View data
| region | Share | Source |
|---|---|---|
| east | 0.2848 | real |
| north | 0.2718 | real |
| south | 0.3042 | real |
| west | 0.1392 | real |
| east | 0.2754 | synthetic |
| north | 0.2656 | synthetic |
| south | 0.3115 | synthetic |
| west | 0.1475 | synthetic |
View data
| churned | Share | Source |
|---|---|---|
| false | 0.7688 | real |
| true | 0.2313 | real |
| false | 0.7250 | synthetic |
| true | 0.2750 | synthetic |
View data
| Column | Column | Difference |
|---|---|---|
| age | age | 0 |
| annual income | age | −0.0395 |
| tenure_months | age | 0.0251 |
| signup | age | 0.0161 |
| visits | age | 0.0482 |
| age | annual income | −0.0395 |
| annual income | annual income | 0 |
| tenure_months | annual income | −0.0986 |
| signup | annual income | 0.0416 |
| visits | annual income | 0.0930 |
| age | tenure_months | 0.0251 |
| annual income | tenure_months | −0.0986 |
| tenure_months | tenure_months | 0 |
| signup | tenure_months | 0.0056 |
| visits | tenure_months | −0.0217 |
| age | signup | 0.0161 |
| annual income | signup | 0.0416 |
| tenure_months | signup | 0.0056 |
| signup | signup | 0 |
| visits | signup | −0.0303 |
| age | visits | 0.0482 |
| annual income | visits | 0.0930 |
| tenure_months | visits | −0.0217 |
| signup | visits | −0.0303 |
| visits | visits | 0 |
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 44.19 ± 12.6 | 0.0531 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 3.043e+04 ± 1.47e+04 | 0.0508 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 15.7 ± 10.4 | 0.0500 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 40.3% | 0.0531 | total variation |
| region | categorical | south 30.4% | south 31.1% | 0.0157 | total variation |
| churned | boolean | false 76.9% | false 72.5% | 0.0437 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-08-22 ± 593 days | 0.0844 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.469 ± 2.14 | 0.0219 | Kolmogorov–Smirnov D |
Copula correlations (normal scores)
| Column | age | annual income | tenure_months | plan | region | churned | signup | visits |
|---|---|---|---|---|---|---|---|---|
| age | 1 | 0.3161 | 0.7229 | 0.1714 | −0.0043 | −0.0816 | −0.0289 | 0.0342 |
| annual income | 0.3161 | 1 | 0.1855 | 0.6503 | −0.1323 | −0.0202 | −0.0244 | 0.2147 |
| tenure_months | 0.7229 | 0.1855 | 1 | 0.1515 | 0.0518 | −0.1174 | −0.0413 | 0.0361 |
| plan | 0.1714 | 0.6503 | 0.1515 | 1 | −0.0928 | −0.1387 | −0.0624 | 0.3428 |
| region | −0.0043 | −0.1323 | 0.0518 | −0.0928 | 1 | 0.0850 | 0.0078 | 0.0240 |
| churned | −0.0816 | −0.0202 | −0.1174 | −0.1387 | 0.0850 | 1 | 0.0535 | −0.0268 |
| signup | −0.0289 | −0.0244 | −0.0413 | −0.0624 | 0.0078 | 0.0535 | 1 | −0.0207 |
| visits | 0.0342 | 0.2147 | 0.0361 | 0.3428 | 0.0240 | −0.0268 | −0.0207 | 1 |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact R script · R R version 4.5.1 (2025-06-13)
# Synthetic data — Gaussian copula
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.copula 1.1.0 · spec 9387f102a28b36bf
# Dataset: g1_customers (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
COLUMNS <- c("age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits")
KINDS <- list(
age = "numeric",
`annual income` = "numeric",
tenure_months = "numeric",
plan = "categorical",
region = "categorical",
churned = "boolean",
signup = "temporal",
visits = "numeric"
)
LEVELS <- list(
plan = c("basic", "plus", "premium"),
region = c("east", "north", "south", "west")
)
SEED <- 42
loaded <- cs_synth_load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
cols <- loaded$cols; n_input <- loaded$n
for (c in cols) if (c$kind == "numeric") cs_check_finite(c$values, c$name) # infinite values stop the run (registry/errors.yaml)
rng <- cs_rng(SEED) # shared stream: the same holdout and the same synthetic rows in Python and R
sp <- cs_synth_split(n_input, 0.2, rng)
train_rows <- sp$train; holdout_rows <- sp$holdout
train <- lapply(cols, cs_synth_take, rows = train_rows)
N_OUT <- length(train_rows)
warnings <- list()
fit_values <- list()
extra_tables <- list()
model_note <- ""
if (length(holdout_rows)) {
warnings <- c(warnings, sprintf("%s of %s rows (%.0f%%) were held out of training so privacy and utility can be checked against rows the generator never saw.",
format(length(holdout_rows), big.mark = ","), format(n_input, big.mark = ","), 100 * length(holdout_rows) / n_input))
}
for (c in train) if (mean(cs_synth_missing(c)) == 1) cs_error("CS_E_ALL_MISSING", column = c$name) # no values in the training rows
# %% Generate
# Gaussian copula (twin: codesplash.synth.copula): normal scores -> correlation -> shared-stream
# draws -> each column's marginal (interpolated values for numbers).
fit <- cs_synth_copula(train, N_OUT, rng, marginal = "interpolated")
synth <- fit$cols
R <- fit$R
fit_values$marginal <- "interpolated"
up <- which(upper.tri(R), arr.ind = TRUE)
up <- up[order(up[, 1], up[, 2]), , drop = FALSE]
fit_values$max_abs_corr <- if (nrow(up)) max(abs(R[up])) else 0
for (r in seq_len(nrow(up))) fit_values[[sprintf("corr[%s,%s]", COLUMNS[up[r, 1]], COLUMNS[up[r, 2]])]] <- R[up[r, 1], up[r, 2]]
model_note <- " with a Gaussian copula"
# Copula (dependence) log density per row: mean over complete training rows and held-out rows. Not
# reported when the correlation of normal scores is (nearly) singular: the density is then meaningless.
if (min(eigen(R, symmetric = TRUE, only.values = TRUE)$values) < 1e-6) {
fit_values$copula_loglik_train <- NA_real_ # NA publishes as null
fit_values$copula_loglik_holdout <- NA_real_
warnings <- c(warnings, "The copula's log density is not reported: the correlation of the normal scores is singular (too few complete rows, or columns that move together exactly).")
} else {
ld_train_ <- cs_synth_copula_log_density(train, R, train)
fit_values$copula_loglik_train <- mean(ld_train_, na.rm = TRUE)
ld_hold_ <- if (length(holdout_rows)) cs_synth_copula_log_density(train, R, lapply(cols, cs_synth_take, rows = holdout_rows)) else numeric(0)
fit_values$copula_loglik_holdout <- if (any(!is.na(ld_hold_))) mean(ld_hold_, na.rm = TRUE) else NA_real_ # NA publishes as null
}
crow <- lapply(seq_along(COLUMNS), function(i) c(list(column = COLUMNS[i]), stats::setNames(as.list(R[i, ]), sprintf("c%d", seq_along(COLUMNS) - 1L))))
extra_tables <- list(list(
key = "copula", title = "Copula correlations (normal scores)",
columns = c(list(list(key = "column", label = "Column", type = "string")),
lapply(seq_along(COLUMNS), function(j) list(key = sprintf("c%d", j - 1L), label = COLUMNS[j], type = "number"))),
rows = crow))
synth <- cs_synth_add_missing(synth, train, rng, "keep_rate") # each column's missing share, at random
# %% Write and compare
out <- cs_ml_out_dir("target/academy-parity/run-54123/synth.copula/customers_all/out-r")
path <- cs_synth_write(file.path(out, "synthetic.parquet"), synth)
split <- cs_synth_write_split(file.path(out, "split.parquet"), n_input, train_rows, holdout_rows)
sm <- cs_synth_summarize(train, synth, length(train_rows), n_input, length(holdout_rows), fit_values)
values <- sm$values
summary <- sprintf("%s synthetic rows over %d column%s from %s training rows%s.",
format(values$n_rows, big.mark = ","), length(COLUMNS), if (length(COLUMNS) != 1) "s" else "",
format(length(train_rows), big.mark = ","), model_note)
if (!is.nan(values$fidelity_ks_mean)) {
summary <- paste0(summary, sprintf(" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of %.3f", values$fidelity_ks_mean),
if (!is.nan(values$fidelity_tv_mean)) sprintf(" and categories by a mean total variation of %.3f.", values$fidelity_tv_mean) else ".")
} else if (!is.nan(values$fidelity_tv_mean)) {
summary <- paste0(summary, sprintf(" Categories differ from the data by a mean total variation of %.3f.", values$fidelity_tv_mean))
}
if (values$exact_matches > 0) {
summary <- paste0(summary, sprintf(" %s synthetic row%s identical to a training row.", format(values$exact_matches, big.mark = ","),
if (values$exact_matches != 1) "s are" else " is"))
}
cs_synth_publish(
"Synthetic data — Gaussian copula",
cs_engine_info("stats", "nanoparquet", "nanoparquet"),
summary, values, sm$table, sm$charts, warnings,
list(list(key = "synthetic", path = path, format = "parquet", title = "Synthetic rows"),
list(key = "split", path = split, format = "parquet", title = "Training and holdout rows")),
list(kind = "generator", columns = I(COLUMNS), params = list(
n_rows = NULL,
marginal = "interpolated",
missing = "keep_rate",
holdout = 0.2
)),
extra_tables
)
320 synthetic rows over 8 columns from 320 training rows with a Gaussian copula. Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of 0.052 and categories by a mean total variation of 0.038.
- Synthetic rows
- 320
- Mean KS distance
- 0.0520
- Mean TV distance
- 0.0375
- Rows copied from the data
- 0
To keep this page light, the plots are shown once, under the R tab.
Real vs synthetic, column by column
| Column | Kind | Real | Synthetic | Distance | Measure |
|---|---|---|---|---|---|
| age | numeric | 43.14 ± 13.1 | 44.19 ± 12.6 | 0.0531 | Kolmogorov–Smirnov D |
| annual income | numeric | 2.929e+04 ± 1.43e+04 | 3.043e+04 ± 1.47e+04 | 0.0508 | Kolmogorov–Smirnov D |
| tenure_months | numeric | 15 ± 10.7 | 15.7 ± 10.4 | 0.0500 | Kolmogorov–Smirnov D |
| plan | categorical | plus 39.7% | plus 40.3% | 0.0531 | total variation |
| region | categorical | south 30.4% | south 31.1% | 0.0157 | total variation |
| churned | boolean | false 76.9% | false 72.5% | 0.0438 | total variation |
| signup | temporal | 2020-11-05 ± 621 days | 2020-08-22 ± 593 days | 0.0844 | Kolmogorov–Smirnov D |
| visits | numeric | 3.394 ± 2.09 | 3.469 ± 2.14 | 0.0219 | Kolmogorov–Smirnov D |
Copula correlations (normal scores)
| Column | age | annual income | tenure_months | plan | region | churned | signup | visits |
|---|---|---|---|---|---|---|---|---|
| age | 1 | 0.3161 | 0.7229 | 0.1714 | −0.0043 | −0.0816 | −0.0289 | 0.0342 |
| annual income | 0.3161 | 1 | 0.1855 | 0.6503 | −0.1323 | −0.0202 | −0.0244 | 0.2147 |
| tenure_months | 0.7229 | 0.1855 | 1 | 0.1515 | 0.0518 | −0.1174 | −0.0413 | 0.0361 |
| plan | 0.1714 | 0.6503 | 0.1515 | 1 | −0.0928 | −0.1387 | −0.0624 | 0.3428 |
| region | −0.0043 | −0.1323 | 0.0518 | −0.0928 | 1 | 0.0850 | 0.0078 | 0.0240 |
| churned | −0.0816 | −0.0202 | −0.1174 | −0.1387 | 0.0850 | 1 | 0.0535 | −0.0268 |
| signup | −0.0289 | −0.0244 | −0.0413 | −0.0624 | 0.0078 | 0.0535 | 1 | −0.0207 |
| visits | 0.0342 | 0.2147 | 0.0361 | 0.3428 | 0.0240 | −0.0268 | −0.0207 | 1 |
- 80 of 400 rows (20%) were held out of training so privacy and utility can be checked against rows the generator never saw.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Synthetic data — Gaussian copula
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method synth.copula 1.1.0 · spec 9387f102a28b36bf
# Dataset: g1_customers (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 codesplash as cs
from codesplash.errors import check_finite
from codesplash.ml.run import out_dir
from codesplash.stats.rng import Rng
from codesplash.synth import common as sy
from codesplash.synth import copula
from codesplash.synth import copula_density
# %% Data
COLUMNS = ["age", "annual income", "tenure_months", "plan", "region", "churned", "signup", "visits"]
KINDS = {
"age": "numeric",
"annual income": "numeric",
"tenure_months": "numeric",
"plan": "categorical",
"region": "categorical",
"churned": "boolean",
"signup": "temporal",
"visits": "numeric",
}
LEVELS = {
"plan": ["basic", "plus", "premium"],
"region": ["east", "north", "south", "west"],
}
SEED = 42
cols, n_input = sy.load("tests/parity/fixtures/g1_customers.parquet", COLUMNS, KINDS, LEVELS)
for c in cols:
if c.kind == "numeric":
check_finite(c.values, c.name) # infinite values stop the run (registry/errors.yaml)
rng = Rng(SEED) # shared stream: the same holdout and the same synthetic rows in Python and R
train_rows, holdout_rows = sy.split_holdout(n_input, 0.2, rng)
train = [c.take(train_rows) for c in cols]
N_OUT = None or len(train_rows)
warnings = []
fit_values = {}
extra_tables = []
model_note = ""
if len(holdout_rows):
warnings.append(f"{len(holdout_rows):,} of {n_input:,} rows ({len(holdout_rows) / n_input:.0%}) were held out of training so privacy and utility can be checked against rows the generator never saw.")
for c in train:
share = float(np.mean(c.missing()))
if share == 1.0:
cs.cs_error("CS_E_ALL_MISSING", column=c.name) # no values in the training rows
# %% Generate
# Gaussian copula (twin: codesplashr::cs_synth_copula): normal scores → correlation → shared-stream
# draws → each column's marginal (interpolated values for numbers).
synth, R = copula.synthesize(train, N_OUT, rng, marginal="interpolated")
fit_values["marginal"] = "interpolated"
iu = np.triu_indices(len(COLUMNS), 1)
fit_values["max_abs_corr"] = float(np.max(np.abs(R[iu]))) if len(iu[0]) else 0.0
for i, j in zip(*iu):
fit_values[f"corr[{COLUMNS[i]},{COLUMNS[j]}]"] = float(R[i, j])
model_note = " with a Gaussian copula"
# Copula (dependence) log density per row: mean over complete training rows and held-out rows. Not
# reported when the correlation of normal scores is (nearly) singular: the density is then meaningless.
if float(np.linalg.eigvalsh(R).min()) < 1e-6:
fit_values["copula_loglik_train"] = None
fit_values["copula_loglik_holdout"] = None
warnings.append("The copula's log density is not reported: the correlation of the normal scores is singular (too few complete rows, or columns that move together exactly).")
else:
_ld_train = copula_density.log_density(train, R, train)
fit_values["copula_loglik_train"] = float(np.nanmean(_ld_train))
_ld_hold = copula_density.log_density(train, R, [c.take(holdout_rows) for c in cols]) if len(holdout_rows) else np.array([])
fit_values["copula_loglik_holdout"] = float(np.nanmean(_ld_hold)) if np.any(~np.isnan(_ld_hold)) else None
extra_tables.append({
"key": "copula",
"title": "Copula correlations (normal scores)",
"columns": [{"key": "column", "label": "Column", "type": "string"}] + [{"key": f"c{j}", "label": c, "type": "number"} for j, c in enumerate(COLUMNS)],
"rows": [{"column": a, **{f"c{j}": float(R[i, j]) for j in range(len(COLUMNS))}} for i, a in enumerate(COLUMNS)],
})
sy.add_missing(synth, train, rng, "keep_rate") # each column's missing share, at random
# %% Write and compare
out = out_dir("target/academy-parity/run-54123/synth.copula/customers_all/out-python")
path = sy.write(os.path.join(out, "synthetic.parquet"), synth)
split = sy.write_split(os.path.join(out, "split.parquet"), n_input, train_rows, holdout_rows)
values, table, charts = sy.summarize(train, synth, len(train_rows), n_input, len(holdout_rows), fit_values)
summary = (
f"{values['n_rows']:,} synthetic rows over {len(COLUMNS)} column{'s' if len(COLUMNS) != 1 else ''} from "
f"{len(train_rows):,} training rows{model_note}."
)
if not np.isnan(values["fidelity_ks_mean"]):
summary += f" Numeric columns differ from the data by a mean Kolmogorov–Smirnov distance of {values['fidelity_ks_mean']:.3f}"
summary += f" and categories by a mean total variation of {values['fidelity_tv_mean']:.3f}." if not np.isnan(values["fidelity_tv_mean"]) else "."
elif not np.isnan(values["fidelity_tv_mean"]):
summary += f" Categories differ from the data by a mean total variation of {values['fidelity_tv_mean']:.3f}."
if values["exact_matches"]:
summary += f" {values['exact_matches']:,} synthetic row{'s are' if values['exact_matches'] != 1 else ' is'} identical to a training row."
sy.publish(
"Synthetic data — Gaussian copula",
cs.engine_info("scipy", "pyarrow", "numpy", "pyarrow"),
summary, values, table, charts, warnings,
[{"key": "synthetic", "path": path, "format": "parquet", "title": "Synthetic rows"},
{"key": "split", "path": split, "format": "parquet", "title": "Training and holdout rows"}],
{"kind": "generator", "columns": COLUMNS, "params": {
"n_rows": None,
"marginal": "interpolated",
"missing": "keep_rate",
"holdout": 0.2,
}},
extra_tables,
)
Mean log density was 0.795 on training rows and 0.721 on held-out rows; a big drop means the learned dependence doesn't carry over. Discrete columns need care: ties make the continuous formula inexact.
Robust covariance: escaping masking
ReadMahalanobis distance measures how far a row is from the center in the data's own ellipse. Estimate and from all rows and the outliers stretch the ellipse until they look normal: masking. The minimum covariance determinant estimator fits them to the rows whose covariance has the smallest determinant, then reweights.
15 of 50 rows (30.0%) are flagged as anomalies (Robust distance ≥ 3.34).
- Anomalies
- 15
- Threshold
- 3.338
Plots
View data
| Anomaly | Robust distance |
|---|---|
| false | 2.630 |
| true | 9.402 |
| true | 4.553 |
| false | 1.583 |
| true | 6.725 |
| true | 6.805 |
| false | 2.132 |
| false | 2.797 |
| false | 2.522 |
| true | 4.253 |
| false | 2.927 |
| false | 1.934 |
| false | 1.657 |
| false | 1.384 |
| false | 1.169 |
| false | 0.6352 |
| false | 2.588 |
| true | 3.615 |
| false | 1.732 |
| false | 2.708 |
| false | 2.015 |
| true | 3.742 |
| false | 1.450 |
| true | 5.347 |
| false | 2.663 |
| false | 0.8962 |
| false | 1.011 |
| true | 7.431 |
| false | 1.280 |
| false | 2.053 |
| true | 3.371 |
| false | 1.727 |
| true | 5.100 |
| false | 1.777 |
| false | 1.433 |
| false | 0.7964 |
| true | 5.193 |
| false | 1.558 |
| true | 4.130 |
| false | 3.290 |
| false | 1.396 |
| false | 2.400 |
| false | 2.070 |
| true | 3.494 |
| false | 2.489 |
| false | 0.6891 |
| true | 4.337 |
| false | 2.456 |
| false | 1.484 |
| false | 0.9951 |
Most anomalous rows
| Rank | Row | Robust distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 9.402 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 6.62 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 28 | 7.431 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 4.39 at its median | 12.200 | 252 | 81 | 46 |
| 3 | 6 | 6.805 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 5.51 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 5 | 6.725 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 3.65 at its median | 9 | 276 | 91 | 40.600 |
| 5 | 24 | 5.347 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Murder: falls 1.83 at its median | 16.100 | 259 | 44 | 17.100 |
| 6 | 37 | 5.193 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 3.22 at its median | 4.900 | 159 | 67 | 29.300 |
| 7 | 33 | 5.100 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.96 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 3 | 4.553 | Rape = 31 (robust z +1.3); 28% of its tail score | Rape: falls 1.35 at its median | 8.100 | 294 | 80 | 31 |
| 9 | 47 | 4.337 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 2.04 at its median | 4 | 145 | 73 | 26.200 |
| 10 | 10 | 4.253 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 1.01 at its median | 17.400 | 211 | 60 | 25.800 |
| 11 | 39 | 4.130 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 1.09 at its median | 3.400 | 174 | 87 | 8.300 |
| 12 | 22 | 3.742 | Rape = 35.1 (robust z +1.7); 35% of its tail score | Rape: falls 1.02 at its median | 12.100 | 255 | 74 | 35.100 |
| 13 | 18 | 3.615 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.966 at its median | 15.400 | 249 | 66 | 22.200 |
| 14 | 44 | 3.494 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 1.58 at its median | 3.200 | 120 | 80 | 22.900 |
| 15 | 31 | 3.371 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Rape: falls 0.594 at its median | 11.400 | 285 | 70 | 32.100 |
| 16 | 40 | 3.290 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.251 at its median | 14.400 | 279 | 48 | 22.500 |
| 17 | 11 | 2.927 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.08 at its median | 5.300 | 46 | 83 | 20.200 |
| 18 | 8 | 2.797 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 1.62 at its median | 5.900 | 238 | 72 | 15.800 |
| 19 | 20 | 2.708 | Assault = 300 (robust z +1.3); 44% of its tail score | Assault: falls 0.303 at its median | 11.300 | 300 | 67 | 27.800 |
| 20 | 25 | 2.663 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 1.87 at its median | 9 | 178 | 70 | 28.200 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Robust covariance (MCD) outliers
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_cov 1.1.0 · spec 264b07cb26a3e2fe
# 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 <- "none" # MCD is affine equivariant: scaling does not change the distances
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
SEED <- 42
# %% Minimum covariance determinant (FastMCD twin, subsets from the shared stream)
fit <- cs_ml_mcd(X, 0.5, SEED)
scores <- fit$robust_distance
DEFAULT_CUTOFF <- fit$cutoff
SCORE_LABEL <- "Robust distance"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(h = fit$h, logdet_raw = fit$logdet_raw, n_reweighted = fit$n_reweighted, chi2_cutoff = fit$cutoff,
n_beyond_cutoff = sum(scores >= fit$cutoff), classical_flagged = sum(fit$classical_distance >= fit$cutoff))
for (i in seq_along(FEATURES)) extra_values[[sprintf("center[%s]", FEATURES[i])]] <- fit$center[i]
rescore <- function(Q, where0, col0) sqrt(cs_ml_mahalanobis2(Q, fit$center, fit$cov)) # the fitted center and scatter
# %% 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.robust_cov/usarrests/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 = "Robust covariance (MCD) outliers",
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"))
))
15 of 50 rows (30.0%) are flagged as anomalies (Robust distance ≥ 3.34).
- Anomalies
- 15
- Threshold
- 3.338
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | Robust distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 9.402 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 6.62 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 28 | 7.431 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 4.39 at its median | 12.200 | 252 | 81 | 46 |
| 3 | 6 | 6.805 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 5.51 at its median | 7.900 | 204 | 78 | 38.700 |
| 4 | 5 | 6.725 | Rape = 40.6 (robust z +2.4); 29% of its tail score | Rape: falls 3.65 at its median | 9 | 276 | 91 | 40.600 |
| 5 | 24 | 5.347 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Murder: falls 1.83 at its median | 16.100 | 259 | 44 | 17.100 |
| 6 | 37 | 5.193 | Rape = 29.3 (robust z +1.1); 40% of its tail score | Rape: falls 3.22 at its median | 4.900 | 159 | 67 | 29.300 |
| 7 | 33 | 5.100 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.96 at its median | 13 | 337 | 45 | 16.100 |
| 8 | 3 | 4.553 | Rape = 31 (robust z +1.3); 28% of its tail score | Rape: falls 1.35 at its median | 8.100 | 294 | 80 | 31 |
| 9 | 47 | 4.337 | Rape = 26.2 (robust z +0.7); 29% of its tail score | Rape: falls 2.04 at its median | 4 | 145 | 73 | 26.200 |
| 10 | 10 | 4.253 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 1.01 at its median | 17.400 | 211 | 60 | 25.800 |
| 11 | 39 | 4.130 | Rape = 8.3 (robust z -1.4); 36% of its tail score | Rape: falls 1.09 at its median | 3.400 | 174 | 87 | 8.300 |
| 12 | 22 | 3.742 | Rape = 35.1 (robust z +1.7); 35% of its tail score | Rape: falls 1.02 at its median | 12.100 | 255 | 74 | 35.100 |
| 13 | 18 | 3.615 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.966 at its median | 15.400 | 249 | 66 | 22.200 |
| 14 | 44 | 3.494 | UrbanPop = 80 (robust z +0.8); 28% of its tail score | Murder: falls 1.58 at its median | 3.200 | 120 | 80 | 22.900 |
| 15 | 31 | 3.371 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Rape: falls 0.594 at its median | 11.400 | 285 | 70 | 32.100 |
| 16 | 40 | 3.290 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.251 at its median | 14.400 | 279 | 48 | 22.500 |
| 17 | 11 | 2.927 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 1.08 at its median | 5.300 | 46 | 83 | 20.200 |
| 18 | 8 | 2.797 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 1.62 at its median | 5.900 | 238 | 72 | 15.800 |
| 19 | 20 | 2.708 | Assault = 300 (robust z +1.3); 44% of its tail score | Assault: falls 0.303 at its median | 11.300 | 300 | 67 | 27.800 |
| 20 | 25 | 2.663 | Rape = 28.2 (robust z +0.9); 38% of its tail score | Rape: falls 1.87 at its median | 9 | 178 | 70 | 28.200 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Robust covariance (MCD) outliers
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_cov 1.1.0 · spec 264b07cb26a3e2fe
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import anomaly as csanom
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "none" # MCD is affine equivariant: scaling does not change the distances
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))
SEED = 42
# %% Minimum covariance determinant (FastMCD twin, subsets from the shared stream)
fit = dx.mcd(X, 0.5, SEED)
scores = fit["robust_distance"]
DEFAULT_CUTOFF = fit["cutoff"]
SCORE_LABEL = "Robust distance"
ENGINE_PACKAGES = ("numpy", "scipy", "pandas")
extra_values = {
"h": fit["h"],
"logdet_raw": fit["logdet_raw"],
"n_reweighted": fit["n_reweighted"],
"chi2_cutoff": fit["cutoff"],
"n_beyond_cutoff": int(np.sum(scores >= fit["cutoff"])),
"classical_flagged": int(np.sum(fit["classical_distance"] >= fit["cutoff"])),
}
for name, v in zip(FEATURES, fit["center"]):
extra_values[f"center[{name}]"] = float(v)
rescore = lambda Q, where, col: np.sqrt(dx.mahalanobis2(Q, fit["center"], fit["cov"])) # the fitted center and scatter
# %% 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.robust_cov/usarrests/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": "Robust covariance (MCD) outliers",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
On the arrests data, the ordinary covariance flagged 2 states and the robust one 15. One ellipse still assumes one population: normal data with several modes need a local or mixture detector.
kNN distance: the simplest local score
ReadThe kNN distance scorekNN outlier scoreDistance from a row to its kth nearest other row (or the mean or median of its k neighbor distances). is the distance to the -th nearest row, , or the mean or median of the distances. Name the version you used, and leave a row out of its own neighbor list.
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 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 7df4f7819d6700bf
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
IMPUTE <- "median"
SCALE <- "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs_check_finite_columns(as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = c("Murder", "Assault", "UrbanPop", "Rape"))), c("Murder", "Assault", "UrbanPop", "Rape"))
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
Murder = "numeric",
Assault = "numeric",
UrbanPop = "numeric",
Rape = "numeric"
),
levels = list(
),
impute = IMPUTE,
scale = SCALE
)
fitted <- cs_ml_design_fit(design, df)
X <- unname(cs_ml_design_apply(fitted, df)) # numbers imputed / scaled; categories one-hot (missing -> all zero)
rows <- seq_len(nrow(df)) - 1L
# %% Scores (twin: codesplash.ml.anomaly_ext; exact distances, k neighbors with ties broken by row order)
n <- nrow(df)
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list(neighbors = NA, perplexity = NA) # null when the score doesn't use it
if (n < 2) cs_error("CS_E_TOO_FEW_ROWS", what = "Nearest-neighbor scores", min = 2, n = n)
k <- min(5, n - 1L)
extra_values$neighbors <- k
METHOD <- "kth"
scores <- cs_ml_knn_scores(X, k, METHOD)
SCORE_LABEL <- "kth-neighbor distance"
rescore <- function(Q, where0, col0) cs_ml_knn_query(X, k, METHOD, Q, where0)
DEFAULT_CUTOFF <- cs_ml_ax_auto_cutoff(scores, "kth")
# %% Flag anomalies
RULE <- "share"
cutoff_ <- NULL
if (is.null(cutoff_)) cutoff_ <- DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flagged <- cs_ml_flag(scores, RULE, 0.1, cutoff_)
flags <- flagged$flag
threshold <- flagged$threshold
ord <- order(-scores, rows) # highest score first, ties by row
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.knn_outlier/usarrests_kth/out-r")
nanoparquet::write_parquet(data.frame(row = as.integer(rows), score = scores, anomaly = flags), file.path(out, "labels.parquet"))
# %% Result
values <- c(list(n = length(rows), n_flagged = sum(flags), threshold = threshold,
score_check = cs_ml_checksum(scores, rows), score_max = max(scores), score_mean = mean(scores)),
extra_values)
for (rank in seq_len(min(10L, length(ord)))) {
values[[sprintf("top_row[%d]", rank)]] <- rows[ord[rank]]
values[[sprintf("top_score[%d]", rank)]] <- scores[ord[rank]]
}
top <- utils::head(ord, 20L)
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
NUMERIC <- c("Murder", "Assault", "UrbanPop", "Rape")
why <- NULL
if (length(NUMERIC)) {
F_ <- as.matrix(as.data.frame(lapply(df[rows + 1L, NUMERIC, drop = FALSE], function(x) as.numeric(as.character(x)))))
med_ <- apply(F_, 2, function(c) if (any(!is.na(c))) stats::median(c[!is.na(c)]) else 0)
for (j in seq_len(ncol(F_))) F_[is.na(F_[, j]), j] <- med_[j]
why <- cs_ml_anomaly_explain(F_, top - 1L)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("why_feature[%d]", rank)]] <- why$feature[rank]
values[[sprintf("why_z[%d]", rank)]] <- why$z[rank]
values[[sprintf("why_share[%d]", rank)]] <- why$share[rank]
}
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
drop_ <- cs_ml_score_drops(X, top - 1L, match(NUMERIC, cs_ml_design_names(fitted)) - 1L, scores, rescore)
for (rank in seq_len(min(10L, length(top)))) {
values[[sprintf("drop_feature[%d]", rank)]] <- drop_$feature[rank]
values[[sprintf("drop_score[%d]", rank)]] <- drop_$drop[rank]
}
}
table_rows <- lapply(seq_along(top), function(rank) {
i <- top[rank]
r <- list(rank = rank, row = rows[i] + 1L, score = scores[i])
if (!is.null(why)) {
j <- why$feature[rank] + 1L
sh <- why$share[rank]
r$why <- paste0(sprintf("%s = %s (robust z %+.1f)", NUMERIC[j], format(signif(F_[i, j], 4)), why$z[rank]),
if (is.nan(sh)) "" else sprintf("; %.0f%% of its tail score", 100 * sh))
d_ <- drop_$drop[rank]
r$drop <- if (d_ > 0) sprintf("%s: falls %s at its median", NUMERIC[drop_$feature[rank] + 1L], format(signif(d_, 3))) else "no single feature lowers it"
}
for (f in FEATURES) {
v <- df[[f]][rows[i] + 1L]
r[[f]] <- if (is.na(v)) NULL else if (is.numeric(v)) v else as.character(v)
}
r
})
cs_publish(list(
title = "Nearest-neighbor outlier scores",
engine = do.call(cs_engine_info, as.list(ENGINE_PACKAGES)),
n = length(rows),
summary = sprintf("%d of %d rows (%.1f%%) are flagged as anomalies (%s ≥ %s).", sum(flags), length(rows),
100 * mean(flags), SCORE_LABEL, format(signif(threshold, 3))),
statistics = list(list(key = "n_flagged", label = "Anomalies", value = sum(flags), format = "integer"),
list(key = "threshold", label = "Threshold", value = threshold)),
tables = list(list(
key = "top", title = "Most anomalous rows",
columns = c(list(list(key = "rank", label = "Rank", type = "integer"), list(key = "row", label = "Row", type = "integer"),
list(key = "score", label = SCORE_LABEL, type = "number")),
if (!is.null(why)) list(list(key = "why", label = "Most unusual"), list(key = "drop", label = "Biggest score drop")) else list(),
lapply(FEATURES, function(f) list(key = f, label = f))),
rows = table_rows
)),
charts = list(cs_chart("scores", "anomaly-scores", paste(SCORE_LABEL, "distribution"), list(
score = cs_col(SCORE_LABEL, scores, "numeric"),
anomaly = cs_col("Anomaly", flags, "boolean")
), controls = list(threshold = threshold))),
values = values,
warnings = warnings,
artifacts = list(list(key = "labels", path = file.path(out, "labels.parquet"), format = "parquet"))
))
5 of 50 rows (10.0%) are flagged as anomalies (kth-neighbor distance ≥ 1.7).
- Anomalies
- 5
- Threshold
- 1.696
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | kth-neighbor distance | Most unusual | Biggest score drop | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|---|---|---|
| 1 | 2 | 2.360 | Rape = 44.5 (robust z +2.8); 40% of its tail score | Rape: falls 0.881 at its median | 10 | 263 | 48 | 44.500 |
| 2 | 33 | 2.075 | Assault = 337 (robust z +1.6); 43% of its tail score | Assault: falls 0.514 at its median | 13 | 337 | 45 | 16.100 |
| 3 | 28 | 1.946 | Rape = 46 (robust z +3.0); 45% of its tail score | Rape: falls 0.522 at its median | 12.200 | 252 | 81 | 46 |
| 4 | 9 | 1.767 | Assault = 335 (robust z +1.6); 35% of its tail score | Murder: falls 0.241 at its median | 15.400 | 335 | 80 | 31.900 |
| 5 | 5 | 1.696 | Rape = 40.6 (robust z +2.4); 29% of its tail score | UrbanPop: falls 0.257 at its median | 9 | 276 | 91 | 40.600 |
| 6 | 45 | 1.689 | UrbanPop = 32 (robust z -1.9); 36% of its tail score | UrbanPop: falls 0.654 at its median | 2.200 | 48 | 32 | 11.200 |
| 7 | 39 | 1.654 | Rape = 8.3 (robust z -1.4); 36% of its tail score | UrbanPop: falls 0.324 at its median | 3.400 | 174 | 87 | 8.300 |
| 8 | 24 | 1.643 | Murder = 16.1 (robust z +1.6); 39% of its tail score | Rape: falls 0.0783 at its median | 16.100 | 259 | 44 | 17.100 |
| 9 | 10 | 1.599 | Murder = 17.4 (robust z +1.9); 55% of its tail score | Murder: falls 0.479 at its median | 17.400 | 211 | 60 | 25.800 |
| 10 | 8 | 1.567 | Assault = 238 (robust z +0.7); 28% of its tail score | Assault: falls 0.703 at its median | 5.900 | 238 | 72 | 15.800 |
| 11 | 30 | 1.471 | UrbanPop = 89 (robust z +1.3); 60% of its tail score | UrbanPop: falls 0.841 at its median | 7.400 | 159 | 89 | 18.800 |
| 12 | 6 | 1.413 | Rape = 38.7 (robust z +2.2); 45% of its tail score | Rape: falls 0.355 at its median | 7.900 | 204 | 78 | 38.700 |
| 13 | 40 | 1.411 | Murder = 14.4 (robust z +1.3); 32% of its tail score | UrbanPop: falls 0.131 at its median | 14.400 | 279 | 48 | 22.500 |
| 14 | 11 | 1.398 | Assault = 46 (robust z -1.0); 46% of its tail score | Assault: falls 0.386 at its median | 5.300 | 46 | 83 | 20.200 |
| 15 | 42 | 1.365 | Murder = 13.2 (robust z +1.1); 37% of its tail score | Murder: falls 0.283 at its median | 13.200 | 188 | 59 | 26.900 |
| 16 | 13 | 1.357 | UrbanPop = 83 (robust z +1.0); 36% of its tail score | UrbanPop: falls 0.214 at its median | 10.400 | 249 | 83 | 24 |
| 17 | 43 | 1.346 | Murder = 12.7 (robust z +1.0); 33% of its tail score | Murder: falls 0.214 at its median | 12.700 | 201 | 80 | 25.500 |
| 18 | 31 | 1.346 | Rape = 32.1 (robust z +1.4); 32% of its tail score | Assault: falls 0.0137 at its median | 11.400 | 285 | 70 | 32.100 |
| 19 | 32 | 1.346 | UrbanPop = 86 (robust z +1.1); 38% of its tail score | UrbanPop: falls 0.262 at its median | 11.100 | 254 | 86 | 26.100 |
| 20 | 18 | 1.329 | Murder = 15.4 (robust z +1.5); 47% of its tail score | Murder: falls 0.0502 at its median | 15.400 | 249 | 66 | 22.200 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Nearest-neighbor outlier scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.knn_outlier 1.0.0 · spec 7df4f7819d6700bf
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.errors import cs_error
from codesplash.ml import anomaly as csanom
from codesplash.ml import anomaly_ext as csax
from codesplash.ml import embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "standard"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"Murder": "numeric",
"Assault": "numeric",
"UrbanPop": "numeric",
"Rape": "numeric",
},
levels={
},
impute=IMPUTE,
scale=SCALE,
)
fitted = design.fit(df)
X = fitted.transform(df) # numbers imputed / scaled; categories one-hot (missing → all zero)
rows = np.arange(len(df))
# %% Scores (twin: codesplashr::cs_ml_*; exact distances, k neighbors with ties broken by row order)
n = len(df)
ENGINE_PACKAGES = ("numpy", "pandas")
extra_values = {"neighbors": None, "perplexity": None} # null when the score doesn't use it
if n < 2:
cs_error("CS_E_TOO_FEW_ROWS", what="Nearest-neighbor scores", min=2, n=n)
k = min(5, n - 1)
extra_values["neighbors"] = k
METHOD = "kth"
scores = csax.knn_scores(X, k, METHOD)
SCORE_LABEL = "kth-neighbor distance"
rescore = lambda Q, where, col: csax.knn_query(X, k, METHOD, Q, where)
DEFAULT_CUTOFF = csax.auto_cutoff(scores, "kth")
# %% Flag anomalies
RULE = "share"
_cutoff = None
if _cutoff is None:
_cutoff = DEFAULT_CUTOFF # set by the including template (e.g. the χ² cutoff for MCD)
flags, threshold = csanom.flag(scores, RULE, 0.1, _cutoff)
order = np.lexsort((rows, -scores)) # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.knn_outlier/usarrests_kth/out-python")
labels = pd.DataFrame({"row": rows.astype(np.int64), "score": scores, "anomaly": flags})
labels.to_parquet(os.path.join(out, "labels.parquet"), index=False)
# %% Result
values = {
"n": len(rows),
"n_flagged": int(flags.sum()),
"threshold": float(threshold),
"score_check": csembed.checksum(scores, rows),
"score_max": float(scores.max()),
"score_mean": float(scores.mean()),
}
values.update(extra_values)
for rank, i in enumerate(order[:10], start=1):
values[f"top_row[{rank}]"] = int(rows[i])
values[f"top_score[{rank}]"] = float(scores[i])
top = order[:20]
# %% Why these rows (numeric features: robust z and the ECOD tail-score share; Phase 11 DS1)
from codesplash.ml import discover_ext as _dx
NUMERIC = ["Murder", "Assault", "UrbanPop", "Rape", ]
why = None
if NUMERIC:
_F = df.iloc[rows][NUMERIC].apply(pd.to_numeric, errors="coerce").to_numpy(dtype=np.float64)
_med = np.array([np.median(c[~np.isnan(c)]) if np.any(~np.isnan(c)) else 0.0 for c in _F.T])
_F = np.where(np.isnan(_F), _med[None, :], _F)
why = _dx.explain_rows(_F, top)
for rank in range(1, min(10, len(top)) + 1):
values[f"why_feature[{rank}]"] = int(why["feature"][rank - 1])
values[f"why_z[{rank}]"] = float(why["z"][rank - 1])
values[f"why_share[{rank}]"] = float(why["share"][rank - 1])
# Score drop: move one feature to its median, leave the rest of the row alone, and rescore.
_cols = [fitted.names.index(f) for f in NUMERIC]
drop = _dx.score_drops(X, top, _cols, scores, rescore)
for rank in range(1, min(10, len(top)) + 1):
values[f"drop_feature[{rank}]"] = int(drop["feature"][rank - 1])
values[f"drop_score[{rank}]"] = float(drop["drop"][rank - 1])
shown = df.iloc[rows[top]][FEATURES]
table_rows = []
for rank, (i, (_, rec)) in enumerate(zip(top, shown.iterrows()), start=1):
r = {"rank": rank, "row": int(rows[i]) + 1, "score": float(scores[i])}
if why is not None:
_j = int(why["feature"][rank - 1])
_share = why["share"][rank - 1]
r["why"] = f"{NUMERIC[_j]} = {_F[i, _j]:.4g} (robust z {why['z'][rank - 1]:+.1f})" + ("" if _share != _share else f"; {_share:.0%} of its tail score")
_d = float(drop["drop"][rank - 1])
r["drop"] = f"{NUMERIC[int(drop['feature'][rank - 1])]}: falls {_d:.3g} at its median" if _d > 0 else "no single feature lowers it"
for f in FEATURES:
v = rec[f]
r[f] = None if pd.isna(v) else (v if isinstance(v, (int, float)) else str(v)) # None, NaN, pd.NA, NaT
table_rows.append(r)
pct = flags.mean()
cs.publish({
"title": "Nearest-neighbor outlier scores",
"engine": cs.engine_info(*ENGINE_PACKAGES),
"n": len(rows),
"summary": f"{int(flags.sum())} of {len(rows)} rows ({pct:.1%}) are flagged as anomalies ({SCORE_LABEL} ≥ {threshold:.3g}).",
"statistics": [
{"key": "n_flagged", "label": "Anomalies", "value": int(flags.sum()), "format": "integer"},
{"key": "threshold", "label": "Threshold", "value": float(threshold)},
],
"tables": [{
"key": "top",
"title": "Most anomalous rows",
"columns": [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "row", "label": "Row", "type": "integer"},
{"key": "score", "label": SCORE_LABEL, "type": "number"}]
+ ([{"key": "why", "label": "Most unusual"}, {"key": "drop", "label": "Biggest score drop"}] if why is not None else [])
+ [{"key": f, "label": f} for f in FEATURES],
"rows": table_rows,
}],
"charts": [cs.chart("scores", "anomaly-scores", f"{SCORE_LABEL} distribution", {
"score": cs.col(SCORE_LABEL, scores, "numeric"),
"anomaly": cs.col("Anomaly", [bool(x) for x in flags], "boolean"),
}, controls={"threshold": float(threshold)})],
"values": values,
"warnings": warnings,
"artifacts": [{"key": "labels", "path": os.path.join(out, "labels.parquet"), "format": "parquet"}],
})
It's easy to explain: open a flagged row and show its neighbors. It's also blunt: a small, tight group of legitimate cases far from the rest scores high, and in many dimensions irrelevant columns make every distance look alike. Check how the ranking moves with .
A kNN score needs a cutoff
ExploreAExplorable · A score is not an alarm
How do you turn an anomaly score into alarms with a known false-alarm rate?
What share of new normal rows will raise an alarm (in %)?
Alarm rule
Calibrate on
1 means new normal rows look like the calibration rows.
- No alarm
- Alarm
- Calibration rows (dashed)
- New normal rows
- Planted anomalies
The cutoff comes from the calibration scores, not from the score's own scale. If calibration rows look like new normal rows, the share of normal rows past the cutoff stays near α.
Commit your prediction above to see the result
Make your prediction to see the result.
The score here is the mean distance to the nearest training rows. A fixed cutoff flags whatever share the score's scale happens to give; switch the rule to conformal to choose the false-alarm rate instead.
LOF and LoOP: density relative to neighbors
ReadLOFLocal outlier factorCompares a row's local density with its neighbors'; a value well above 1 means it sits in a sparser spot than they do. compares a row's local reachability density with its neighbors': . Near 1 means "as dense as my neighbors"; well above 1 means sparser. It's a ratio, not a p-value, and duplicates can make densities blow up.
LoOPLocal outlier probability (LoOP)A 0–1 outlier score from the same neighborhoods as LOF, scaled by how unusual the local density ratios are across the data. uses a probabilistic distance from the root mean squared neighbor distance, compares it with the neighbors', and maps the excess through an error function to a 0–1 scale. With a 0.5 cutoff on pima it flagged 22 rows. The scale looks like a probability; it becomes one only after you check it against labeled cases.
Where each idea stands in CodeSplash
Read| Entry | In CodeSplash |
|---|---|
| KDE (UCL046) | Runs in CodeSplash: Kernel density anomaly scores |
| Gaussian copula density (UCL047) | Partly runs in CodeSplash: Synthetic data — Gaussian copula reports train and held-out mean log density; no per-row anomaly score yet |
| LOF (UCL050) | Runs in CodeSplash: Local outlier factor |
| LoOP (UCL051) | Runs as an option of Local outlier factor: Score LoOP |
| MCD Mahalanobis (UCL058) | Runs in CodeSplash: Robust covariance (MCD) outliers |
| kNN distance (UCL061) | Runs in CodeSplash: Nearest-neighbor outlier scores, kth, mean or median |
Check your understanding
CheckpointCheck yourself
Why can't you reuse a KDE score cutoff from another dataset?
Show the answer
Answer: b
Change centimeters to millimeters, or add a column, and every density changes scale. Calibrate cutoffs on held-out normal rows of the same table, or flag a share.
Check yourself
How should you choose the KDE bandwidth for anomaly scoring?
Show the answer
Answer: a
Tuning on the evaluation anomalies and then reporting them as validation is double-dipping. Keep the evaluation set untouched.
Check yourself
A row's every value is ordinary on its own, but its copula log density is very low. What does that mean?
Show the answer
Answer: b
The copula's dependence part looks at ranks jointly. It catches unusual combinations that one-column checks miss.
Check yourself
What goes wrong when you apply the continuous copula formula to a column with many ties, like a 1–5 rating?
Show the answer
Answer: a
Discrete margins need their own treatment. Read copula densities on discrete columns as rough scores.
Check yourself
A row's LOF is 1.05. What does it say?
Show the answer
Answer: b
LOF is a ratio of neighbor density to own density. Values near 1 are typical; it isn't a probability.
Check yourself
LOF flags different rows with = 5 and = 30. Which is right?
Show the answer
Answer: b
The neighborhood size sets the scale of "local". Stable rankings across plausible k are more trustworthy.
Check yourself
A row has LoOP 0.95. Can you tell a manager it's 95% likely to be an anomaly?
Show the answer
Answer: b
LoOP's error-function mapping gives a probability-shaped scale, not a validated probability.
Check yourself
What does LoOP add over LOF?
Show the answer
Answer: b
LOF ratios are unbounded and data-dependent. LoOP normalizes the deviation, which helps comparison but doesn't calibrate it.
Check yourself
An ordinary Mahalanobis distance flags two rows; the MCD version flags fifteen. Why can that happen?
Show the answer
Answer: a
Robust location and scatter stop outliers from hiding themselves. Compare the two ellipses to see how much masking there was.
Check yourself
Normal data come from two quite different machine types. Why might MCD struggle?
Show the answer
Answer: b
MCD assumes one elliptical population. With several modes, use a local or mixture-based detector, or score each type separately.
Check yourself
A small, tight group of legitimate premium customers sits far from everyone else. How do kNN distance scores treat them?
Show the answer
Answer: b
With k bigger than the group, each member's k-th neighbor is outside it. Rare coherent groups can be normal yet distant.
Check yourself
Scoring the training rows, what must a kNN detector do with each row's own zero-distance match?
Show the answer
Answer: a
Including the row itself shifts every score by one neighbor and hides isolated points.
Do it on your own data
In the appUnder Spot anomalies, run Robust covariance (MCD) outliers for one population, Nearest-neighbor outlier scores or Local outlier factor for local oddness, and Kernel density anomaly scores for low-density rows. Flag a share, then compare which rows each method agrees on.
Concepts in this lesson