HEvaluate predictions · evaluate.ood
Evaluate out-of-distribution detection
How well does a score separate rows unlike the training data (out-of-distribution) from familiar ones?
Treats the out-of-distribution rows as the class to catch and a larger score as "more likely out". Reports the AUROC with DeLong's interval, the false-positive rate when the threshold catches a target share (95% by default) of the out-of-distribution rows, and the area under the precision–recall curve with either class as positive.
A real result
Example “Mahalanobis”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
AUROC 0.949 (95% CI 0.918 to 0.981); catching 96.0% of the 50 out-of-distribution rows flags 24.0% of the 100 familiar ones. AUPR-out 0.918, AUPR-in 0.975.
- AUROC
- 0.9494
- FPR at 95% TPR
- 0.2400
- AUPR-out
- 0.9182
- p (AUROC = 0.5)
- < .001
Plots
View data
| False-positive rate (familiar rows flagged) | Catches 95% | True-positive rate (out-of-distribution rows caught) |
|---|---|---|
| 0 | false | 0 |
| 0 | false | 0.0200 |
| 0 | false | 0.0400 |
| 0 | false | 0.0600 |
| 0 | false | 0.0800 |
| 0 | false | 0.1000 |
| 0 | false | 0.1200 |
| 0 | false | 0.1400 |
| 0 | false | 0.1600 |
| 0 | false | 0.1800 |
| 0 | false | 0.2000 |
| 0 | false | 0.2200 |
| 0 | false | 0.2400 |
| 0 | false | 0.2600 |
| 0 | false | 0.2800 |
| 0 | false | 0.3000 |
| 0 | false | 0.3200 |
| 0 | false | 0.3400 |
| 0 | false | 0.3600 |
| 0 | false | 0.3800 |
| 0 | false | 0.4000 |
| 0 | false | 0.4200 |
| 0 | false | 0.4400 |
| 0 | false | 0.4600 |
| 0 | false | 0.4800 |
| 0 | false | 0.5000 |
| 0.0100 | false | 0.5000 |
| 0.0100 | false | 0.5200 |
| 0.0100 | false | 0.5400 |
| 0.0100 | false | 0.5600 |
| 0.0100 | false | 0.5800 |
| 0.0100 | false | 0.6000 |
| 0.0100 | false | 0.6200 |
| 0.0100 | false | 0.6400 |
| 0.0200 | false | 0.6400 |
| 0.0200 | false | 0.6600 |
| 0.0200 | false | 0.6800 |
| 0.0200 | false | 0.7200 |
| 0.0200 | false | 0.7400 |
| 0.0300 | false | 0.7400 |
| 0.0400 | false | 0.7400 |
| 0.0500 | false | 0.7400 |
| 0.0600 | false | 0.7400 |
| 0.0600 | false | 0.7600 |
| 0.0700 | false | 0.7600 |
| 0.0800 | false | 0.7600 |
| 0.0800 | false | 0.7800 |
| 0.0800 | false | 0.8000 |
| 0.0900 | false | 0.8000 |
| 0.1000 | false | 0.8000 |
| 0.1100 | false | 0.8000 |
| 0.1100 | false | 0.8200 |
| 0.1200 | false | 0.8200 |
| 0.1300 | false | 0.8200 |
| 0.1400 | false | 0.8200 |
| 0.1400 | false | 0.8400 |
| 0.1500 | false | 0.8400 |
| 0.1600 | false | 0.8400 |
| 0.1600 | false | 0.8600 |
| 0.1700 | false | 0.8600 |
First 60 of 150 rows.
View data
| Positive class | Precision | Recall |
|---|---|---|
| Out-of-distribution | 1 | 0.0200 |
| Out-of-distribution | 1 | 0.0400 |
| Out-of-distribution | 1 | 0.0600 |
| Out-of-distribution | 1 | 0.0800 |
| Out-of-distribution | 1 | 0.1000 |
| Out-of-distribution | 1 | 0.1200 |
| Out-of-distribution | 1 | 0.1400 |
| Out-of-distribution | 1 | 0.1600 |
| Out-of-distribution | 1 | 0.1800 |
| Out-of-distribution | 1 | 0.2000 |
| Out-of-distribution | 1 | 0.2200 |
| Out-of-distribution | 1 | 0.2400 |
| Out-of-distribution | 1 | 0.2600 |
| Out-of-distribution | 1 | 0.2800 |
| Out-of-distribution | 1 | 0.3000 |
| Out-of-distribution | 1 | 0.3200 |
| Out-of-distribution | 1 | 0.3400 |
| Out-of-distribution | 1 | 0.3600 |
| Out-of-distribution | 1 | 0.3800 |
| Out-of-distribution | 1 | 0.4000 |
| Out-of-distribution | 1 | 0.4200 |
| Out-of-distribution | 1 | 0.4400 |
| Out-of-distribution | 1 | 0.4600 |
| Out-of-distribution | 1 | 0.4800 |
| Out-of-distribution | 1 | 0.5000 |
| Out-of-distribution | 0.9615 | 0.5000 |
| Out-of-distribution | 0.9630 | 0.5200 |
| Out-of-distribution | 0.9643 | 0.5400 |
| Out-of-distribution | 0.9655 | 0.5600 |
| Out-of-distribution | 0.9667 | 0.5800 |
| Out-of-distribution | 0.9677 | 0.6000 |
| Out-of-distribution | 0.9688 | 0.6200 |
| Out-of-distribution | 0.9697 | 0.6400 |
| Out-of-distribution | 0.9412 | 0.6400 |
| Out-of-distribution | 0.9429 | 0.6600 |
| Out-of-distribution | 0.9444 | 0.6800 |
| Out-of-distribution | 0.9474 | 0.7200 |
| Out-of-distribution | 0.9487 | 0.7400 |
| Out-of-distribution | 0.9250 | 0.7400 |
| Out-of-distribution | 0.9024 | 0.7400 |
| Out-of-distribution | 0.8810 | 0.7400 |
| Out-of-distribution | 0.8605 | 0.7400 |
| Out-of-distribution | 0.8636 | 0.7600 |
| Out-of-distribution | 0.8444 | 0.7600 |
| Out-of-distribution | 0.8261 | 0.7600 |
| Out-of-distribution | 0.8298 | 0.7800 |
| Out-of-distribution | 0.8333 | 0.8000 |
| Out-of-distribution | 0.8163 | 0.8000 |
| Out-of-distribution | 0.8000 | 0.8000 |
| Out-of-distribution | 0.7843 | 0.8000 |
| Out-of-distribution | 0.7885 | 0.8200 |
| Out-of-distribution | 0.7736 | 0.8200 |
| Out-of-distribution | 0.7593 | 0.8200 |
| Out-of-distribution | 0.7455 | 0.8200 |
| Out-of-distribution | 0.7500 | 0.8400 |
| Out-of-distribution | 0.7368 | 0.8400 |
| Out-of-distribution | 0.7241 | 0.8400 |
| Out-of-distribution | 0.7288 | 0.8600 |
| Out-of-distribution | 0.7167 | 0.8600 |
| Out-of-distribution | 0.7213 | 0.8800 |
First 60 of 298 rows.
View data
| Rows | score_maha |
|---|---|
| Familiar | 1.245 |
| Familiar | 2.456 |
| Familiar | 1.554 |
| Familiar | 2.323 |
| Familiar | 1.503 |
| Familiar | 2.978 |
| Familiar | 2.624 |
| Familiar | 1.249 |
| Familiar | 3.441 |
| Familiar | 3.288 |
| Familiar | 2.520 |
| Familiar | 2.640 |
| Familiar | 3.088 |
| Familiar | 3.700 |
| Familiar | 7.763 |
| Familiar | 9.118 |
| Familiar | 6.577 |
| Familiar | 1.616 |
| Familiar | 3.789 |
| Familiar | 2.375 |
| Familiar | 3.011 |
| Familiar | 2.790 |
| Familiar | 3.499 |
| Familiar | 2.791 |
| Familiar | 7.101 |
| Familiar | 2.528 |
| Familiar | 1.456 |
| Familiar | 1.534 |
| Familiar | 1.733 |
| Familiar | 2.517 |
| Familiar | 2.029 |
| Familiar | 4.669 |
| Familiar | 8.438 |
| Familiar | 5.793 |
| Familiar | 1.667 |
| Familiar | 2.881 |
| Familiar | 4.612 |
| Familiar | 3.349 |
| Familiar | 3.114 |
| Familiar | 1.302 |
| Familiar | 2.176 |
| Familiar | 12.495 |
| Familiar | 3.144 |
| Familiar | 7.444 |
| Familiar | 3.718 |
| Familiar | 2.804 |
| Familiar | 3.923 |
| Familiar | 1.976 |
| Familiar | 2.195 |
| Familiar | 1.231 |
| Familiar | 7.428 |
| Familiar | 3.094 |
| Familiar | 5.657 |
| Familiar | 3.631 |
| Familiar | 3.459 |
| Familiar | 4.361 |
| Familiar | 4.670 |
| Familiar | 4.330 |
| Familiar | 4.901 |
| Familiar | 6.899 |
First 60 of 150 rows.
Assumptions
- Scores come from a fitted detector — Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric.
- Enough rows of each kind — 50 out-of-distribution and 100 familiar rows.
Detection metrics
| Metric | Value | 95% CI low | 95% CI high | Chance level |
|---|---|---|---|---|
| AUROC | 0.9494 | 0.9183 | 0.9805 | 0.5000 |
| FPR at 95% TPR | 0.2400 | — | — | 0.9500 |
| AUPR-out (out-of-distribution positive) | 0.9182 | — | — | 0.3333 |
| AUPR-in (familiar positive) | 0.9746 | — | — | 0.6667 |
Threshold 4.93678: rows with a score ≥ it are flagged (TPR 96.0%). DeLong interval for the AUROC.
- Out-of-distribution: split = out. Larger scores mean more likely out-of-distribution.
AUROC 0.949 (95% CI 0.918 to 0.981); catching 96.0% of the 50 out-of-distribution rows flags 24.0% of the 100 familiar ones. AUPR-out 0.918, AUPR-in 0.975.
- AUROC
- 0.9494
- FPR at 95% TPR
- 0.2400
- AUPR-out
- 0.9182
- p (AUROC = 0.5)
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Scores come from a fitted detector — Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric.
- Enough rows of each kind — 50 out-of-distribution and 100 familiar rows.
Detection metrics
| Metric | Value | 95% CI low | 95% CI high | Chance level |
|---|---|---|---|---|
| AUROC | 0.9494 | 0.9183 | 0.9805 | 0.5000 |
| FPR at 95% TPR | 0.2400 | — | — | 0.9500 |
| AUPR-out (out-of-distribution positive) | 0.9182 | — | — | 0.3333 |
| AUPR-in (familiar positive) | 0.9746 | — | — | 0.6667 |
Threshold 4.93678: rows with a score ≥ it are flagged (TPR 96.0%). DeLong interval for the AUROC.
- Out-of-distribution: split = out. Larger scores mean more likely out-of-distribution.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Mahalanobisevp_ood · label: split · score: score_maha
- Petal booleanevp_ood · label: is_out · score: score_petal
- Tied scoresevp_ood · label: split · score: score_tied
- Lower directionevp_ood · label: split · score: score_maha
- Degenerate single levelevp_ood · label: split · score: score_maha
- Degenerate tiesevp_ood · label: split · score: score_maha
In the guides
Where it sits in the decision guides
- Anomaly detection · DS & ML Decision Guide · Discover — find structure without labels
- Predict: regression MAE, RMSE, R²; classification accuracy, precision, recall, F1, AUC; calibration, lift, log loss · DS & ML Decision Guide · How to evaluate — common metrics by question type
What you need
- Detection scorenumeric · 1 column
- The score that should flag unfamiliar rows (a distance, an anomaly score, 1 − the top predicted probability…).
- In or out of distributioncategorical / boolean · 1 column · 2–2 levels
- Which rows really are out-of-distribution (two levels).
Choices you make
hypothesis
- Out-of-distribution leveldefault —
The level that marks out-of-distribution rows (default the last stored level — true for true/false columns).
- Larger scores meandefault higher
Whether a larger score means "more likely out-of-distribution" (a distance) or "more familiar" (a confidence).
- More likely out-of-distribution(default) — Distances, anomaly scores and uncertainty: the larger, the stranger.
- More familiar — Confidence or likelihood: the score is negated before evaluation.
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
statistics
- Share of out-of-distribution rows to catchdefault 0.95
The false-positive rate is read where the threshold flags at least this share of the out-of-distribution rows (95% is the usual benchmark).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Scores come from a fitted detector
The detector and its threshold should be fixed before seeing these rows; tuning on them flatters every metric.
Enough rows of each kind
With fewer than about 20 out-of-distribution or 20 familiar rows the false-positive rate at a target catch rate is very noisy.
What it reports
- Tests: The score separates the two kinds of rows (AUROC differs from 0.5)
- n
- All rows, the familiar (in-distribution) rows, the out-of-distribution rows and their share.
- n_in
- All rows, the familiar (in-distribution) rows, the out-of-distribution rows and their share.
- n_out
- All rows, the familiar (in-distribution) rows, the out-of-distribution rows and their share.
- ood_level
- Which label level marks out-of-distribution rows, and whether larger scores mean stranger (higher) or more familiar (lower).
- direction
- Which label level marks out-of-distribution rows, and whether larger scores mean stranger (higher) or more familiar (lower).
- prevalence_out
- All rows, the familiar (in-distribution) rows, the out-of-distribution rows and their share.
- auroc
- Chance a random out-of-distribution row scores stranger than a random familiar one, with DeLong's SE, interval and test of 0.5.
- auroc_se
- Chance a random out-of-distribution row scores stranger than a random familiar one, with DeLong's SE, interval and test of 0.5.
- auroc_low
- Chance a random out-of-distribution row scores stranger than a random familiar one, with DeLong's SE, interval and test of 0.5.
- auroc_high
- Chance a random out-of-distribution row scores stranger than a random familiar one, with DeLong's SE, interval and test of 0.5.
- auroc_p
- Chance a random out-of-distribution row scores stranger than a random familiar one, with DeLong's SE, interval and test of 0.5.
- target_tpr
- Share of familiar rows flagged when the threshold catches the target share of out-of-distribution rows (95% by default).
- threshold
- Share of familiar rows flagged when the threshold catches the target share of out-of-distribution rows (95% by default).
- tpr_at_threshold
- Share of familiar rows flagged when the threshold catches the target share of out-of-distribution rows (95% by default).
- fpr_at_tpr
- Share of familiar rows flagged when the threshold catches the target share of out-of-distribution rows (95% by default).
- tnr_at_tpr
- Share of familiar rows flagged when the threshold catches the target share of out-of-distribution rows (95% by default).
- aupr_out
- Average precision with out-of-distribution rows as positives (out) or familiar rows as positives (in); chance equals the share.
- aupr_in
- Average precision with out-of-distribution rows as positives (out) or familiar rows as positives (in); chance equals the share.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
The exact script CodeSplash ran for example “Mahalanobis” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Evaluate out-of-distribution detection
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ood 1.0.0 · spec fffdf59d46b92863
# Dataset: evp_ood (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_groups
from codesplash.evaluate import ood # thresholds, FPR at a target TPR, average precision (twin: codesplashr cs_eval_*)
from codesplash.stats import roc # AUROC with DeLong's SE (twin: cs_auc_delong)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/evp_ood.parquet", columns=["score_maha", "split"])
n_input = len(df)
df["split"] = pd.Categorical(df["split"], categories=["in", "out"]) # stored level order
df = df.dropna(subset=["score_maha", "split"]) # listwise deletion over the analysis columns
df["split"] = df["split"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["score_maha", "split"]) # infinite values stop the run (registry/errors.yaml)
# %% Scores
sc_col, lc = "score_maha", "split"
present = [str(v) for v in df[lc].cat.categories] # levels with data, in stored order
check_groups(df[lc], lc, minimum=2, exactly=2)
out_level = present[-1] # default: the last level ("true")
direction = "higher"
raw = df[sc_col].to_numpy(dtype=float)
s = raw if direction == "higher" else -raw # larger = more likely out-of-distribution
pos = (df[lc].astype(str) == out_level).to_numpy()
n, n_out = int(pos.size), int(pos.sum())
n_in = n - n_out
target = 0.95
conf = 0.95
# %% Detection
dl = roc.auc_delong(s[pos], s[~pos], conf)
op = ood.fpr_at_tpr(s, pos, target)
threshold = op["threshold"] if direction == "higher" else -op["threshold"]
aupr_out = ood.average_precision(s, pos)
aupr_in = ood.average_precision(-s, ~pos)
# %% Assumptions
small = min(n_in, n_out) < 20
assumptions = [
{"key": "held_out", "label": "Scores come from a fitted detector", "status": "info",
"detail": "Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric."},
{"key": "sample_size", "label": "Enough rows of each kind", "status": "warn" if small else "pass",
"detail": f"{n_out} out-of-distribution and {n_in} familiar rows" + ("; the rates are noisy with fewer than 20 of either." if small else ".")},
]
if dl["auc"] < 0.5:
warnings.append("AUROC is below 0.5: the score ranks familiar rows as stranger than the out-of-distribution ones. Check the direction setting.")
# %% Result
pct = f"{conf:.0%}"
values = {
"n": n, "n_in": n_in, "n_out": n_out, "ood_level": out_level, "direction": direction, "prevalence_out": n_out / n,
"auroc": dl["auc"], "auroc_se": dl["se"], "auroc_low": dl["low"], "auroc_high": dl["high"], "auroc_p": dl["p"],
"target_tpr": target, "threshold": threshold, "tpr_at_threshold": op["tpr"], "fpr_at_tpr": op["fpr"], "tnr_at_tpr": 1 - op["fpr"],
"aupr_out": aupr_out, "aupr_in": aupr_in,
}
rc = ood.roc_curve(s, pos)
keep = ood.thin(rc["tpr"].size)
chosen = np.zeros(rc["tpr"].size, dtype=bool)
chosen[1 + int(np.flatnonzero(rc["threshold"] == op["threshold"])[0])] = True # the operating point (index 0 is the (0, 0) start)
keep = np.union1d(keep, np.flatnonzero(chosen))
pr_out, pr_in = ood.pr_curve(s, pos), ood.pr_curve(-s, ~pos)
ko, ki = ood.thin(pr_out["recall"].size), ood.thin(pr_in["recall"].size)
charts = [
cs.chart("roc", "roc-curve", f"ROC curve (AUROC {dl['auc']:.3f})", {
"fpr": cs.col("False-positive rate (familiar rows flagged)", rc["fpr"][keep]),
"tpr": cs.col("True-positive rate (out-of-distribution rows caught)", rc["tpr"][keep]),
"optimal": cs.col(f"Catches {target:.0%}", chosen[keep], "boolean")}),
cs.chart("pr", "pr-curve", "Precision–recall, each class as positive", {
"recall": cs.col("Recall", np.concatenate([pr_out["recall"][ko], pr_in["recall"][ki]])),
"precision": cs.col("Precision", np.concatenate([pr_out["precision"][ko], pr_in["precision"][ki]])),
"curve": cs.col("Positive class", ["Out-of-distribution"] * ko.size + ["Familiar"] * ki.size, "categorical",
["Out-of-distribution", "Familiar"])}),
cs.chart("scores", "overlap-density", "Scores of familiar and out-of-distribution rows", {
"score": cs.col(sc_col, raw), "group": cs.col("Rows", np.where(pos, "Out-of-distribution", "Familiar"), "categorical",
["Familiar", "Out-of-distribution"])}),
]
summary = (f"AUROC {dl['auc']:.3f} ({pct} CI {dl['low']:.3f} to {dl['high']:.3f}); catching {op['tpr']:.1%} of the "
f"{n_out} out-of-distribution rows flags {op['fpr']:.1%} of the {n_in} familiar ones. AUPR-out {aupr_out:.3f}, AUPR-in {aupr_in:.3f}.")
cs.publish({
"method": "evaluate.ood",
"methodVersion": "1.0.0",
"title": "Evaluate out-of-distribution detection",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"statistics": [
{"key": "auroc", "label": "AUROC", "value": dl["auc"]},
{"key": "fpr_at_tpr", "label": f"FPR at {target:.0%} TPR", "value": op["fpr"]},
{"key": "aupr_out", "label": "AUPR-out", "value": aupr_out},
{"key": "auroc_p", "label": "p (AUROC = 0.5)", "value": dl["p"], "format": "p"},
],
"tables": [
{"key": "metrics", "title": "Detection metrics", "columns": [
{"key": "metric", "label": "Metric", "type": "string"}, {"key": "value", "label": "Value", "type": "number"},
{"key": "low", "label": f"{pct} CI low", "type": "number"}, {"key": "high", "label": f"{pct} CI high", "type": "number"},
{"key": "chance", "label": "Chance level", "type": "number"}],
"rows": [
{"metric": "AUROC", "value": dl["auc"], "low": dl["low"], "high": dl["high"], "chance": 0.5},
{"metric": f"FPR at {target:.0%} TPR", "value": op["fpr"], "low": None, "high": None, "chance": target},
{"metric": "AUPR-out (out-of-distribution positive)", "value": aupr_out, "low": None, "high": None, "chance": n_out / n},
{"metric": "AUPR-in (familiar positive)", "value": aupr_in, "low": None, "high": None, "chance": n_in / n}],
"note": f"Threshold {threshold:.6g}: rows with a score {'≥' if direction == 'higher' else '≤'} it are flagged (TPR {op['tpr']:.1%}). DeLong interval for the AUROC."},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Out-of-distribution: {lc} = {out_level}. Larger scores mean {'more likely out-of-distribution' if direction == 'higher' else 'more familiar'}."],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Mahalanobis” · R version 4.5.1 (2025-06-13)
# Evaluate out-of-distribution detection
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method evaluate.ood 1.0.0 · spec fffdf59d46b92863
# Dataset: evp_ood (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_eval_fpr_at_tpr, cs_eval_average_precision, cs_eval_ood_roc, cs_auc_delong
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/evp_ood.parquet", col_select = c("score_maha", "split")))
n_input <- nrow(df)
df[["split"]] <- factor(df[["split"]], levels = c("in", "out")) # stored level order
df <- df[stats::complete.cases(df[c("score_maha", "split")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("score_maha", "split")) # infinite values stop the run (registry/errors.yaml)
# %% Scores
sc_col <- "score_maha"
lc <- "split"
present <- levels(df[[lc]]) # levels with data, in stored order
cs_check_groups(df[[lc]], lc, minimum = 2, exactly = 2)
out_level <- present[length(present)] # default: the last level ("true")
direction <- "higher"
raw <- as.numeric(df[[sc_col]])
s <- if (direction == "higher") raw else -raw # larger = more likely out-of-distribution
pos <- as.character(df[[lc]]) == out_level
n <- length(pos)
n_out <- sum(pos)
n_in <- n - n_out
target <- 0.95
conf <- 0.95
# %% Detection
dl <- cs_auc_delong(s[pos], s[!pos], conf)
op <- cs_eval_fpr_at_tpr(s, pos, target)
threshold <- if (direction == "higher") op$threshold else -op$threshold
aupr_out <- cs_eval_average_precision(s, pos)
aupr_in <- cs_eval_average_precision(-s, !pos)
# %% Assumptions
small <- min(n_in, n_out) < 20
assumptions <- list(
list(key = "held_out", label = "Scores come from a fitted detector", status = "info",
detail = "Fix the detector and any threshold before looking at these rows; tuning on them flatters every metric."),
list(key = "sample_size", label = "Enough rows of each kind", status = if (small) "warn" else "pass",
detail = paste0(sprintf("%d out-of-distribution and %d familiar rows", n_out, n_in),
if (small) "; the rates are noisy with fewer than 20 of either." else "."))
)
if (isTRUE(dl$auc < 0.5)) warnings <- c(warnings, "AUROC is below 0.5: the score ranks familiar rows as stranger than the out-of-distribution ones. Check the direction setting.")
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
values <- list(
n = n, n_in = n_in, n_out = n_out, ood_level = out_level, direction = direction, prevalence_out = n_out / n,
auroc = dl$auc, auroc_se = dl$se, auroc_low = dl$low, auroc_high = dl$high, auroc_p = dl$p,
target_tpr = target, threshold = threshold, tpr_at_threshold = op$tpr, fpr_at_tpr = op$fpr, tnr_at_tpr = 1 - op$fpr,
aupr_out = aupr_out, aupr_in = aupr_in
)
rc <- cs_eval_ood_roc(s, pos)
chosen <- rep(FALSE, length(rc$tpr))
chosen[1 + which(rc$threshold == op$threshold)[1]] <- TRUE # the operating point (element 1 is the (0, 0) start)
keep <- sort(union(cs_eval_thin(length(rc$tpr)), which(chosen)))
pr_out <- cs_eval_ood_pr(s, pos)
pr_in <- cs_eval_ood_pr(-s, !pos)
ko <- cs_eval_thin(length(pr_out$recall))
ki <- cs_eval_thin(length(pr_in$recall))
charts <- list(
cs_chart("roc", "roc-curve", sprintf("ROC curve (AUROC %.3f)", dl$auc),
list(fpr = cs_col("False-positive rate (familiar rows flagged)", rc$fpr[keep]),
tpr = cs_col("True-positive rate (out-of-distribution rows caught)", rc$tpr[keep]),
optimal = cs_col(sprintf("Catches %.0f%%", 100 * target), chosen[keep], "boolean"))),
cs_chart("pr", "pr-curve", "Precision–recall, each class as positive",
list(recall = cs_col("Recall", c(pr_out$recall[ko], pr_in$recall[ki])),
precision = cs_col("Precision", c(pr_out$precision[ko], pr_in$precision[ki])),
curve = cs_col("Positive class", c(rep("Out-of-distribution", length(ko)), rep("Familiar", length(ki))), "categorical",
c("Out-of-distribution", "Familiar")))),
cs_chart("scores", "overlap-density", "Scores of familiar and out-of-distribution rows",
list(score = cs_col(sc_col, raw),
group = cs_col("Rows", ifelse(pos, "Out-of-distribution", "Familiar"), "categorical", c("Familiar", "Out-of-distribution"))))
)
summary <- sprintf("AUROC %.3f (%s CI %.3f to %.3f); catching %.1f%% of the %d out-of-distribution rows flags %.1f%% of the %d familiar ones. AUPR-out %.3f, AUPR-in %.3f.",
dl$auc, pct, dl$low, dl$high, 100 * op$tpr, n_out, 100 * op$fpr, n_in, aupr_out, aupr_in)
cs_publish(list(
method = "evaluate.ood",
methodVersion = "1.0.0",
title = "Evaluate out-of-distribution detection",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
statistics = list(
list(key = "auroc", label = "AUROC", value = dl$auc),
list(key = "fpr_at_tpr", label = sprintf("FPR at %.0f%% TPR", 100 * target), value = op$fpr),
list(key = "aupr_out", label = "AUPR-out", value = aupr_out),
list(key = "auroc_p", label = "p (AUROC = 0.5)", value = dl$p, format = "p")
),
tables = list(
list(key = "metrics", title = "Detection metrics",
columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "value", label = "Value", type = "number"),
list(key = "low", label = sprintf("%s CI low", pct), type = "number"), list(key = "high", label = sprintf("%s CI high", pct), type = "number"),
list(key = "chance", label = "Chance level", type = "number")),
rows = list(
list(metric = "AUROC", value = dl$auc, low = dl$low, high = dl$high, chance = 0.5),
list(metric = sprintf("FPR at %.0f%% TPR", 100 * target), value = op$fpr, low = NA, high = NA, chance = target),
list(metric = "AUPR-out (out-of-distribution positive)", value = aupr_out, low = NA, high = NA, chance = n_out / n),
list(metric = "AUPR-in (familiar positive)", value = aupr_in, low = NA, high = NA, chance = n_in / n)),
note = sprintf("Threshold %.6g: rows with a score %s it are flagged (TPR %.1f%%). DeLong interval for the AUROC.",
threshold, if (direction == "higher") "≥" else "≤", 100 * op$tpr))
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Out-of-distribution: %s = %s. Larger scores mean %s.", lc, out_level,
if (direction == "higher") "more likely out-of-distribution" else "more familiar")),
charts = charts,
values = values
))
Sources
- Hendrycks, D., & Gimpel, K. (2017). A baseline for detecting misclassified and out-of-distribution examples in neural networks. ICLR.
- DeLong, E. R., DeLong, D. M., & Clarke-Pearson, D. L. (1988). Comparing the areas under two or more correlated receiver operating characteristic curves: a nonparametric approach. Biometrics, 44, 837–845.
- Davis, J., & Goadrich, M. (2006). The relationship between precision-recall and ROC curves. Proceedings of ICML, 233–240.
From the CodeSplash method registry · evaluate.ood v1.0.0.