Skip to content

About

Distribution-shift detection for monitoring medical AI after deployment (MUKS, MMD, classifier tests), with dental NHANES and RetinaMNIST demonstrations. Research use only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

shiftwatch

tests DOI License: MIT Python 3.10-3.12

Distribution-shift detection for monitoring medical AI after deployment. shiftwatch asks one question of a deployed model: does the data it sees now still look like the data it was validated on? It provides three two-sample tests, simulators for population and acquisition shifts, detection-power curves, a batch monitor and subgroup performance tables, with two open demonstrations on public data (a dental questionnaire model on NHANES and a retinal-image model on RetinaMNIST).

Research and education use only. shiftwatch is not a medical device and must not be used to make clinical decisions or as the sole post-market surveillance measure of a regulated product.

It follows the study design of Koch, Baumgartner and Berens, Distribution shift detection for the postmarket surveillance of medical AI algorithms: a retrospective simulation study, npj Digital Medicine 2024;7:120 (doi:10.1038/s41746-024-01085-w). shiftwatch is an independent implementation (no code copied from the authors' repository lmkoch/postmarket-shift-detection) and is not endorsed by the authors. It does not re-analyse their EyePACS data.

Quickstart

pip install git+https://github.com/Decadentry/shiftwatch
shiftwatch demo
shiftwatch test reference.csv incoming.csv --columns age,q1,q2 --method all
shiftwatch power --pool pool.csv --group diabetes --prevalence 0.5 --sizes 100,200,500 --reps 100
import numpy as np
from shiftwatch import run_test, Monitor

ref = np.random.default_rng(0).normal(size=(500, 8))      # e.g. model embeddings at validation
new = np.random.default_rng(1).normal(size=(200, 8)) + 0.3  # embeddings of this week's cases
for method in ("muks", "mmd", "c2st"):
    r = run_test(method, ref, new, alpha=0.05, rng=0)
    print(method, r.p_value, r.detected)

mon = Monitor(ref, method="c2st", alpha=0.05, consecutive=1)
mon.update(new, label="week 1")

What it does

Module Content
detectors MUKS: one Kolmogorov-Smirnov test per feature, Bonferroni-combined. MMD: Gaussian-kernel maximum mean discrepancy (median-heuristic bandwidth, pooled standardisation) with a permutation p-value. C2ST: classifier two-sample test; a domain classifier (default: logistic regression) is trained on half the pooled data, held-out accuracy is tested against 0.5 with an exact binomial test.
simulate Subgroup (prevalence) shifts; image degradations (blur, noise, brightness, contrast, down-sampling); binary answer flips.
power Detection rate / false-alarm rate over replicates with Wilson 95% intervals; power curves; minimum n for a target detection rate.
monitor Batch-wise testing against a fixed reference with an optional "k consecutive rejections" alarm rule.
subgroups Sensitivity, specificity and AUROC per subgroup with bootstrap 95% CIs.
nhanes, retina Loaders for the two demonstrations (data are downloaded by scripts/, never redistributed).
CLI shiftwatch test, shiftwatch power, shiftwatch demo.

Method in brief

Each test compares a reference sample (for example, model inputs, embeddings or outputs at validation) with a test sample from deployment, under the null hypothesis that both come from the same distribution. In simulations, every replicate splits the evaluation pool at random into two disjoint halves; the reference is drawn from one half, the test sample from the other, and the shift is applied only to the test sample. The share of rejections at alpha = 0.05 over 100 replicates is the detection rate (power); under "no shift" it is the false-alarm rate.

Results

All numbers below come from results/*.json (tables generated by experiments/make_tables.py, full tables in docs/results_tables.md). Reproduce with:

pip install -e ".[figures]"
python scripts/download_nhanes.py && python scripts/download_retinamnist.py
python experiments/run_nhanes.py && python experiments/run_retina.py
python experiments/make_figures.py && python experiments/make_tables.py

1. Dental demonstration: NHANES 2009-2014 oral-health questionnaire model

Model: logistic regression for periodontitis (deepest probing depth >= 4 mm) from eight self-reported oral-health items and age, trained on a random half of NHANES 2009-2010 (n = 1,745). Evaluation pool: NHANES 2011-2014 (n = 6,560; AUROC 0.654). Detectors see the nine model inputs plus the predicted probability; sex, ethnicity and diabetes are not detector features, so those shifts can only be seen through their indirect effect on answers and age.

Subgroup performance on the pool (threshold from training data) shows why monitoring matters: AUROC was 0.568 [0.527, 0.606] in participants with self-reported diabetes vs 0.664 [0.650, 0.678] without, and 0.580 [0.548, 0.611] at age 65+ vs 0.676 [0.661, 0.691] below 65.

NHANES detection rates

Detection rate (100 replicates, alpha 0.05; n = size of each of the reference and test samples), selected cells. Age is itself a detector feature, so the age shift is seen directly:

Shift in test sample n MUKS MMD C2ST MUKS (output only)
none (false alarms) 1000 0.02 0.04 0.03 0.06
female 100% (pool 51%) 1000 0.39 0.58 0.29 0.27
non-Hispanic Black 100% (pool 22%) 500 1.00 1.00 0.97 0.79
diabetes 50% (pool 13%) 500 0.81 0.89 0.62 0.74
age 65+ 50% (pool 21%) 200 1.00 0.96 0.75 0.39
answer noise 10% (5 yes/no items) 500 0.27 1.00 0.81 0.38

Batch monitor (C2ST, reference 1,000, batches of 200, diabetes share raised to 50% from batch 10, 50 runs; C2ST balances samples, so each batch is compared with a random 200 of the reference cases). With an alarm on any rejection there were 0.048 false alarms per batch before the shift; an alarm came in batches 10-19 in 86% of shifted runs (median delay 2 batches, 0 = first shifted batch) but also in 30% of no-shift control runs. Requiring two consecutive rejections cut false alarms to 0.002 per batch (control: 4% of runs) but raised an alarm in only 24% of shifted runs. A 50% diabetes share is hard to see in batches of 200.

Real data, no simulation: comparing a held-out half of 2009-2010 (n = 1,746) with the later cycles, 3 of 6 tests rejected at 0.05 without multiplicity correction (2011-2012: MUKS p = 0.206, MMD p = 0.015 on 1,500 per side, C2ST p = 0.130; 2013-2014: 0.041, 0.010, 0.086). The cycles did differ: the non-Hispanic Black share was 0.176 in the reference and 0.250 in 2011-2012, and periodontitis prevalence fell from 0.495 to 0.358 in 2013-2014. Model AUROC was 0.677, 0.649 and 0.658. A change in outcome prevalence is not directly visible to tests on model inputs, which is one reason input monitoring cannot replace outcome checks.

2. Imaging demonstration: RetinaMNIST

Model: one-hidden-layer MLP (128 units) on 28 x 28 colour fundus images, trained on the official RetinaMNIST training split (n = 1,080); test 5-class accuracy 0.507, referable-DR (grade >= 2) AUROC 0.779. Detectors: MUKS on the 5-class softmax output, MMD and C2ST on the 128-unit embedding. Pool: validation + test images (n = 520).

RetinaMNIST detection rates

Shift in test sample Test-set accuracy under shift n for >= 0.80 detection: MUKS / MMD / C2ST
none 0.507 false alarms at n = 200: 0.04 / 0.03 / 0.05
blur sigma 0.5 px 0.497 not reached by 200 / not reached / 100
blur sigma 1.0 px 0.422 50 / 50 / 25
Gaussian noise SD 0.03 0.463 100 / not reached / 50
brightness -0.05 0.512 not reached / 100 / 50
contrast x 0.8 0.280 25 / 25 / 25
down-sampling x 2 0.425 50 / 50 / 25
referable DR 80% (pool 45%) n/a not reached by 100 (0.66 / 0.51 / 0.16 at n = 100)

Honest comparison with the source paper

  • Similar ordering: as in Koch et al. (2024), a pure sex shift was the hardest to detect, and co-morbidity and image-quality shifts were easier. The definitions differ, though: the paper's co-morbidity shift was mainly reported eye disease and its quality shift selected real images of adequate quality, whereas here co-morbidity is self-reported diabetes and acquisition shifts are synthetic pixel degradations (closer to the paper's out-of-distribution shift). No test raised false alarms clearly above the nominal 5% in our simulations (MUKS is conservative with discrete features).
  • Differs: in the paper the classifier-based test performed best overall. Here no single test won: MMD was strongest in most NHANES scenarios (MUKS for the age shift), including the sex shift, where the paper found that only the classifier test succeeded; C2ST was strongest on most image degradations; MUKS on the softmax output was best for the label-prevalence shift. Our C2ST uses a logistic-regression domain classifier on fixed features, and our MMD uses a fixed Gaussian kernel; the paper trained a CNN domain classifier and a deep kernel on 130,486 EyePACS images. Absolute sample sizes are therefore not comparable with the paper, and this is not a reproduction of its numbers.

Limitations

  • Small public datasets and simple models; RetinaMNIST at 28 x 28 pixels is far from clinical fundus images, and a blur of 0.5 pixel there does not map to a clinical optical change.
  • Detection rates are conditional on one fixed pool and one trained model. Pools are small (RetinaMNIST: 520 images, halves of 260), so at large n successive replicates overlap heavily; Wilson intervals do not cover pool-to-pool or model-to-model variation.
  • Simulated shifts; the only real shift examined is NHANES cycle-to-cycle variation.
  • Detecting a shift is not the same as detecting harm: some detected shifts barely changed performance (brightness -0.05: accuracy 0.512 vs 0.507), while others did (contrast x 0.8: 0.280).
  • Multiplicity: MUKS corrects across features, but nothing corrects across the three tests, across scenarios or across monitoring batches; repeated monitoring at a fixed alpha accumulates false alarms.
  • C2ST discards rows of the larger sample to balance the two samples, which wastes reference data.
  • NHANES: complete cases only (borderline diabetes and missing answers excluded); survey weights are not used, and NHANES deliberately oversamples some groups (for example non-Hispanic Black and older adults), so pool prevalences are sample, not population, estimates; race/ethnicity uses RIDRETH1.

Intended use

Teaching and research on post-deployment monitoring of clinical prediction and imaging models, power planning for monitoring designs ("how many cases per month do we need?"), and benchmarking shift tests. Not for clinical decisions, regulatory submissions or patient-level use.

Data and licences

  • Code: MIT (c) Hossein Boustani Hezarani / Decadentry.
  • NHANES (CDC/NCHS): public domain; downloaded by scripts/download_nhanes.py; follow the NCHS data-use restrictions.
  • RetinaMNIST (MedMNIST+, Yang et al., Sci Data 2023, doi:10.1038/s41597-022-01721-8; Zenodo doi:10.5281/zenodo.10519652; source images from the DeepDRiD challenge): CC BY 4.0; downloaded by scripts/download_retinamnist.py. No data are stored in this repository.

How to cite

Please cite the software (see CITATION.cff; DOI added after the first Zenodo release; technical note: docs/technical_note.pdf) and the paper whose design it follows:

Koch LM, Baumgartner CF, Berens P. Distribution shift detection for the postmarket surveillance of medical AI algorithms: a retrospective simulation study. npj Digit Med. 2024;7:120. doi:10.1038/s41746-024-01085-w

Acknowledgement

Thanks to Lisa M. Koch, Christian F. Baumgartner and Philipp Berens for an openly published study design (CC BY 4.0) and code, to NCHS for NHANES, and to the MedMNIST and DeepDRiD teams for RetinaMNIST.

Development

pip install -e ".[dev]"
python -m pytest -q
ruff check src tests experiments scripts conftest.py

About

Distribution-shift detection for monitoring medical AI after deployment (MUKS, MMD, classifier tests), with dental NHANES and RetinaMNIST demonstrations. Research use only.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages