From score to alarm: thresholds, reference rows and who gets flagged
Every detector in this unit ranks rows; none of them raises alarms on its own. The checks that turn a ranking into an alarm you can defend, which settings only look like error rates, and why false alarms pile up on some groups.
What runs in CodeSplash
- UCL048Isolation Forest Runs in CodeSplash
- UCL055Histogram-Based Outlier Score (HBOS) Runs in CodeSplash
- UCL056One-class support vector machine Runs in CodeSplash
- UCL060Empirical Cumulative Distribution Outlier Detection (ECOD) Runs in CodeSplash
- UCL061K-nearest-neighbor distance detector Runs in CodeSplash
- Isolation forest Verified in Python and R
- ECOD anomaly scores Verified in Python and R
- One-class SVM Verified in Python and R
- Nearest-neighbor outlier scores Verified in Python and R
You will be able to
- Tell a score, a flag rule and a calibrated error rate apart
- Name the assumptions behind a calibrated false-alarm rate and the situations that break them
- Check false alarms by subgroup before deploying a detector
- Evaluate a detector with labels at an operating false-alarm level, without tuning on the test anomalies
A ranking is not an alarm
ReadA detector gives every row a score and sorts them. Then a flag rule draws a line:
- a share: flag the top 5%. The isolation forest on pima flagged 27 of 532 rows, and it would flag the same share of perfectly clean data;
- a cutoff: flag scores above a number, whose meaning depends on the method, the units and the data;
- a calibrated rate: flag rows whose score is rarer than a chosen share of normal scores.
Only the third says how often a normal row gets flagged. The first two are decisions that look like findings.
A cutoff that flags half the table
Read158 of 344 rows (45.9%) are flagged as anomalies (ECOD score ≥ 8).
- Anomalies
- 158
- Threshold
- 8
Plots
View data
| Anomaly | ECOD score |
|---|---|
| true | 10.018 |
| true | 8.444 |
| false | 7.315 |
| false | 6.341 |
| true | 9.548 |
| true | 10.440 |
| true | 9.531 |
| true | 8.868 |
| true | 10.477 |
| true | 9.550 |
| true | 8.811 |
| true | 10.016 |
| true | 8.878 |
| true | 11.791 |
| true | 12.797 |
| true | 9.599 |
| true | 8.405 |
| true | 9.424 |
| true | 11.957 |
| true | 12.037 |
| true | 10.713 |
| true | 9.181 |
| true | 8.888 |
| false | 7.419 |
| true | 8.199 |
| true | 9.152 |
| false | 7.707 |
| false | 6.437 |
| true | 11.553 |
| true | 8.668 |
| true | 9.438 |
| true | 10.149 |
| false | 6.996 |
| true | 8.197 |
| false | 7.242 |
| true | 9.388 |
| true | 8.672 |
| true | 8.588 |
| true | 9.984 |
| true | 8.650 |
| true | 9.214 |
| false | 6.233 |
| true | 8.979 |
| false | 7.064 |
| true | 8.388 |
| false | 7.203 |
| true | 8.592 |
| true | 10.424 |
| false | 7.951 |
| true | 9.966 |
| false | 6.779 |
| false | 7.052 |
| true | 8.285 |
| false | 6.572 |
| true | 9.282 |
| false | 6.051 |
| false | 6.864 |
| false | 6.209 |
| true | 8.849 |
| false | 7.308 |
First 60 of 344 rows.
Most anomalous rows
| Rank | Row | ECOD score | Most unusual | Biggest score drop | island | bill_len | bill_dep | flipper_len | sex |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 216 | 13.884 | flipper_len = 231 (robust z +2.1); 52% of its tail score | flipper_len: falls 5.18 at its median | Biscoe | 54.300 | 15.700 | 231 | male |
| 2 | 99 | 13.415 | bill_len = 33.1 (robust z -1.6); 51% of its tail score | bill_len: falls 4.46 at its median | Dream | 33.100 | 16.100 | 178 | female |
| 3 | 186 | 13.116 | bill_len = 59.6 (robust z +2.2); 56% of its tail score | bill_len: falls 5.15 at its median | Biscoe | 59.600 | 17 | 230 | male |
| 4 | 15 | 12.797 | bill_dep = 21.1 (robust z +1.7); 48% of its tail score | bill_dep: falls 3.39 at its median | Torgersen | 34.600 | 21.100 | 198 | male |
| 5 | 143 | 12.090 | bill_len = 32.1 (robust z -1.8); 66% of its tail score | bill_len: falls 5.15 at its median | Dream | 32.100 | 15.500 | 188 | female |
| 6 | 71 | 12.065 | bill_len = 33.5 (robust z -1.6); 62% of its tail score | bill_len: falls 4.05 at its median | Torgersen | 33.500 | 19 | 190 | female |
| 7 | 294 | 12.055 | bill_len = 58 (robust z +1.9); 59% of its tail score | bill_len: falls 4.46 at its median | Dream | 58 | 17.800 | 181 | female |
| 8 | 20 | 12.037 | bill_dep = 21.5 (robust z +1.9); 76% of its tail score | bill_dep: falls 5.18 at its median | Torgersen | 46 | 21.500 | 194 | male |
| 9 | 19 | 11.957 | bill_len = 34.4 (robust z -1.4); 54% of its tail score | bill_len: falls 3.36 at its median | Torgersen | 34.400 | 18.400 | 184 | female |
| 10 | 268 | 11.858 | flipper_len = 230 (robust z +2.0); 41% of its tail score | bill_len: falls 3.54 at its median | Biscoe | 55.100 | 16 | 230 | male |
| 11 | 308 | 11.857 | bill_dep = 20.8 (robust z +1.6); 45% of its tail score | bill_dep: falls 3.24 at its median | Dream | 54.200 | 20.800 | 201 | male |
| 12 | 14 | 11.791 | bill_dep = 21.2 (robust z +1.8); 64% of its tail score | bill_dep: falls 4.08 at its median | Torgersen | 38.600 | 21.200 | 191 | male |
| 13 | 29 | 11.553 | flipper_len = 172 (robust z -1.5); 66% of its tail score | flipper_len: falls 5.18 at its median | Biscoe | 37.900 | 18.600 | 172 | female |
| 14 | 254 | 11.458 | flipper_len = 228 (robust z +1.9); 37% of its tail score | bill_len: falls 4.05 at its median | Biscoe | 55.900 | 17 | 228 | male |
| 15 | 123 | 11.166 | flipper_len = 176 (robust z -1.3); 70% of its tail score | flipper_len: falls 4.08 at its median | Torgersen | 40.200 | 17 | 176 | female |
| 16 | 340 | 11.133 | bill_len = 55.8 (robust z +1.6); 56% of its tail score | bill_len: falls 3.77 at its median | Dream | 55.800 | 19.800 | 207 | male |
| 17 | 125 | 10.862 | bill_len = 35.2 (robust z -1.3); 51% of its tail score | bill_len: falls 2.59 at its median | Torgersen | 35.200 | 15.900 | 186 | female |
| 18 | 177 | 10.848 | bill_dep = 13.1 (robust z -1.9); 72% of its tail score | bill_dep: falls 5.18 at its median | Biscoe | 42.900 | 13.100 | 215 | female |
| 19 | 78 | 10.842 | bill_len = 37.2 (robust z -1.0); 32% of its tail score | flipper_len: falls 1.72 at its median | Torgersen | 37.200 | 19.400 | 184 | male |
| 20 | 314 | 10.817 | bill_dep = 20.7 (robust z +1.5); 47% of its tail score | bill_dep: falls 2.88 at its median | Dream | 52 | 20.700 | 210 | male |
The exact R script · R R version 4.5.1 (2025-06-13)
# ECOD anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ecod 1.3.0 · spec 48d0751a722f8efe
# Dataset: ml_penguins (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"
# 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_penguins.parquet", col_select = c("island", "bill_len", "bill_dep", "flipper_len", "sex"))), c("island", "bill_len", "bill_dep", "flipper_len", "sex"))
FEATURES <- c("island", "bill_len", "bill_dep", "flipper_len", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_penguins.parquet", col_select = FEATURES))
warnings <- list()
design <- cs_ml_design(
df, FEATURES,
kinds = list(
island = "categorical",
bill_len = "numeric",
bill_dep = "numeric",
flipper_len = "numeric",
sex = "categorical"
),
levels = list(
island = c("Biscoe", "Dream", "Torgersen"),
sex = c("female", "male")
),
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
scores <- cs_ml_ecod(X) # port of PyOD's ECOD
SCORE_LABEL <- "ECOD score"
ENGINE_PACKAGES <- c("codesplashr", "nanoparquet")
extra_values <- list()
rescore <- function(Q, where0, col0) cs_ml_ecod_rescore(X, scores, Q, where0, col0)
# %% Flag anomalies
RULE <- "cutoff"
cutoff_ <- 8
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.ecod/penguins_mixed_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("bill_len", "bill_dep", "flipper_len")
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 = "ECOD 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"))
))
158 of 344 rows (45.9%) are flagged as anomalies (ECOD score ≥ 8).
- Anomalies
- 158
- Threshold
- 8
To keep this page light, the plots are shown once, under the R tab.
Most anomalous rows
| Rank | Row | ECOD score | Most unusual | Biggest score drop | island | bill_len | bill_dep | flipper_len | sex |
|---|---|---|---|---|---|---|---|---|---|
| 1 | 216 | 13.884 | flipper_len = 231 (robust z +2.1); 52% of its tail score | flipper_len: falls 5.18 at its median | Biscoe | 54.300 | 15.700 | 231 | male |
| 2 | 99 | 13.415 | bill_len = 33.1 (robust z -1.6); 51% of its tail score | bill_len: falls 4.46 at its median | Dream | 33.100 | 16.100 | 178 | female |
| 3 | 186 | 13.116 | bill_len = 59.6 (robust z +2.2); 56% of its tail score | bill_len: falls 5.15 at its median | Biscoe | 59.600 | 17 | 230 | male |
| 4 | 15 | 12.797 | bill_dep = 21.1 (robust z +1.7); 48% of its tail score | bill_dep: falls 3.39 at its median | Torgersen | 34.600 | 21.100 | 198 | male |
| 5 | 143 | 12.090 | bill_len = 32.1 (robust z -1.8); 66% of its tail score | bill_len: falls 5.15 at its median | Dream | 32.100 | 15.500 | 188 | female |
| 6 | 71 | 12.065 | bill_len = 33.5 (robust z -1.6); 62% of its tail score | bill_len: falls 4.05 at its median | Torgersen | 33.500 | 19 | 190 | female |
| 7 | 294 | 12.055 | bill_len = 58 (robust z +1.9); 59% of its tail score | bill_len: falls 4.46 at its median | Dream | 58 | 17.800 | 181 | female |
| 8 | 20 | 12.037 | bill_dep = 21.5 (robust z +1.9); 76% of its tail score | bill_dep: falls 5.18 at its median | Torgersen | 46 | 21.500 | 194 | male |
| 9 | 19 | 11.957 | bill_len = 34.4 (robust z -1.4); 54% of its tail score | bill_len: falls 3.36 at its median | Torgersen | 34.400 | 18.400 | 184 | female |
| 10 | 268 | 11.858 | flipper_len = 230 (robust z +2.0); 41% of its tail score | bill_len: falls 3.54 at its median | Biscoe | 55.100 | 16 | 230 | male |
| 11 | 308 | 11.857 | bill_dep = 20.8 (robust z +1.6); 45% of its tail score | bill_dep: falls 3.24 at its median | Dream | 54.200 | 20.800 | 201 | male |
| 12 | 14 | 11.791 | bill_dep = 21.2 (robust z +1.8); 64% of its tail score | bill_dep: falls 4.08 at its median | Torgersen | 38.600 | 21.200 | 191 | male |
| 13 | 29 | 11.553 | flipper_len = 172 (robust z -1.5); 66% of its tail score | flipper_len: falls 5.18 at its median | Biscoe | 37.900 | 18.600 | 172 | female |
| 14 | 254 | 11.458 | flipper_len = 228 (robust z +1.9); 37% of its tail score | bill_len: falls 4.05 at its median | Biscoe | 55.900 | 17 | 228 | male |
| 15 | 123 | 11.166 | flipper_len = 176 (robust z -1.3); 70% of its tail score | flipper_len: falls 4.08 at its median | Torgersen | 40.200 | 17 | 176 | female |
| 16 | 340 | 11.133 | bill_len = 55.8 (robust z +1.6); 56% of its tail score | bill_len: falls 3.77 at its median | Dream | 55.800 | 19.800 | 207 | male |
| 17 | 125 | 10.862 | bill_len = 35.2 (robust z -1.3); 51% of its tail score | bill_len: falls 2.59 at its median | Torgersen | 35.200 | 15.900 | 186 | female |
| 18 | 177 | 10.848 | bill_dep = 13.1 (robust z -1.9); 72% of its tail score | bill_dep: falls 5.18 at its median | Biscoe | 42.900 | 13.100 | 215 | female |
| 19 | 78 | 10.842 | bill_len = 37.2 (robust z -1.0); 32% of its tail score | flipper_len: falls 1.72 at its median | Torgersen | 37.200 | 19.400 | 184 | male |
| 20 | 314 | 10.817 | bill_dep = 20.7 (robust z +1.5); 47% of its tail score | bill_dep: falls 2.88 at its median | Dream | 52 | 20.700 | 210 | male |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# ECOD anomaly scores
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.ecod 1.3.0 · spec 48d0751a722f8efe
# Dataset: ml_penguins (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 embed as csembed
# %% Data
IMPUTE = "median"
SCALE = "none"
# Infinite values stop the run before the design (registry/errors.yaml)
cs.check_finite_columns(pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=["island", "bill_len", "bill_dep", "flipper_len", "sex"]), ["island", "bill_len", "bill_dep", "flipper_len", "sex"])
FEATURES = ["island", "bill_len", "bill_dep", "flipper_len", "sex"]
df = pd.read_parquet("tests/parity/fixtures/ml_penguins.parquet", columns=FEATURES)
warnings = []
design = csml.Design.for_frame(
df,
FEATURES,
kinds={
"island": "categorical",
"bill_len": "numeric",
"bill_dep": "numeric",
"flipper_len": "numeric",
"sex": "categorical",
},
levels={
"island": ["Biscoe", "Dream", "Torgersen"],
"sex": ["female", "male"],
},
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
from pyod.models.ecod import ECOD
model = ECOD(n_jobs=1).fit(X)
scores = np.asarray(model.decision_scores_, dtype=np.float64)
SCORE_LABEL = "ECOD score"
ENGINE_PACKAGES = ("pyod", "numpy", "pandas")
extra_values = {}
from codesplash.ml import discover_ext as _dx_e
rescore = lambda Q, where, col: _dx_e.ecod_rescore(X, scores, Q, where, col)
# %% Flag anomalies
RULE = "cutoff"
_cutoff = 8
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.ecod/penguins_mixed_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 = ["bill_len", "bill_dep", "flipper_len", ]
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": "ECOD 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"}],
})
An ECOD cutoff of 8 on the penguins flagged 158 of 344 birds. ECOD sums one surprisal per column, so its scale grows with the number of columns: a cutoff that worked on a narrower table means nothing here.
The same goes for settings that sound like rates. An isolation forest's contamination only places the line. A one-class SVM's shapes the training fit; it doesn't promise a future false-alarm rate.
Calibrating against normal rows
ReadCalibration compares each row with reference rows you take to be normal. A row's conformal p-valueConformal p-value (anomaly)One plus the reference rows scoring at least as high as a row, divided by the reference count plus one. is the share of reference scores at least as high as its own (with a +1 in numerator and denominator). Flag rows with and each normal row is flagged at most a share of the time.
That promise rests on three conditions:
- the reference rows really are normal, or nearly so;
- new normal rows are exchangeableExchangeabilityUnder the null, any relabeling of the data is as likely as the one observed. Permutation tests rest on this. with them: same process, no ordering that matters;
- nothing about the threshold, bandwidth or was tuned on the rows you then report.
Lesson "Calibrated alerts" shows the mechanics; here we look at what breaks them.
Calibrate a score into alarms
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.
Conformal p-values set the cutoff from held-out normal rows, so about α of new normal rows raise alarms. Calibrate on the training rows instead, or shift the new data, and that promise breaks.
Winter reference, summer data
PredictPredict first
You calibrate a sensor detector on normal readings from winter, at α = 5%. In summer the machines run warmer but are fine. What happens to the false alarms?
Reveal
Many more than 5%. Summer readings aren't exchangeable with the winter reference, so normal summer rows look rare and get flagged. The guarantee only holds for rows from the same process. Recalibrate on recent normal data, or calibrate within each season.
Rows that aren't independent
ReadTime breaks exchangeability in quieter ways too. Neighboring readings are correlated, so one fault produces a burst of flagged rows: the false-alarm rate counts rows, not incidents. A slow drift moves every score until the reference no longer describes normal.
Group rows into incidents before you count alarms, recalibrate on a recent normal window, and watch the share of flags over time: a steady climb is drift, not a crime wave.
Who gets the false alarms?
ReadA rate that is fine overall can be unfair in detail. Per-column tail scores such as ECOD and HBOS flag values far into a column's tail, and a minority group whose normal values sit there (tall players, small shops, older patients) collects most of the false alarms. Distance scores do the same to a small, legitimate cluster far from the rest.
Before deploying, compare the share flagged in each group among rows you know are normal, with counts and intervals. If one group bears the alarms, calibrate within groups or use a detector that sees dependence.
Judging a detector with labels
ReadWhen some anomalies are labeled, evaluate the way you'll operate: precision and detection rate at the false-alarm level you can afford, not one overall AUC that averages over thresholds you'd never use. Keep the labeled test rows out of every choice, from to bandwidth to the detector itself.
Synthetic anomalies (shifted rows, injected noise) are a controlled check of mechanics, not evidence about the anomalies you care about. And a flag is a reason to look: review before anyone deletes or acts.
Where it runs in CodeSplash
Read| Idea | In CodeSplash |
|---|---|
| Share or cutoff flag rules | Runs in CodeSplash: Flag anomalies by on every detector |
| Conformal p-values, false-alarm or false discovery rate | Runs in CodeSplash: the Alerts tab of a detector run |
| False alarms by subgroup | Explained here: save the flags and compare groups among rows known to be normal |
| Incident grouping and drift checks | Explained here |
Check your understanding
CheckpointCheck yourself
An isolation forest flags 5% of your rows. What has it found?
Show the answer
Answer: b
The share is the flag rule you chose. To know how often normal rows get flagged, calibrate against reference rows.
Check yourself
You try ten tree counts and subsample sizes and keep the one that catches the most labeled frauds in your test set. What's wrong with reporting that catch rate?
Show the answer
Answer: a
Choose settings on separate data, then report on test rows that no choice ever saw.
Check yourself
An HBOS detector on store sales flags small rural stores far more often than others, though their sales are normal for their size. Why?
Show the answer
Answer: a
Per-column scores don't know what's normal for a subgroup. Compare flag rates by group among normal rows, and calibrate within groups if one bears the alarms.
Check yourself
What should an HBOS report include besides the overall flag count?
Show the answer
Answer: b
HBOS is a sum of per-column surprisals, so contributions and subgroup flag rates show what it is really reacting to.
Check yourself
A one-class SVM was trained with ν = 0.02. Your manager asks for the false-alarm rate in production. What do you say?
Show the answer
Answer: b
ν bounds training fractions under the optimization's assumptions. A false-alarm rate is a property of the threshold on new normal data.
Check yourself
The one-class SVM's boundary was fit last year. Production data have shifted slightly but are still normal. What do you expect?
Show the answer
Answer: a
A boundary describes the data it was fit on. Refit or recalibrate on recent normal data.
Check yourself
Why does an ECOD cutoff that suited a 4-column table flag far too much on a 9-column table?
Show the answer
Answer: b
Score scales depend on the method and the table. Flag a share, or calibrate the cutoff on normal rows of this table.
Check yourself
ECOD runs on minute-by-minute machine data. One fault produces sixty flagged minutes. What does the row-level false-alarm rate miss?
Show the answer
Answer: a
Calibration guarantees are about single rows. Group consecutive flags into incidents before reporting rates.
Check yourself
You calibrate a kNN distance detector using last month's rows as the reference. Which condition matters most for the false-alarm guarantee?
Show the answer
Answer: b
Conformal p-values assume the reference describes normal data exchangeable with new normal rows.
Check yourself
A kNN detector flags a tight group of legitimate wholesale customers. How should you find out before deploying?
Show the answer
Answer: b
Distance scores flag small, distant clusters even when they are normal. A subgroup check finds that before customers feel it.
Do it on your own data
In the appRun a detector under Spot anomalies, open its Alerts tab and pick reference rows you trust as normal. Then save the flags, compare flag rates across your main groups, and repeat with reference rows from a recent window.
Concepts in this lesson