Skip to content

Anomalies by density: kernel density scores

Score each row by how thin the data are around it, with a kernel density estimate. Learn to set the bandwidth, why the row is left out of its own estimate, and how a copula density finds unusual combinations.

Applied ~10 min5 steps

What runs in CodeSplash

You will be able to

  • Explain a kernel density estimate and the role of the bandwidth
  • Read a low-density score as a log density ratio
  • Explain why each row is left out of its own density
  • Tell an unusual value from an unusual combination of values

Read first

01

Put a bump on every row

Read

A kernel density estimate places a small normal bump on every row and adds them up. Where many rows sit close together the bumps pile up and the density is high. An isolated row sits on its own bump, so the density there is low.

f^(x)=1n∑i=1n∏c1hc ϕ ⁣(xc−xichc)\hat f(x) = \frac{1}{n} \sum_{i=1}^{n} \prod_{c} \frac{1}{h_c} \, \phi\!\left(\frac{x_c - x_{ic}}{h_c}\right)

The app's low-density scoreLow-density scoreMinus the row's leave-one-out log density: higher means fewer close neighbors in every direction at once. is minus the log of that density at each row. Each +1 means the density there is ee times thinner.

02

The bandwidth is the one choice

Read

Each column's bandwidth hch_c is a bandwidth factorBandwidth factorHow wide each row's Gaussian bump is, as a multiple of each column's SD; smaller is bumpier. times that column's spread. Scott's and Silverman's rules choose the factor from the number of rows and columns. A smaller factor makes the density bumpier, and when it's too small every row looks isolated.

Kernel density anomaly scoresRecorded · Python and R agreeRecorded 2026-11-25 · 79 values compared
R

27 of 532 rows (5.1%) are flagged as anomalies (Low-density score ≥ 13.1).

Anomalies
27
Threshold
13.144

Plots

Low-density score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyLow-density score
false7.160
false12.658
false8.962
false9.034
false6.870
false8.927
false7.096
true13.293
false9.601
false10.583
true21.917
false8.848
true14.525
true15.663
false9.868
false7.583
false8.201
false10.183
false9.176
false7.740
false6.926
false9.117
false9.090
false6.800
false6.667
false11.474
false7.001
false8.923
false7.841
false6.835
false9.023
false7.501
false7.819
false8.496
false9.183
false10.929
false8.379
false8.549
false8.617
false7.349
false9.930
false8.585
false8.391
false7.063
false6.950
false8.057
false7.704
false12.598
false8.061
false9.800
false7.298
false6.595
false8.396
false6.902
false6.712
false9.646
false8.427
false9.364
false9.555
true14.076

First 60 of 532 rows.

Most anomalous rows

RankRowLow-density scoreMost unusualBiggest score dropnpregglubpskinbmipedage
115753.975skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 42.4 at its median2197709934.7000.575062
239829.044ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 16.2 at its median0180786359.4002.42025
31121.917ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 11.2 at its median0137403543.1002.28833
427920.248bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 7 at its median01291104667.1000.319026
522118.697bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 7.28 at its median91711102445.4000.721054
640317.054age = 81 (robust z +6.0); 44% of its tail scoreage: falls 7.85 at its median9134743325.9000.460081
735816.494age = 65 (robust z +4.2); 31% of its tail scorebp: falls 6.16 at its median51031083739.2000.305065
849116.106bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 6.2 at its median10681062335.5000.285047
949215.876bmi = 57.3 (robust z +3.7); 33% of its tail scorebmi: falls 4.48 at its median31231003557.3000.880022
1025715.791bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 2.72 at its median1883042550.496026
111415.663npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 4.88 at its median129262727.6000.926044
1243215.163age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 3.26 at its median612990719.6000.582060
1321814.578ped = 1.39 (robust z +3.7); 27% of its tail scoreage: falls 3.19 at its median4111724737.1001.39056
141314.525age = 59 (robust z +3.5); 28% of its tail scoreage: falls 5.36 at its median1189602330.1000.398059
1520814.387bp = 30 (robust z -3.5); 35% of its tail scorebp: falls 6.27 at its median1103303843.3000.183033
166014.076bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.96 at its median81671064637.6000.165043
1711113.944bp = 110 (robust z +3.2); 36% of its tail scorebp: falls 4.19 at its median41891103128.5000.680037
1841713.666age = 58 (robust z +3.4); 21% of its tail scorebmi: falls 2.82 at its median0173783246.5001.15958
1953013.652age = 63 (robust z +3.9); 29% of its tail scoreage: falls 2.42 at its median10101764832.9000.171063
2027213.648npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 1.47 at its median17163724140.9000.817047
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"))
))
Python

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

RankRowLow-density scoreMost unusualBiggest score dropnpregglubpskinbmipedage
115753.975skin = 99 (robust z +6.7); 34% of its tail scoreskin: falls 42.4 at its median2197709934.7000.575062
239829.044ped = 2.42 (robust z +7.6); 26% of its tail scoreped: falls 16.2 at its median0180786359.4002.42025
31121.917ped = 2.288 (robust z +7.1); 29% of its tail scoreped: falls 11.2 at its median0137403543.1002.28833
427920.248bmi = 67.1 (robust z +5.2); 33% of its tail scorebmi: falls 7 at its median01291104667.1000.319026
522118.697bp = 110 (robust z +3.2); 28% of its tail scorebp: falls 7.28 at its median91711102445.4000.721054
640317.054age = 81 (robust z +6.0); 44% of its tail scoreage: falls 7.85 at its median9134743325.9000.460081
735816.494age = 65 (robust z +4.2); 31% of its tail scorebp: falls 6.16 at its median51031083739.2000.305065
849116.106bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 6.2 at its median10681062335.5000.285047
949215.876bmi = 57.3 (robust z +3.7); 33% of its tail scorebmi: falls 4.48 at its median31231003557.3000.880022
1025715.791bp = 30 (robust z -3.5); 30% of its tail scorebp: falls 2.72 at its median1883042550.496026
111415.663npreg = 12 (robust z +3.4); 19% of its tail scorenpreg: falls 4.88 at its median129262727.6000.926044
1243215.163age = 60 (robust z +3.6); 19% of its tail scoreskin: falls 3.26 at its median612990719.6000.582060
1321814.578ped = 1.39 (robust z +3.7); 27% of its tail scoreage: falls 3.19 at its median4111724737.1001.39056
141314.525age = 59 (robust z +3.5); 28% of its tail scoreage: falls 5.36 at its median1189602330.1000.398059
1520814.387bp = 30 (robust z -3.5); 35% of its tail scorebp: falls 6.27 at its median1103303843.3000.183033
166014.076bp = 106 (robust z +2.9); 26% of its tail scorebp: falls 3.96 at its median81671064637.6000.165043
1711113.944bp = 110 (robust z +3.2); 36% of its tail scorebp: falls 4.19 at its median41891103128.5000.680037
1841713.666age = 58 (robust z +3.4); 21% of its tail scorebmi: falls 2.82 at its median0173783246.5001.15958
1953013.652age = 63 (robust z +3.9); 29% of its tail scoreage: falls 2.42 at its median10101764832.9000.171063
2027213.648npreg = 17 (robust z +5.1); 36% of its tail scorenpreg: falls 1.47 at its median17163724140.9000.817047
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"}],
})

Try the same data with Silverman's rule or a fixed factor and watch which rows stay at the top. Rows that stay flagged whatever the bandwidth are the ones worth reviewing first.

Kernel density anomaly scoresRecorded · Python and R agreeRecorded 2026-11-25 · 79 values compared
R

5 of 50 rows (10.0%) are flagged as anomalies (Low-density score ≥ 6.48).

Anomalies
5
Threshold
6.480

Plots

Low-density score distributionHow unusual are the most anomalous rows compared with the rest, and where is the cut?
View data
AnomalyLow-density score
false4.951
true10.842
false5.432
false5.336
true6.495
false6.159
false4.824
false5.982
true6.755
false5.637
false5.659
false4.328
false4.845
false3.904
false4.104
false3.734
false5.143
false5.194
false4.319
false5.082
false4.792
false4.998
false4.182
false5.832
false4.899
false4.235
false3.880
true6.673
false4.158
false5.437
false4.767
false4.896
true6.480
false4.985
false4.151
false3.834
false4.942
false4.093
false6.022
false5.331
false4.441
false5.288
false5.211
false4.769
false5.779
false4.122
false4.565
false5.286
false4.404
false4.187

Most anomalous rows

RankRowLow-density scoreMost unusualBiggest score dropMurderAssaultUrbanPopRape
1210.842Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 5.31 at its median102634844.500
296.755Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 1.25 at its median15.4003358031.900
3286.673Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 1.75 at its median12.2002528146
456.495Rape = 40.6 (robust z +2.4); 29% of its tail scoreRape: falls 0.852 at its median92769140.600
5336.480Assault = 337 (robust z +1.6); 43% of its tail scoreRape: falls 0.39 at its median133374516.100
666.159Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 1.54 at its median7.9002047838.700
7396.022Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 1.06 at its median3.400174878.300
885.982Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 1.97 at its median5.9002387215.800
9245.832Murder = 16.1 (robust z +1.6); 39% of its tail scoreUrbanPop: falls 0.471 at its median16.1002594417.100
10455.779UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 1.63 at its median2.200483211.200
11115.659Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 1.34 at its median5.300468320.200
12105.637Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.723 at its median17.4002116025.800
13305.437UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 1.7 at its median7.4001598918.800
1435.432Rape = 31 (robust z +1.3); 28% of its tail scoreAssault: falls 0.315 at its median8.1002948031
1545.336UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 1.04 at its median8.8001905019.500
16405.331Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.534 at its median14.4002794822.500
17425.288Murder = 13.2 (robust z +1.1); 37% of its tail scoreMurder: falls 0.489 at its median13.2001885926.900
18485.286UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 0.858 at its median5.70081399.300
19435.211Murder = 12.7 (robust z +1.0); 33% of its tail scoreUrbanPop: falls 0.58 at its median12.7002018025.500
20185.194Murder = 15.4 (robust z +1.5); 47% of its tail scoreno single feature lowers it15.4002496622.200
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 d7ba4ccbf919618a
# 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
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"))  # ±Inf stops the run
IMPUTE <- "median"
SCALE <- "standard"
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

# %% 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, "silverman", 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.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.kde/usarrests_silverman/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 = "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"))
))
Python

5 of 50 rows (10.0%) are flagged as anomalies (Low-density score ≥ 6.48).

Anomalies
5
Threshold
6.480

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

Most anomalous rows

RankRowLow-density scoreMost unusualBiggest score dropMurderAssaultUrbanPopRape
1210.842Rape = 44.5 (robust z +2.8); 40% of its tail scoreRape: falls 5.31 at its median102634844.500
296.755Assault = 335 (robust z +1.6); 35% of its tail scoreMurder: falls 1.25 at its median15.4003358031.900
3286.673Rape = 46 (robust z +3.0); 45% of its tail scoreRape: falls 1.75 at its median12.2002528146
456.495Rape = 40.6 (robust z +2.4); 29% of its tail scoreRape: falls 0.852 at its median92769140.600
5336.480Assault = 337 (robust z +1.6); 43% of its tail scoreRape: falls 0.39 at its median133374516.100
666.159Rape = 38.7 (robust z +2.2); 45% of its tail scoreRape: falls 1.54 at its median7.9002047838.700
7396.022Rape = 8.3 (robust z -1.4); 36% of its tail scoreRape: falls 1.06 at its median3.400174878.300
885.982Assault = 238 (robust z +0.7); 28% of its tail scoreAssault: falls 1.97 at its median5.9002387215.800
9245.832Murder = 16.1 (robust z +1.6); 39% of its tail scoreUrbanPop: falls 0.471 at its median16.1002594417.100
10455.779UrbanPop = 32 (robust z -1.9); 36% of its tail scoreUrbanPop: falls 1.63 at its median2.200483211.200
11115.659Assault = 46 (robust z -1.0); 46% of its tail scoreAssault: falls 1.34 at its median5.300468320.200
12105.637Murder = 17.4 (robust z +1.9); 55% of its tail scoreMurder: falls 0.723 at its median17.4002116025.800
13305.437UrbanPop = 89 (robust z +1.3); 60% of its tail scoreUrbanPop: falls 1.7 at its median7.4001598918.800
1435.432Rape = 31 (robust z +1.3); 28% of its tail scoreAssault: falls 0.315 at its median8.1002948031
1545.336UrbanPop = 50 (robust z -0.9); 40% of its tail scoreUrbanPop: falls 1.04 at its median8.8001905019.500
16405.331Murder = 14.4 (robust z +1.3); 32% of its tail scoreUrbanPop: falls 0.534 at its median14.4002794822.500
17425.288Murder = 13.2 (robust z +1.1); 37% of its tail scoreMurder: falls 0.489 at its median13.2001885926.900
18485.286UrbanPop = 39 (robust z -1.5); 37% of its tail scoreUrbanPop: falls 0.858 at its median5.70081399.300
19435.211Murder = 12.7 (robust z +1.0); 33% of its tail scoreUrbanPop: falls 0.58 at its median12.7002018025.500
20185.194Murder = 15.4 (robust z +1.5); 47% of its tail scoreno single feature lowers it15.4002496622.200
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 d7ba4ccbf919618a
# 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, 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_usarrests.parquet", columns=["Murder", "Assault", "UrbanPop", "Rape"]), ["Murder", "Assault", "UrbanPop", "Rape"])  # ±Inf stops the run
IMPUTE = "median"
SCALE = "standard"
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))

# %% 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, "silverman", 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.1, _cutoff)
order = np.lexsort((rows, -scores))  # highest score first, ties by row
out = csml.out_dir("target/academy-parity/run-8142/discover.kde/usarrests_silverman/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": "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"}],
})
03

Leave the row out of its own estimate

Read

If a row's own bump counted toward its density, every row would look at least somewhat dense, and an isolated row would hide behind itself. So each row's density uses only the other rows (leave-one-out).

04

Unusual values, unusual combinations

Read

A kernel density score is high when a row is far from the others in any direction, including a single extreme value. Sometimes the interesting rows are ordinary in every column but combine them unusually: a tall person who weighs little, a young customer with a very long tenure.

The Gaussian copula in the Synthetic Data studio separates the two. It describes each column by its own distribution and the columns' dependence by a correlation matrix. Its log density, averaged over the training rows and over held-out rows, shows whether the dependence it learned carries over to rows it never saw.

Synthetic data — Gaussian copulaRecorded · Python and R agreeRecorded 2026-11-21 · 78 values compared · largest relative difference 9.8e-16
R

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

age: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceage
0.0230real18.950
0.0016real20.850
0.0049real22.750
0.0148real24.650
0.0148real26.550
0.0181real28.450
0.0197real30.350
0.0296real32.250
0.0362real34.150
0.0115real36.050
0.0362real37.950
0.0313real39.850
0.0296real41.750
0.0280real43.650
0.0280real45.550
0.0181real47.450
0.0164real49.350
0.0197real51.250
0.0362real53.150
0.0148real55.050
0.0164real56.950
0.0181real58.850
0.0082real60.750
0.0164real62.650
0.0049real64.550
0.0115real66.450
0.0066real68.350
0.0049real70.250
0.0016real72.150
0.0049real74.050
0.0164synthetic18.950
0synthetic20.850
0.0033synthetic22.750
0.0164synthetic24.650
0.0164synthetic26.550
0.0148synthetic28.450
0.0214synthetic30.350
0.0197synthetic32.250
0.0313synthetic34.150
0.0082synthetic36.050
0.0395synthetic37.950
0.0378synthetic39.850
0.0263synthetic41.750
0.0280synthetic43.650
0.0280synthetic45.550
0.0197synthetic47.450
0.0132synthetic49.350
0.0214synthetic51.250
0.0428synthetic53.150
0.0247synthetic55.050
0.0214synthetic56.950
0.0181synthetic58.850
0.0082synthetic60.750
0.0115synthetic62.650
0.0082synthetic64.550
0.0148synthetic66.450
0.0066synthetic68.350
0.0033synthetic70.250
0.0033synthetic72.150
0.0016synthetic74.050
annual income: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourceannual income
3.010e-6real6851.93
1.605e-5real10141.74
2.107e-5real13431.55
2.408e-5real16721.36
3.511e-5real20011.17
4.113e-5real23300.98
2.809e-5real26590.79
2.408e-5real29880.60
2.508e-5real33170.41
1.605e-5real36460.22
1.605e-5real39750.03
1.505e-5real43039.84
1.003e-5real46329.65
5.016e-6real49619.46
6.019e-6real52909.27
4.013e-6real56199.07
4.013e-6real59488.88
4.013e-6real62778.69
1.003e-6real66068.50
1.003e-6real69358.31
1.003e-6real72648.12
0real75937.93
1.003e-6real79227.74
1.003e-6real82517.55
0real85807.36
0real89097.17
0real92386.98
0real95676.79
0real98966.60
1.003e-6real102256.41
4.000e-6synthetic6851.93
9.999e-6synthetic10141.74
1.800e-5synthetic13431.55
3.100e-5synthetic16721.36
3.200e-5synthetic20011.17
3.200e-5synthetic23300.98
3.300e-5synthetic26590.79
2.000e-5synthetic29880.60
3.100e-5synthetic33170.41
2.100e-5synthetic36460.22
1.400e-5synthetic39750.03
9.999e-6synthetic43039.84
1.300e-5synthetic46329.65
5.999e-6synthetic49619.46
4.999e-6synthetic52909.27
4.000e-6synthetic56199.07
7.999e-6synthetic59488.88
6.999e-6synthetic62778.69
2.000e-6synthetic66068.50
0synthetic69358.31
0synthetic72648.12
9.999e-7synthetic75937.93
0synthetic79227.74
0synthetic82517.55
0synthetic85807.36
9.999e-7synthetic89097.17
0synthetic92386.98
0synthetic95676.79
0synthetic98966.60
9.999e-7synthetic102256.41
tenure_months: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcetenure_months
0.0938real0.7667
0.0224real2.300
0.0183real3.833
0.0306real5.367
0.0204real6.900
0.0265real8.433
0.0204real9.967
0.0530real11.500
0.0183real13.033
0.0510real14.567
0.0183real16.100
0.0367real17.633
0.0224real19.167
0.0448real20.700
0.0469real22.233
0.0082real23.767
0.0306real25.300
0.0061real26.833
0.0183real28.367
0.0041real29.900
0.0143real31.433
0.0061real32.967
0.0183real34.500
0.0020real36.033
0.0041real37.567
0real39.100
0.0061real40.633
0.0041real42.167
0.0020real43.700
0.0041real45.233
0.0836synthetic0.7667
0.0245synthetic2.300
0.0143synthetic3.833
0.0224synthetic5.367
0.0163synthetic6.900
0.0265synthetic8.433
0.0204synthetic9.967
0.0510synthetic11.500
0.0122synthetic13.033
0.0591synthetic14.567
0.0122synthetic16.100
0.0408synthetic17.633
0.0285synthetic19.167
0.0387synthetic20.700
0.0632synthetic22.233
0.0082synthetic23.767
0.0387synthetic25.300
0.0082synthetic26.833
0.0204synthetic28.367
0.0020synthetic29.900
0.0245synthetic31.433
0.0102synthetic32.967
0.0061synthetic34.500
0.0041synthetic36.033
0.0041synthetic37.567
0synthetic39.100
0.0020synthetic40.633
0.0041synthetic42.167
0.0061synthetic43.700
0synthetic45.233
signup: real vs syntheticDoes the synthetic data reproduce the shape of a numeric column?
View data
DensitySourcesignup
0.0005real17582.23
0.0007real17654.70
0.0005real17727.17
0.0005real17799.63
0.0004real17872.10
0.0005real17944.57
0.0006real18017.03
0.0004real18089.50
0.0005real18161.97
0.0005real18234.43
0.0001real18306.90
0.0009real18379.37
0.0006real18451.83
0.0003real18524.30
0.0005real18596.77
0.0004real18669.23
0.0002real18741.70
0.0005real18814.17
0.0006real18886.63
0.0005real18959.10
0.0005real19031.57
0.0005real19104.03
0.0003real19176.50
0.0006real19248.97
0.0004real19321.43
0.0003real19393.90
0.0002real19466.37
0.0005real19538.83
0.0003real19611.30
0.0004real19683.77
0.0006synthetic17582.23
0.0006synthetic17654.70
0.0004synthetic17727.17
0.0005synthetic17799.63
0.0005synthetic17872.10
0.0005synthetic17944.57
0.0006synthetic18017.03
0.0005synthetic18089.50
0.0007synthetic18161.97
0.0005synthetic18234.43
0.0002synthetic18306.90
0.0010synthetic18379.37
0.0009synthetic18451.83
0.0004synthetic18524.30
0.0003synthetic18596.77
0.0003synthetic18669.23
0.0001synthetic18741.70
0.0005synthetic18814.17
0.0007synthetic18886.63
0.0004synthetic18959.10
0.0004synthetic19031.57
0.0003synthetic19104.03
0.0004synthetic19176.50
0.0006synthetic19248.97
0.0003synthetic19321.43
0.0004synthetic19393.90
0.0002synthetic19466.37
0.0002synthetic19538.83
0.0002synthetic19611.30
0.0003synthetic19683.77
plan: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
planShareSource
basic0.3563real
plus0.3969real
premium0.2469real
basic0.3031synthetic
plus0.4031synthetic
premium0.2938synthetic
region: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
regionShareSource
east0.2848real
north0.2718real
south0.3042real
west0.1392real
east0.2754synthetic
north0.2656synthetic
south0.3115synthetic
west0.1475synthetic
churned: real vs syntheticDoes the synthetic data keep the category proportions of the real data?
View data
churnedShareSource
false0.7688real
true0.2313real
false0.7250synthetic
true0.2750synthetic
Correlation difference (real − synthetic)What do the values of a square or rectangular result matrix look like at a glance?
View data
ColumnColumnDifference
ageage0
annual incomeage−0.0395
tenure_monthsage0.0251
signupage0.0161
visitsage0.0482
ageannual income−0.0395
annual incomeannual income0
tenure_monthsannual income−0.0986
signupannual income0.0416
visitsannual income0.0930
agetenure_months0.0251
annual incometenure_months−0.0986
tenure_monthstenure_months0
signuptenure_months0.0056
visitstenure_months−0.0217
agesignup0.0161
annual incomesignup0.0416
tenure_monthssignup0.0056
signupsignup0
visitssignup−0.0303
agevisits0.0482
annual incomevisits0.0930
tenure_monthsvisits−0.0217
signupvisits−0.0303
visitsvisits0

Real vs synthetic, column by column

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.144.19 ± 12.60.0531Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+043.043e+04 ± 1.47e+040.0508Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.7 ± 10.40.0500Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 40.3%0.0531total variation
regioncategoricalsouth 30.4%south 31.1%0.0157total variation
churnedbooleanfalse 76.9%false 72.5%0.0437total variation
signuptemporal2020-11-05 ± 621 days2020-08-22 ± 593 days0.0844Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.469 ± 2.140.0219Kolmogorov–Smirnov D

Copula correlations (normal scores)

Columnageannual incometenure_monthsplanregionchurnedsignupvisits
age10.31610.72290.1714−0.0043−0.0816−0.02890.0342
annual income0.316110.18550.6503−0.1323−0.0202−0.02440.2147
tenure_months0.72290.185510.15150.0518−0.1174−0.04130.0361
plan0.17140.65030.15151−0.0928−0.1387−0.06240.3428
region−0.0043−0.13230.0518−0.092810.08500.00780.0240
churned−0.0816−0.0202−0.1174−0.13870.085010.0535−0.0268
signup−0.0289−0.0244−0.0413−0.06240.00780.05351−0.0207
visits0.03420.21470.03610.34280.0240−0.0268−0.02071
  • 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
)
Python

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

ColumnKindRealSyntheticDistanceMeasure
agenumeric43.14 ± 13.144.19 ± 12.60.0531Kolmogorov–Smirnov D
annual incomenumeric2.929e+04 ± 1.43e+043.043e+04 ± 1.47e+040.0508Kolmogorov–Smirnov D
tenure_monthsnumeric15 ± 10.715.7 ± 10.40.0500Kolmogorov–Smirnov D
plancategoricalplus 39.7%plus 40.3%0.0531total variation
regioncategoricalsouth 30.4%south 31.1%0.0157total variation
churnedbooleanfalse 76.9%false 72.5%0.0438total variation
signuptemporal2020-11-05 ± 621 days2020-08-22 ± 593 days0.0844Kolmogorov–Smirnov D
visitsnumeric3.394 ± 2.093.469 ± 2.140.0219Kolmogorov–Smirnov D

Copula correlations (normal scores)

Columnageannual incometenure_monthsplanregionchurnedsignupvisits
age10.31610.72290.1714−0.0043−0.0816−0.02890.0342
annual income0.316110.18550.6503−0.1323−0.0202−0.02440.2147
tenure_months0.72290.185510.15150.0518−0.1174−0.04130.0361
plan0.17140.65030.15151−0.0928−0.1387−0.06240.3428
region−0.0043−0.13230.0518−0.092810.08500.00780.0240
churned−0.0816−0.0202−0.1174−0.13870.085010.0535−0.0268
signup−0.0289−0.0244−0.0413−0.06240.00780.05351−0.0207
visits0.03420.21470.03610.34280.0240−0.0268−0.02071
  • 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,
)
05

Check your understanding

Checkpoint

Check yourself

You halve the bandwidth factor. What happens to the scores?

Show the answer

Answer: b

Narrow bumps only reach close neighbors, so rows without very close neighbors get low densities, which means high scores.

Check yourself

Why is each row left out of its own density estimate?

Show the answer

Answer: b

With its own bump counted, every row looks somewhat dense. Leaving it out measures how many other rows are close.

Check yourself

Row A scores 9.0 and row B scores 7.0. How do their densities compare?

Show the answer

Answer: a

The score is minus the log density, so a difference of 2 means a density ratio of e2e^2.

Check yourself

The copula's mean log density is much lower on held-out rows than on the training rows. What does it suggest?

Show the answer

Answer: b

The copula log density measures how usual each row's combination of values is under the learned correlations, so a gap between training and held-out rows points to correlations that don't generalize.

Concepts in this lesson