Skip to content

Medical Imaging and Clinical AI

Bringing artificial intelligence to the hospital bedside raises the stakes higher than almost any other engineering domain, because every prediction touches human health, asymmetric clinical risk, and fragile real-world hospital workflows. This file examines medical imaging across radiology and pathology, clinical NLP over Electronic Health Records, bedside Bayesian reasoning with selective abstention, and the safety, fairness, and regulatory discipline required for trustworthy clinical deployment.

  • Recommending the wrong film on a streaming app wastes ten minutes of someone's evening. Missing an early intracranial haemorrhage on an emergency head CT can cost a patient's life within an hour, while flooding an intensive care unit with false alarms triggers alert fatigue that causes exhausted clinicians to silence genuinely urgent warnings.

  • Clinical medicine is uniquely unforgiving for AI systems for four interlocking reasons.

  • Asymmetric error costs mean false negatives and false positives are never equally painful, so raw accuracy is almost always the wrong objective.
  • Distribution shift happens constantly across hospitals, because a Siemens MRI scanner in London, a GE scanner in Tokyo, and a portable bedside X-ray machine produce subtly different intensity distributions, slice thicknesses, and patient demographics.
  • Patient privacy and governance restrict centralising raw clinical records, driving techniques like de-identification, strict access auditing, and federated learning where models travel to hospital data instead of data leaving the hospital.
  • Human-in-the-loop workflows matter as much as model weights, because an accurate algorithm that clashes with how radiologists or nurses actually work either goes unused or encourages dangerous automation bias (blindly rubber-stamping the machine's suggestion).

Medical Imaging Across Clinical Modalities

  • Unlike everyday photographs of cats and street signs, medical images come in wildly different physical formats, resolutions, and supervision regimes. Choosing the right neural architecture starts with respecting the geometry of each modality.

Radiology with 2D and 3D Vision Architectures

  • Chest X-rays are high-resolution 2D projections where bones, lungs, heart, and airways overlap along the beam path. Computed Tomography (CT) and Magnetic Resonance Imaging (MRI) capture full 3D volumes of voxels (\(H \times W \times D\)), where CT intensities carry calibrated physical density in Hounsfield units while MRI intensities vary with coil physics and pulse sequences.

  • Both 2D/3D Convolutional Neural Networks and Vision Transformers (ViTs) from Chapter 08 power modern radiology triage. 3D CNNs sweep volumetric kernels across neighbouring slices to catch subtle spherical lung nodules or vessel blockages, whereas ViTs and hybrid architectures capture long-range anatomical symmetry, such as comparing the left and right hemispheres of a brain scan to detect an asymmetric stroke.

Computational Pathology and Multiple Instance Learning

  • Now picture inspecting a digitised glass biopsy called a Whole-Slide Image (WSI). A single pathology slide at \(40\times\) magnification measures roughly \(100{,}000 \times 100{,}000\) pixels, containing \(10\) billion pixels, which is over a thousand times larger than a standard GPU image batch. Worse still, a clinical report typically gives only one slide-level label ("invasive cancer present" or "benign"), even if malignant cells occupy less than \(1\%\) of the glass!

  • Imagine searching a massive photo album of \(5{,}000\) holiday snapshots when someone tells you only whether at least one photo contains a red umbrella, without circling which page it is on. Multiple Instance Learning (MIL) frames each slide as a bag of \(K\) cropped tissue tiles \(\{\mathbf{h}_1, \dots, \mathbf{h}_K\}\) encoded by a pretrained vision backbone (such as a pathology foundation model).

  • In Attention-based MIL (Ilse et al., 2018), a tiny neural gate assigns every tile \(k\) a learned scalar importance weight \(a_k\) normalised via softmax, pooling the entire gigapixel slide into one compact slide vector \(\mathbf{z}\) before predicting the diagnosis.

\[a_k = \frac{\exp\!\left(\mathbf{w}^T \tanh(V \mathbf{h}_k)\right)}{\sum_{j=1}^{K} \exp\!\left(\mathbf{w}^T \tanh(V \mathbf{h}_j)\right)}, \qquad \mathbf{z} = \sum_{k=1}^{K} a_k \mathbf{h}_k\]
  • The beautiful side effect is built-in interpretability. Trained using only slide-level diagnoses, the attention weights \(a_k\) naturally spike over the sparse cancerous glands and drop near zero on healthy tissue, generating a pathology heatmap that guides the pathologist's eye straight to the decisive microscopic cells.

Anatomical Segmentation with U-Net and Soft Dice Loss

  • Before a radiation oncologist aims high-energy beams at a brain tumour, they need millimetre-accurate voxel contours tracing where the tumour stops and healthy optic nerve begins. U-Net (Ronneberger et al., 2015) and its self-configuring successor nnU-Net (Isensee et al., 2021) remain the gold standard for biomedical segmentation by pairing a contracting context encoder with an expanding decoder linked by skip connections that preserve crisp anatomical boundaries.

Medical imaging pipelines comparing 2D and 3D radiology classification, gigapixel whole-slide pathology with patch tiling and attention Multiple Instance Learning, and anatomical segmentation with U-Net and Soft Dice loss

  • Training a segmentation network with plain pixel-wise cross-entropy often fails dramatically when a tiny lesion covers only \(1\%\) of the scan. Predicting "background everywhere" instantly earns \(99\%\) pixel accuracy while missing the entire tumour! Soft Dice loss avoids this trap by directly optimising the differentiable overlap between predicted probabilities \(p_i \in [0, 1]\) and ground-truth binary mask voxels \(g_i \in \{0, 1\}\) (with a tiny smoothing constant \(\epsilon\) to prevent division by zero).
\[\mathcal{L}_{\text{Dice}}(p, g) = 1 - \frac{2 \sum_{i} p_i g_i + \epsilon}{\sum_{i} p_i + \sum_{i} g_i + \epsilon}\]
  • Notice what happens if the model lazily predicts \(p_i = 0\) everywhere on a scan containing a small tumour. The numerator collapses to zero, forcing \(\mathcal{L}_{\text{Dice}} \approx 1\) (maximum penalty), regardless of how tiny the tumour is relative to the surrounding organ.

Clinical NLP and Electronic Health Records

  • Medical images tell only one slice of a patient's story. The rest lives inside the Electronic Health Record (EHR), a messy, longitudinal tapestry of irregularly sampled blood tests, vital-sign waveforms sampled at \(250\text{ Hz}\) in the ICU, medication orders, billing codes, and hastily typed clinical notes stuffed with abbreviations ("SOB", "r/o PE") and copy-pasted history.

  • Notice that even missingness carries clinical signal in an EHR. A doctor rarely orders a blood lactate measurement on a healthy patient walking in for a routine vaccine, so the mere fact that a lab was measured at \(3\text{ a.m.}\) already implies clinical suspicion. Modern EHR models therefore feed both measurement values and time-since-last-observation masks into Transformers, neural state-space models, or continuous-time survival models (such as Cox proportional hazards networks) to forecast sepsis onset, readmission risk, or long-term mortality trajectories.

  • Large Language Models and clinical NLP pipelines unlock the unstructured text side of medicine, drafting structured discharge summaries, extracting adverse drug reactions, and automating clinical trial matching by comparing a patient's complex pathology and genetic eligibility criteria against thousands of active trials. Increasingly, multimodal clinical AI (connecting to Chapter 13) fuses radiology scans, pathology slides, lab trajectories, and physiological waveforms into one holistic patient representation, mirroring how a multidisciplinary tumour board synthesises every clue before choosing therapy.

Bayes' Theorem at the Bedside, Calibration, and Abstention

  • Imagine a brand-new AI screening tool for a rare cancer advertised with \(95\%\) sensitivity (it catches \(95\%\) of true cancers) and \(95\%\) specificity (it correctly clears \(95\%\) of healthy people). Suppose your screening scan comes back positive. Most patients, and surprisingly many trained doctors, instinctively guess there is a \(95\%\) chance they have the disease.

  • Bayes' theorem from Chapter 05 delivers a sobering reality check whenever a disease has low prevalence (base rate), say \(P(D) = 0.005\) (\(0.5\%\) of the screened population). Out of \(10{,}000\) screened patients, roughly \(50\) truly have the disease and \(9{,}950\) are healthy. The test correctly flags \(0.95 \times 50 \approx 47.5\) true positives, yet its \(5\%\) false-positive rate also flags \(0.05 \times 9{,}950 = 497.5\) completely healthy people!

\[\text{PPV} = P(D \mid +) = \frac{\text{Sensitivity} \cdot P(D)}{\text{Sensitivity} \cdot P(D) + (1 - \text{Specificity}) \cdot (1 - P(D))} \approx \frac{47.5}{47.5 + 497.5} \approx 8.7\%\]
  • Even with a \(95\%\) sensitive and \(95\%\) specific classifier, over \(91\%\) of positive flags are false alarms! Meanwhile, the Negative Predictive Value (NPV) \(P(\neg D \mid -)\) sits above \(99.97\%\), making a negative result highly reassuring. Understanding PPV versus NPV explains why screening models must be tuned to radically higher specificity than diagnostic models used in high-prevalence specialist clinics.

  • Beyond threshold metrics, clinical AI must be well calibrated, meaning that when a model outputs a predicted risk of \(0.30\), roughly \(30\%\) of patients given that score truly experience the event. Deep networks tend to be overconfident, so engineers apply post-hoc temperature scaling (dividing logits by a validation-tuned scalar \(T > 1\) before the softmax) and build selective abstention gates. When predictive uncertainty is high or an input looks out-of-distribution, the safest clinical AI says "I am not confident on this scan" and automatically defers the case to a senior specialist instead of guessing.

Safety, Shortcut Learning, Regulation, and Drift Monitoring

  • In a famous cautionary study (Zech et al., 2018), deep networks trained to spot pneumonia on chest X-rays achieved stellar accuracy inside their training hospitals yet stumbled badly at external sites. Inspecting saliency heatmaps uncovered an astonishing shortcut. Severely ill hospitalised patients were frequently imaged using portable bedside X-ray machines stamped with a faint metallic "PORTABLE" text token in the corner, so the model had learned to read the scanner watermark and hospital tag instead of examining the lungs!

Clinical AI safety loop showing multimodal patient inputs audited for shortcuts, calibrated risk estimation with Bayes base-rate checking, a confidence triage gate routing cases to clinician decision support or specialist abstention, and continuous post-deployment drift and fairness auditing

  • Preventing real-world harm requires turning safety into an end-to-end engineering lifecycle connected directly to Chapter 21 (ML Systems Design).
  • Prospective clinical trials evaluate the AI live in real hospital workflows rather than relying solely on tidy retrospective test sets, measuring whether the tool genuinely improves patient outcomes and clinician speed rather than merely boosting an offline AUROC score.
  • Regulatory clearance treats clinical algorithms as Software as a Medical Device (SaMD) under frameworks such as the US FDA's Good Machine Learning Practice and Predetermined Change Control Plans (PCCPs), which define strict validation boundaries for how a deployed model may safely be updated over time.
  • Demographic fairness auditing slices sensitivity, specificity, and calibration across age, sex, skin tone, and socioeconomic subgroups to catch hidden disparities, such as dermatology classifiers underperforming on darker skin tones or pulse-oximetry proxies introducing systematic bias.
  • Post-deployment drift monitoring continuously tracks input feature distributions, scanner software upgrades, disease prevalence shifts (like a sudden winter respiratory surge), and clinician override rates, firing alerts before silent degradation harms patients.

Take-Home

  • Clinical AI operates under asymmetric stakes and constant shift, making patient privacy, scanner generalisation, and human-in-the-loop clinical integration just as vital as raw model accuracy.
  • Medical imaging matches architecture to clinical geometry, spanning 2D and 3D CNNs or ViTs for radiology, Attention-based Multiple Instance Learning for gigapixel pathology slides, and U-Net with Soft Dice loss for class-imbalanced anatomical segmentation.
  • EHR and multimodal clinical models handle irregular sampling, informative missingness, unstructured notes, and longitudinal survival trajectories across imaging, labs, and physiological waveforms.
  • Bayes' theorem governs every bedside alert, because low disease prevalence turns even \(95\%\) sensitive and specific tests into mostly false positives unless paired with strict calibration and selective abstention to specialists.
  • Trustworthy deployment requires vigilance beyond offline metrics, guarding against shortcut learning through external validation, prospective clinical trials, FDA SaMD governance, demographic fairness audits, and continuous drift monitoring.

Coding Tasks (use CoLab or notebook)

  1. Compare Soft Dice Loss against standard Binary Cross-Entropy (BCE) on a severely imbalanced synthetic 2D medical image where a small circular tumour occupies roughly \(2.5\%\) of the pixels. Train a lightweight spatial feature classifier with jax.grad under both losses and inspect the resulting Dice overlap and predicted masks.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(14)
    k1, k2 = jax.random.split(key)
    H, W = 40, 40
    
    # Synthetic 2D scan: small tumour (radius 3.5 px -> ~2.4% of pixels) inside noisy tissue
    yy, xx = jnp.meshgrid(jnp.arange(H), jnp.arange(W), indexing="ij")
    dist = jnp.sqrt((yy - 14.0) ** 2 + (xx - 26.0) ** 2)
    mask = (dist <= 3.5).astype(jnp.float32)
    
    # Intensity + blurred intensity + local contrast features per pixel (noisy signal)
    raw_img = 0.25 + 1.15 * mask + 0.55 * jax.random.normal(k1, (H, W))
    # Simple 3x3 local neighbourhood mean using rolled shifts (Pyodide-safe pure array ops)
    local_mean = (
        raw_img + jnp.roll(raw_img, 1, axis=0) + jnp.roll(raw_img, -1, axis=0)
        + jnp.roll(raw_img, 1, axis=1) + jnp.roll(raw_img, -1, axis=1)
    ) / 5.0
    X_feat = jnp.stack([raw_img, local_mean, raw_img ** 2, jnp.ones((H, W))], axis=-1).reshape(-1, 4)
    y_true = mask.reshape(-1)
    print(f"Tumour foreground fraction: {float(jnp.mean(y_true)):.2%}")
    
    def bce_loss(w):
        p = jax.nn.sigmoid(X_feat @ w)
        return -jnp.mean(y_true * jnp.log(p + 1e-6) + (1.0 - y_true) * jnp.log(1.0 - p + 1e-6))
    
    def soft_dice_loss(w):
        p = jax.nn.sigmoid(X_feat @ w)
        return 1.0 - (2.0 * jnp.sum(p * y_true) + 1.0) / (jnp.sum(p) + jnp.sum(y_true) + 1.0)
    
    def train_model(loss_fn, steps=250, lr=0.4):
        w = jax.random.normal(k2, (4,)) * 0.1
        g_fn = jax.grad(loss_fn)
        for _ in range(steps):
            w = w - lr * g_fn(w)
        return jax.nn.sigmoid(X_feat @ w).reshape(H, W)
    
    prob_bce = train_model(bce_loss, steps=250, lr=0.4)
    prob_dice = train_model(soft_dice_loss, steps=250, lr=0.8)
    
    def hard_dice(prob):
        pred = (prob > 0.5).astype(jnp.float32)
        return float((2.0 * jnp.sum(pred * mask) + 1e-6) / (jnp.sum(pred) + jnp.sum(mask) + 1e-6))
    
    print(f"Hard Dice Score -> BCE: {hard_dice(prob_bce):.3f} | Soft Dice Loss: {hard_dice(prob_dice):.3f}")
    
    fig, axes = plt.subplots(1, 3, figsize=(10.5, 3.4))
    axes[0].imshow(raw_img, cmap="gray"); axes[0].contour(mask, levels=[0.5], colors="#27ae60", linewidths=1.5)
    axes[0].set_title("Noisy Scan + True Contour"); axes[0].axis("off")
    axes[1].imshow(prob_bce, cmap="magma", vmin=0, vmax=1)
    axes[1].set_title(f"BCE Prob Map (Dice={hard_dice(prob_bce):.2f})"); axes[1].axis("off")
    axes[2].imshow(prob_dice, cmap="magma", vmin=0, vmax=1)
    axes[2].set_title(f"Soft Dice Map (Dice={hard_dice(prob_dice):.2f})"); axes[2].axis("off")
    plt.tight_layout(); plt.show()
    

  2. Implement Attention-based Multiple Instance Learning (ABMIL) for synthetic whole-slide pathology bags (\(K=20\) tiles per slide, \(D=8\) features per tile). In cancer-positive slides, only one hidden tile carries the tumour signature while the model sees only slide-level labels during training. Verify that attention weights automatically pinpoint the malignant tile!

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    key = jax.random.PRNGKey(33)
    k1, k2, k3, k4 = jax.random.split(key, 4)
    N_slides, K_tiles, D_feat = 160, 20, 8
    
    # Healthy background tiles drawn around 0; malignant patch carries a distinct pattern vector
    tumour_sig = jnp.array([2.2, -1.8, 1.5, 1.9, -1.2, 0.8, 1.4, -1.5])
    bags = 0.65 * jax.random.normal(k1, (N_slides, K_tiles, D_feat))
    y_slide = jnp.concatenate([jnp.zeros(N_slides // 2), jnp.ones(N_slides // 2)])
    
    # Inject exactly 1 malignant tile at a random tile position in every positive slide
    pos_idx = jax.random.randint(k2, (N_slides,), 0, K_tiles)
    tile_grid = jnp.arange(K_tiles)[None, :]
    is_tumour_tile = ((tile_grid == pos_idx[:, None]) & (y_slide[:, None] > 0.5)).astype(jnp.float32)
    bags = bags + is_tumour_tile[:, :, None] * tumour_sig[None, None, :]
    
    # Balanced train/test split (120 train / 40 test)
    tr_idx = jnp.concatenate([jnp.arange(60), jnp.arange(80, 140)])
    te_idx = jnp.concatenate([jnp.arange(60, 80), jnp.arange(140, 160)])
    X_tr, y_tr = bags[tr_idx], y_slide[tr_idx]
    X_te, y_te, mask_te = bags[te_idx], y_slide[te_idx], is_tumour_tile[te_idx]
    
    # ABMIL parameters: attention gate (V, w_a) and bag classifier (w_c, b_c)
    kp = jax.random.split(k4, 3)
    V = jax.random.normal(kp[0], (D_feat, 10)) * 0.25
    w_a = jax.random.normal(kp[1], (10, 1)) * 0.25
    w_c = jax.random.normal(kp[2], (D_feat, 1)) * 0.25
    b_c = jnp.array(0.0)
    
    def abmil_forward(V_, wa_, wc_, bc_, X):
        h = jnp.tanh(X @ V_)                                   # (N, K, 10)
        attn_logits = (h @ wa_).squeeze(-1)                    # (N, K)
        attn = jax.nn.softmax(attn_logits, axis=1)             # (N, K)
        z_bag = jnp.sum(attn[:, :, None] * X, axis=1)          # (N, D)
        prob = jax.nn.sigmoid((z_bag @ wc_).squeeze(-1) + bc_) # (N,)
        return prob, attn, h, z_bag
    
    # Analytical backprop through attention softmax and bag classifier
    N_tr = X_tr.shape[0]
    lr = 0.25
    for _ in range(300):
        prob, attn, h, z_bag = abmil_forward(V, w_a, w_c, b_c, X_tr)
        d_logit = (prob - y_tr) / N_tr                         # (N,)
        dw_c = z_bag.T @ d_logit[:, None]
        db_c = jnp.sum(d_logit)
        d_z = d_logit[:, None] @ w_c.T                         # (N, D)
        d_attn = jnp.sum(d_z[:, None, :] * X_tr, axis=-1)      # (N, K)
        d_al = attn * (d_attn - jnp.sum(attn * d_attn, axis=1, keepdims=True))
        dw_a = jnp.sum(h * d_al[:, :, None], axis=(0, 1))[:, None]
        d_h = (d_al[:, :, None] * w_a.T[None, :, :]) * (1.0 - h ** 2)
        dV = jnp.einsum("nkd,nkh->dh", X_tr, d_h)
        V, w_a, w_c, b_c = V - lr * dV, w_a - lr * dw_a, w_c - lr * dw_c, b_c - lr * db_c
    
    prob_te, attn_te, _, _ = abmil_forward(V, w_a, w_c, b_c, X_te)
    slide_acc = float(jnp.mean((prob_te > 0.5) == y_te))
    pos_te = y_te > 0.5
    top_tile_hit = float(jnp.mean(jnp.argmax(attn_te[pos_te], axis=1) == jnp.argmax(mask_te[pos_te], axis=1)))
    print(f"Test Slide Accuracy: {slide_acc:.1%} | Attention pinpointed exact tumour tile: {top_tile_hit:.1%}")
    
    # Plot attention heatmap for one positive test slide
    ex_i = int(jnp.argmax(y_te))
    true_t = int(jnp.argmax(mask_te[ex_i]))
    bar_cols = ["#e74c3c" if k == true_t else "#3498db" for k in range(K_tiles)]
    plt.figure(figsize=(8.5, 3.6))
    plt.bar(range(K_tiles), attn_te[ex_i], color=bar_cols, alpha=0.85)
    plt.xlabel("Tissue Patch Index (Red = True Hidden Tumour Tile)"); plt.ylabel("Attention Weight a_k")
    plt.title(f"ABMIL Pinpoints Tumour Tile #{true_t} Using Only Slide-Level Labels")
    plt.grid(axis="y", alpha=0.3); plt.tight_layout(); plt.show()
    

  3. Simulate Bayes' theorem at the bedside, temperature-scaling calibration, and selective abstention. First verify how a \(95\%\) sensitive and \(95\%\) specific screening test behaves across disease prevalences from \(0.1\%\) to \(50\%\), then calibrate an overconfident model's logits and watch deferring uncertain cases to human specialists boost accuracy on retained predictions.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # Part 1: Bayes' theorem PPV and NPV across disease prevalence
    sens, spec = 0.95, 0.95
    prev = jnp.linspace(0.001, 0.50, 300)
    ppv = (sens * prev) / (sens * prev + (1.0 - spec) * (1.0 - prev))
    npv = (spec * (1.0 - prev)) / (spec * (1.0 - prev) + (1.0 - sens) * prev)
    
    p_half = 0.005
    ppv_half = (sens * p_half) / (sens * p_half + (1.0 - spec) * (1.0 - p_half))
    print(f"At 0.5% prevalence (95% sens / 95% spec) -> PPV = {ppv_half:.1%} (91%+ false alarms!)")
    
    # Part 2: Overconfident clinical model -> temperature scaling + selective abstention
    key = jax.random.PRNGKey(2026)
    k1, k2 = jax.random.split(key)
    N = 2000
    true_logits = jax.random.normal(k1, (N,)) * 1.6
    true_probs = jax.nn.sigmoid(true_logits)
    y_obs = (jax.random.uniform(k2, (N,)) < true_probs).astype(jnp.float32)
    
    # Uncalibrated neural model has overconfident logits scaled by 3.0x
    raw_logits = true_logits * 3.0
    raw_probs = jax.nn.sigmoid(raw_logits)
    
    # Optimise scalar temperature T > 0 on negative log-likelihood using jax.grad
    def nll_temp(log_T):
        p = jax.nn.sigmoid(raw_logits / jnp.exp(log_T))
        return -jnp.mean(y_obs * jnp.log(p + 1e-6) + (1.0 - y_obs) * jnp.log(1.0 - p + 1e-6))
    
    log_T = jnp.array(0.0)
    g_temp = jax.grad(nll_temp)
    for _ in range(120):
        log_T = log_T - 0.5 * g_temp(log_T)
    T_opt = float(jnp.exp(log_T))
    cal_probs = jax.nn.sigmoid(raw_logits / T_opt)
    print(f"Learned calibration temperature T = {T_opt:.2f} (true overconfidence factor = 3.00)")
    
    # Selective abstention: defer scans with calibrated confidence below threshold
    conf = jnp.maximum(cal_probs, 1.0 - cal_probs)
    correct = ((cal_probs >= 0.5) == (y_obs > 0.5)).astype(jnp.float32)
    taus = jnp.linspace(0.50, 0.94, 30)
    coverages, accs = [], []
    for tau in taus:
        keep = conf >= tau
        coverages.append(float(jnp.mean(keep)))
        accs.append(float(jnp.sum(correct * keep) / (jnp.sum(keep) + 1e-6)))
    
    print(f"Full coverage (100%): Acc = {accs[0]:.1%} | Selective deferral ({coverages[12]:.0%} automated): Acc = {accs[12]:.1%}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
    axes[0].plot(prev * 100, ppv * 100, color="#e74c3c", lw=2.3, label="PPV P(Disease | +)")
    axes[0].plot(prev * 100, npv * 100, color="#27ae60", lw=2.3, linestyle="--", label="NPV P(Healthy | -)")
    axes[0].scatter([0.5], [ppv_half * 100], color="#333", s=55, zorder=5)
    axes[0].annotate(f"0.5% prev -> PPV {ppv_half:.1%}", xy=(0.8, ppv_half * 100), xytext=(10, 22),
                     arrowprops=dict(arrowstyle="->", color="#333"), fontsize=8.5)
    axes[0].set_xlabel("Disease Prevalence (%)"); axes[0].set_ylabel("Predictive Value (%)")
    axes[0].set_title("Bayes Base-Rate Effect (95% Sens / Spec)"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].plot(jnp.array(coverages) * 100, jnp.array(accs) * 100, color="#3498db", lw=2.4)
    axes[1].invert_xaxis()
    axes[1].set_xlabel("Automated Coverage (%) [Right = More Specialist Deferral]")
    axes[1].set_ylabel("Accuracy on Retained Cases (%)")
    axes[1].set_title("Selective Abstention Improves Bedside Safety"); axes[1].grid(alpha=0.3)
    plt.tight_layout(); plt.show()