Conformal anomaly detection and exchangeability martingales¶
Exact finite-sample conformal p-values for outlier/novelty detection, Benjamini–Hochberg conformal FDR control, and online exchangeability test martingales for drift detection.
| Use it when | You need calibrated false-alarm control on an anomaly scorer, FDR-controlled batch outlier discovery, or an anytime-valid online drift alarm. |
| Guarantee | ConformalAnomalyDetector: P(p <= alpha) <= alpha for any exchangeable inlier at any calibration size n (per category with groups=). ConformalMartingale: all-time false-alarm probability P(sup_t M_t >= C) <= 1 / C under exchangeability (Ville's inequality). |
| In the library | ConformalAnomalyDetector, ConformalMartingale, MartingaleResult |
| Source | Laxhammar and Falkman (2011); Bates et al. (Annals of Statistics, 2023); Vovk et al. (ICML 2003; COPA 2021) |
| Example needs | pyconformal |
Finite-sample & anytime-valid guarantees
For clean calibration scores \(s_1, \dots, s_n\), ConformalAnomalyDetector computes \(p(s) = \frac{1 + \#\{i : s_i \ge s\}}{n + 1}\), guaranteeing \(\mathbb{P}(p(S_{n+1}) \le \alpha) \le \alpha\) for any exchangeable inlier. Online, ConformalMartingale satisfies Ville's inequality
$\(\mathbb{P}\!\left(\sup_{t \ge 1} M_t \ge C\right) \le \frac{1}{C}\)$
controlling the all-time false-alarm rate at \(1/C\) regardless of stream length.
Minimal example¶
Copy, paste, run.
import numpy as np
from pyconformal import ConformalAnomalyDetector, ConformalMartingale
rng = np.random.default_rng(0)
cal_scores = rng.normal(0.0, 1.0, size=500) # clean inlier scores
test_scores = np.r_[rng.normal(0.0, 1.0, 180), rng.normal(4.5, 1.0, 20)]
# 1. Exact conformal p-values and Benjamini-Hochberg FDR control
cad = ConformalAnomalyDetector(alpha=0.05).calibrate(scores=cal_scores)
pvals = cad.predict_pvalue(scores=test_scores)
flags = cad.predict_anomaly(scores=test_scores)
bh_flags = cad.bh_select(pvals, fdr=0.10)
print(f"FPR on inliers: {flags[:180].mean():.3f} TPR on outliers: {flags[180:].mean():.3f}")
print(f"BH discoveries: {bh_flags.sum()} (true outliers caught: {bh_flags[180:].sum()}/20)")
# 2. Online Simple Jumper test martingale for distribution shift
stream = np.r_[rng.normal(0.0, 1.0, 200), rng.normal(3.0, 1.0, 200)]
cm = ConformalMartingale(betting="jumper", threshold=20.0, random_state=0)
res = cm.run(scores=stream)
print(f"drift alarm at step: {res.alarm_step} final log(M_t): {cm.log_martingale_:.2f}")
More¶
- Full argument list: API reference
- All methods: what's inside