Dataset Viewer

The dataset viewer is not available because its heuristics could not detect any supported data files. You can try uploading some data files, or configuring the data files location manually.

YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

SpatialUQ: Post-Hoc Uncertainty Quantification from Spatial Consistency in Black-Box Vision Models

Python 3.9+ PyTorch 2.0+ MIT License


Overview

SpatialUQ is a post-hoc, training-free uncertainty quantification method for frozen vision model checkpoints. It quantifies prediction uncertainty by measuring the Jensen-Shannon Divergence (JSD) between a frozen model's global prediction on a full image and the mean of predictions made over five fixed spatial crops of the same image. This scalar score—the **Multicrop Uncertainty Score (MUS)**—requires exactly six deterministic forward passes, no model internals, no gradients, no training data, and no retraining.

The core insight is geometric: a reliable model anchors its predictions to stable visual evidence, producing consistent outputs regardless of which spatial sub-region of the image is presented. When a model's confidence is not grounded in localizable features—due to distributional mismatch, low image quality, or atypical presentations—its predictions diverge between the global view and local crops. This inconsistency is a principled, information-theoretically grounded signal for failure detection.

On NIH ChestX-ray14 (DenseNet-121, N=25,596), MUS achieves 0.784 failure-detection AUC, outperforming MC-Dropout (0.664) at one-fifth the compute. It scales with model quality—reaching 0.899 AUC on BiomedCLIP (Spearman ρ=0.846 with per-image Brier score)—and generalizes zero-shot to CheXpert, VinBigData, ImageNet-1k, and MS COCO. A lightweight logistic fusion of MUS with entropy, confidence, and L1 distance reaches 0.832 AUC, surpassing a five-member deep ensemble (0.813 AUC) without any model retraining.


Motivation

The Problem: Frozen Black-Box Deployments

In high-stakes clinical settings, deployed vision models frequently exist as frozen checkpoints: the model weights are fixed, internal activations are inaccessible, and retraining is infeasible due to regulatory, computational, or data availability constraints. Yet, these models fail silently on out-of-distribution inputs—and without ground truth at inference time, identifying when a prediction should be trusted is non-trivial.

Limitations of Existing UQ Methods

Method Requirement Limitation
MC-Dropout Dropout layers at training time Inapplicable to frozen checkpoints; 30× compute
Deep Ensembles Train K independent models 5× training cost; requires model access
Bayesian weight approx. Training-time modification Poor scalability
DDU / Mahalanobis Penultimate-layer features + training distribution Requires model internals; stores full covariance
ODIN Gradient-based input perturbation Requires backpropagation access
Conformal prediction Calibration dataset Produces prediction sets, not scalar triage scores
TTA (variance) Multiple stochastic augmentations Confounds photometric and geometric sensitivity

SpatialUQ addresses all of these limitations simultaneously: it is fully post-hoc, works from output probabilities alone, and introduces a geometrically grounded perturbation strategy (spatial sub-regions) rather than photometric or stochastic perturbations. Lemma 1 in the paper formalizes why JSD between global and local outputs upper-bounds the mean absolute probability shift—making MUS a theoretically grounded rather than heuristic score.


Method

Core Insight

A model with well-localized, spatially stable predictions produces broadly consistent outputs whether it sees the full image or any spatial crop containing the relevant features. When model confidence is not anchored to stable visual evidence, small changes in spatial field-of-view produce large distributional shifts in output probabilities.

Spatial Decomposition

Each 224×224 input image is decomposed into five fixed spatial crops: four non-overlapping quadrants and one center crop overlapping each quadrant, providing complete spatial coverage with intentional double coverage of the diagnostically critical central region:

Crop coordinates (y1, x1, y2, x2):
  C1 = (  0,   0, 112, 112)   # top-left quadrant
  C2 = (  0, 112, 112, 224)   # top-right quadrant
  C3 = (112,   0, 224, 112)   # bottom-left quadrant
  C4 = (112, 112, 224, 224)   # bottom-right quadrant
  C5 = ( 56,  56, 168, 168)   # center crop (overlaps all quadrants)

Each crop is bilinearly upsampled to 224×224 before passing through the frozen model f. The aggregate local prediction is:

plocal(x)=15∑k=15f ⁣(upsample(x[Ck]))p_{\text{local}}(x) = \frac{1}{5} \sum_{k=1}^{5} f\!\left(\text{upsample}(x[\mathcal{C}_k])\right)

Together with $p_{\text{global}}(x) = f(x)$, this requires exactly six forward passes through an unmodified, frozen model.

Uncertainty Scoring via Jensen-Shannon Divergence

Multi-label tasks (Bernoulli JSD) — used for NIH, CheXpert, VinBigData, MS COCO

For each class $c$ with mixture $m_c = \frac{1}{2}(p_{\text{global},c} + p_{\text{local},c})$:

JSDc(p,q)=12 ⁣[pclog⁡pcmc+(1−pc)log⁡1−pc1−mc+qclog⁡qcmc+(1−qc)log⁡1−qc1−mc]\text{JSD}_c(p, q) = \frac{1}{2}\!\left[p_c \log\frac{p_c}{m_c} + (1-p_c)\log\frac{1-p_c}{1-m_c} + q_c\log\frac{q_c}{m_c} + (1-q_c)\log\frac{1-q_c}{1-m_c}\right]

MUS(x)=sbern(x)=1C∑c=1CJSDc(pglobal,c, plocal,c)\text{MUS}(x) = s_{\text{bern}}(x) = \frac{1}{C}\sum_{c=1}^{C} \text{JSD}_c(p_{\text{global},c},\, p_{\text{local},c})

Single-label tasks (Categorical JSD) — used for ImageNet

MUS(x)=scat(x)=JSD(pglobal∥plocal)=12KL(pglobal∥m)+12KL(plocal∥m)\text{MUS}(x) = s_{\text{cat}}(x) = \text{JSD}(p_{\text{global}} \| p_{\text{local}}) = \frac{1}{2}\text{KL}(p_{\text{global}} \| m) + \frac{1}{2}\text{KL}(p_{\text{local}} \| m)

where $m = \frac{1}{2}(p_{\text{global}} + p_{\text{local}})$ is the mixture distribution.

JSD is bounded in $[0, \log 2]$, symmetric, and well-defined under zero probability mass—properties that make it well-suited to sigmoid multi-label outputs.

Information-Theoretic Bound (Lemma 1)

The paper proves that a large MUS score necessarily implies a large mean absolute shift between global and local class probabilities:

1C∑c=1C∣pglobal,c−plocal,c∣≤2ln⁡2⋅sbern(x)\frac{1}{C}\sum_{c=1}^{C} |p_{\text{global},c} - p_{\text{local},c}| \leq \sqrt{2 \ln 2 \cdot s_{\text{bern}}(x)}

where $\sqrt{2 \ln 2} \approx 1.177$. This is a formal bound, not a correlation—spatial inconsistency bounds, rather than merely correlates with, prediction instability.

Optional Linear Fusion

For settings where a small labeled hold-out is available, logistic regression over four complementary signals yields further gains:

sfused(x)=σ ⁣(α0+α1s(x)+α2H(x)+α3(1−max⁡cpc)+α4dℓ1(x))s_{\text{fused}}(x) = \sigma\!\left(\alpha_0 + \alpha_1 s(x) + \alpha_2 H(x) + \alpha_3 (1 - \max_c p_c) + \alpha_4 d_{\ell_1}(x)\right)

where $H(x)$ is predictive entropy, $\max_c p_c$ is maximum confidence, and $d_{\ell_1}(x) = \frac{1}{C}\sum_c |p_{\text{global},c} - p_{\text{local},c}|$. Coefficients are estimated via 5-fold cross-validation on the validation set (or a 10% hold-out of the test set for zero-shot settings), preserving the zero-retraining property of the frozen backbone.


Algorithm

Algorithm: SpatialUQ (MUS Computation)

Input:  Frozen model f, image x ∈ ℝ^(224×224×3), task ∈ {single-label, multi-label}
Output: Scalar uncertainty score s(x) ≥ 0

1.  p_global ← sigmoid(f(x))                          # forward pass 1

2.  PATCH_COORDS ← [(0,0,112,112), (0,112,112,224),
                    (112,0,224,112), (112,112,224,224),
                    (56,56,168,168)]

3.  for k = 1 to 5:
        crop_k   ← x[PATCH_COORDS[k]]                 # spatial crop
        crop_k   ← bilinear_upsample(crop_k, 224×224) # restore resolution
        p_k      ← sigmoid(f(crop_k))                 # forward passes 2–6

4.  p_local ← (1/5) * Σ_k p_k                         # aggregate local

5.  if task == 'multi-label':
        s(x) ← (1/C) * Σ_c JSD_bernoulli(p_global_c, p_local_c)
    else:  # single-label
        m    ← 0.5 * (p_global + p_local)
        s(x) ← 0.5 * KL(p_global ∥ m) + 0.5 * KL(p_local ∥ m)

6.  return s(x)

Key properties:

  • Exactly 6 deterministic forward passes (1 global + 5 crops)
  • No stored state between calls; no model modification
  • All 6 passes can be batched in a single GPU call for efficiency
  • Applicable to any pretrained checkpoint including foundation models

Repository Structure

The repository is organized around four functional modules: backbone training, SpatialUQ evaluation (in-distribution and zero-shot), and natural image / detection experiments.

spatialuq/
│
├── README.md
│
├── notebooks/
│   │
│   ├── training/                          # Backbone fine-tuning on NIH ChestX-ray14
│   │   ├── train-nih-densenet121-ipynb.ipynb    # DenseNet-121 (primary backbone)
│   │   ├── train-nih-efficientnetb4.ipynb       # EfficientNet-B4
│   │   └── train-nih-vit16.ipynb               # ViT-B/16
│   │
│   ├── zeroshot_medical/                  # Zero-shot SpatialUQ on medical datasets
│   │   ├── zeroshot-nih-clip-vitb32.ipynb      # CLIP ViT-B/32 on NIH
│   │   ├── zeroshot-nih-biomedclip.ipynb       # BiomedCLIP on NIH
│   │   ├── zeroshot-nih-biovil-t.ipynb         # BioViL-T on NIH (failure regime)
│   │   ├── zeroshot-chexpert-densenet121.ipynb # NIH DenseNet-121 → CheXpert
│   │   └── zeroshot-vinbigdata-densenet121.ipynb # NIH DenseNet-121 → VinBigData
│   │
│   └── natural_images/                    # ImageNet & MS COCO experiments
│       ├── imagenet_efficientnetb4.ipynb  # ImageNet EfficientNet-B4
│       ├── imagenet_vit16.ipynb           # ImageNet ViT-B/16
│       ├── imagenet_convnexttiny.ipynb    # ImageNet ConvNeXt-Tiny
│       └── ms-coco-retinanet-fastercnn.ipynb # MS COCO Faster R-CNN & RetinaNet
│
├── outputs/                               # Saved results (auto-created)
│   ├── checkpoints/                       # Model weights (best_model.pt)
│   ├── figures/                           # Publication-quality plots (PDF)
│   ├── rich_audit_results.csv             # Per-image MUS scores (test set)
│   ├── val_audit_results.csv              # Per-image MUS scores (val set)
│   ├── test_probs.npy                     # Backbone sigmoid probabilities
│   ├── test_labels.npy                    # Ground truth labels
│   ├── mc_dropout_results.csv             # MC-Dropout baseline scores
│   └── backbone_eval.csv                  # Per-class backbone AUC/Brier/AP
│
└── requirements.txt

Note: All notebooks are self-contained and designed for execution on Kaggle (GPU environment). Paths reference Kaggle input directories; adapt CSV_PATH, IMG_ROOT, TRAIN_LIST, TEST_LIST, and SAVE_DIR for local execution.


Installation & Requirements

Python Environment

Tested with Python 3.9–3.11 and PyTorch 2.0+. CUDA 11.8+ is strongly recommended for training; inference (MUS scoring only) can run on CPU.

git clone https://github.com/your-org/spatialuq.git
cd spatialuq
pip install -r requirements.txt

requirements.txt

torch>=2.0.0
torchvision>=0.15.0
numpy>=1.24.0
pandas>=1.5.0
Pillow>=9.0.0
scikit-learn>=1.2.0
scipy>=1.10.0
matplotlib>=3.7.0
seaborn>=0.12.0
tqdm>=4.65.0
open_clip_torch>=2.20.0        # for CLIP ViT-B/32 and BiomedCLIP experiments
# hi-ml-multimodal             # for BioViL-T only (optional, uncomment if needed)

Foundation Model Dependencies

  • CLIP ViT-B/32: pip install open_clip_torch — weights downloaded automatically via OpenAI hub
  • BiomedCLIP: pip install open_clip_torch — weights loaded via hf-hub:microsoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224
  • BioViL-T (optional): pip install hi-ml-multimodal — requires health_multimodal package

Hardware

Experiment Minimum GPU Approx. Wall-Clock
DenseNet-121 training (NIH) 16 GB VRAM (T4) ~8 hours
EfficientNet-B4 training (NIH) 16 GB VRAM (T4) ~10 hours
ViT-B/16 training (NIH) 16 GB VRAM (T4) ~6 hours (early stop)
MUS scoring — DenseNet-121 (25k images) Any GPU ~8 min
MUS scoring — ViT-B/16 (25k images) Any GPU ~29 min
MC-Dropout baseline (T=30, DenseNet-121) Any GPU ~39 min

All MUS inference uses torch.no_grad() and can be run in a single batched call.


Usage

Minimal MUS Scoring on a Single Image

import torch
import torch.nn.functional as F
import numpy as np

PATCH_COORDS = [
    (0,   0,   112, 112),   # top-left
    (0,   112, 112, 224),   # top-right
    (112, 0,   224, 112),   # bottom-left
    (112, 112, 224, 224),   # bottom-right
    (56,  56,  168, 168),   # center
]

def js_divergence_bernoulli(p, q, eps=1e-8):
    """Bernoulli JSD between two probability tensors. Shape: (C,) → scalar."""
    m = 0.5 * (p + q)
    kl_pm = p * torch.log((p + eps) / (m + eps)) + \
            (1 - p) * torch.log((1 - p + eps) / (1 - m + eps))
    kl_qm = q * torch.log((q + eps) / (m + eps)) + \
            (1 - q) * torch.log((1 - q + eps) / (1 - m + eps))
    return 0.5 * (kl_pm + kl_qm)

@torch.no_grad()
def compute_mus(model, img_tensor, task='multi-label', device='cuda'):
    """
    Compute the Multicrop Uncertainty Score (MUS) for a single image.

    Args:
        model:       Frozen classifier, callable with img_tensor → logits/probs.
                     Must output raw probabilities (sigmoid applied internally if needed).
        img_tensor:  Tensor of shape (1, 3, 224, 224), ImageNet-normalized.
        task:        'multi-label' (Bernoulli JSD) or 'single-label' (Categorical JSD).
        device:      'cuda' or 'cpu'.

    Returns:
        float: MUS score ≥ 0 (higher = more uncertain).
    """
    img_tensor = img_tensor.to(device)
    model = model.to(device).eval()

    # Forward pass 1: global prediction
    p_global = torch.sigmoid(model(img_tensor)).squeeze(0)   # shape: (C,)

    # Forward passes 2–6: spatial crops
    crop_probs = []
    for (y1, x1, y2, x2) in PATCH_COORDS:
        crop = img_tensor[:, :, y1:y2, x1:x2]
        crop_up = F.interpolate(crop, size=(224, 224), mode='bilinear', align_corners=False)
        p_crop = torch.sigmoid(model(crop_up)).squeeze(0)    # shape: (C,)
        crop_probs.append(p_crop)

    p_local = torch.stack(crop_probs).mean(dim=0)            # shape: (C,)

    if task == 'multi-label':
        mus = js_divergence_bernoulli(p_global, p_local).mean().item()
    else:  # single-label (softmax outputs)
        m = 0.5 * (p_global + p_local)
        eps = 1e-8
        kl_pm = (p_global * torch.log((p_global + eps) / (m + eps))).sum()
        kl_qm = (p_local  * torch.log((p_local  + eps) / (m + eps))).sum()
        mus = (0.5 * (kl_pm + kl_qm)).item()

    return mus


# Example usage
from torchvision import transforms, models
from PIL import Image

transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
])

# Load your frozen model
model = models.densenet121(weights='IMAGENET1K_V1')
model.eval()

img = Image.open("chest_xray.png").convert("RGB")
img_tensor = transform(img).unsqueeze(0)

mus_score = compute_mus(model, img_tensor, task='multi-label')
print(f"MUS score: {mus_score:.6f}")
# Higher MUS → higher predicted failure probability

Batched MUS Scoring (Efficient — Recommended for Full Datasets)

@torch.no_grad()
def compute_mus_batch(model, imgs, task='multi-label', device='cuda'):
    """
    Efficient batched MUS computation: all 6 forward passes in one concatenated call.

    Args:
        model:  Frozen classifier.
        imgs:   Tensor of shape (B, 3, 224, 224).
        task:   'multi-label' or 'single-label'.
        device: 'cuda' or 'cpu'.

    Returns:
        np.ndarray: MUS scores, shape (B,).
    """
    imgs = imgs.to(device)
    B = imgs.size(0)

    # Global pass
    p_global = torch.sigmoid(model(imgs))      # (B, C)

    # Concatenate all 5 crops into one batch → single forward pass
    crop_list = []
    for (y1, x1, y2, x2) in PATCH_COORDS:
        crop = F.interpolate(
            imgs[:, :, y1:y2, x1:x2],
            size=(224, 224), mode='bilinear', align_corners=False
        )
        crop_list.append(crop)

    patch_batch = torch.cat(crop_list, dim=0)              # (5B, C, H, W)
    p_patches = torch.sigmoid(model(patch_batch))          # (5B, num_classes)
    p_patches = p_patches.view(5, B, -1)                   # (5, B, C)
    p_local = p_patches.mean(dim=0)                        # (B, C)

    if task == 'multi-label':
        jsd_per_class = js_divergence_bernoulli(p_global, p_local)  # (B, C)
        mus = jsd_per_class.mean(dim=1).cpu().numpy()               # (B,)
    else:
        m = 0.5 * (p_global + p_local)
        eps = 1e-8
        kl_pm = (p_global * torch.log((p_global + eps) / (m + eps))).sum(dim=1)
        kl_qm = (p_local  * torch.log((p_local  + eps) / (m + eps))).sum(dim=1)
        mus = (0.5 * (kl_pm + kl_qm)).cpu().numpy()

    return mus

Reproducing Main Experiments

All experiments are implemented as self-contained Jupyter notebooks. The workflow within each notebook follows this order:

Step 1 — Backbone Training (NIH ChestX-ray14 only)

Open and run notebooks/training/train-nih-densenet121-ipynb.ipynb on Kaggle with the NIH ChestX-ray14 dataset. Set USE_SUBSET = False for full training. Key cells:

  • Cell 1: Setup, constants, JSD helpers, crop coordinates
  • Cell 2: Dataset loading and patient-level splits
  • Cell 3: Two-stage fine-tuning (Stage 1: frozen backbone, Stage 2: full unfreeze)
  • Cell 4: Backbone evaluation (per-class AUC, Brier, AP)
  • Cell 5: MUS audit across all crop counts
  • Cells 5.1–5.4: Baselines (TTA, L1, normalization ablation)
  • Cell 7: Crop count ablation
  • Cell 8: Per-class MUS analysis
  • Cell 9: MC-Dropout baseline

Step 2 — Zero-Shot / Foundation Model Evaluation

Run the appropriate notebook from notebooks/zeroshot_medical/:

# CLIP ViT-B/32 on NIH test set
notebooks/zeroshot_medical/zeroshot-nih-clip-vitb32.ipynb

# BiomedCLIP on NIH test set
notebooks/zeroshot_medical/zeroshot-nih-biomedclip.ipynb

# Domain transfer: NIH DenseNet-121 → CheXpert
notebooks/zeroshot_medical/zeroshot-chexpert-densenet121.ipynb

# Domain transfer: NIH DenseNet-121 → VinBigData (severe shift regime)
notebooks/zeroshot_medical/zeroshot-vinbigdata-densenet121.ipynb

Step 3 — Natural Image & Detection Experiments

# ImageNet-1k (50,000 images, three architectures)
notebooks/natural_images/imagenet_efficientnetb4.ipynb
notebooks/natural_images/imagenet_vit16.ipynb
notebooks/natural_images/imagenet_convnexttiny.ipynb

# MS COCO 2014 (5,000 images, two detectors)
notebooks/natural_images/ms-coco-retinanet-fastercnn.ipynb

Evaluating Failure Detection (AUC + Calibration)

All notebooks compute the following after running MUS:

from sklearn.metrics import roc_auc_score
import numpy as np

# Load results
mus_scores = rich_df['mus'].values
brier_scores = rich_df['brier'].values

# Failure label: Brier score exceeds 75th percentile
threshold = np.percentile(brier_scores, 75)
y_failure = (brier_scores > threshold).astype(int)

# Failure detection AUC
auc = roc_auc_score(y_failure, mus_scores)
print(f"MUS Failure Detection AUC: {auc:.4f}")

# Score Calibration Error (SCE): ECE on min-max normalized scores
def compute_sce(y_true, scores, n_bins=15):
    scores_norm = (scores - scores.min()) / (scores.max() - scores.min() + 1e-9)
    bins = np.linspace(0, 1, n_bins + 1)
    sce = 0.0
    n = len(y_true)
    for lo, hi in zip(bins[:-1], bins[1:]):
        mask = (scores_norm >= lo) & (scores_norm < hi)
        if mask.sum() == 0:
            continue
        sce += (mask.sum() / n) * abs(y_true[mask].mean() - scores_norm[mask].mean())
    return sce

sce = compute_sce(y_failure, mus_scores)
print(f"SCE: {sce:.4f}")

Checking the ρ Diagnostic (Deployment Gate)

Before deploying MUS, verify that the spatial consistency signal is meaningful for your target domain using a small labeled calibration sample:

from scipy.stats import spearmanr

rho, pval = spearmanr(mus_scores, brier_scores)
print(f"Spearman ρ(MUS, Brier) = {rho:.3f}  (p = {pval:.2e})")

if abs(rho) < 0.15:
    print("WARNING: ρ < 0.15 — severe domain shift detected.")
    print("MUS is unreliable in this regime. Prefer MC-Dropout or deep ensembles.")
else:
    print("MUS is reliable for this domain. Proceed with threshold-based deployment.")

In this study, the diagnostic correctly identified every failure regime: NIH (ρ=0.523), CheXpert (ρ=0.298), VinBigData (ρ=0.027, correctly flagged), BioViL-T (ρ=−0.187, correctly flagged).


Datasets

NIH ChestX-ray14 (Primary)

  • Source: NIH Clinical Center | Kaggle
  • Size: 112,120 frontal chest X-rays, 14 multi-label disease classes
  • Access: Publicly available; no registration required
  • Splits used: Official train_val_list.txt / test_list.txt with patient-level 15% validation holdout → 73,891 / 12,633 / 25,596 train/val/test
Data_Entry_2017.csv          # Labels and metadata
train_val_list.txt           # Official train+val file list
test_list.txt                # Official test file list
images*/images/*.png         # Image files (12 zip archives)

Preprocessing: Resize to 256, RandomRotation(±10°), RandomCrop(224×224). No horizontal flip (preserves anatomical laterality). Normalize with ImageNet mean/std. Class-balanced BCE with label smoothing (ε=0.1).

CheXpert (Zero-Shot Transfer)

  • Source: Stanford ML Group
  • Size: 224,316 chest X-rays; evaluation on 44,399 test images (10 NIH-overlapping classes)
  • Access: Requires registration
  • Label mapping: 10 overlapping classes; uncertain labels treated as negative (U-Zeros)

VinBigData (Severe Domain Shift)

  • Source: VinDr-CXR | Kaggle
  • Size: 15,000 chest X-rays (9 NIH-overlapping classes)
  • Access: Publicly available on Kaggle
  • Label mapping: 9 classes; bounding box annotations converted to image-level binary labels

ImageNet-1k (Natural Image Validation)

  • Source: ILSVRC2012 on Kaggle
  • Size: 50,000 validation images, 1,000 classes
  • Access: Kaggle competition dataset
  • Models: Zero-shot evaluation using torchvision pretrained weights

MS COCO 2014 (Object Detection)

  • Source: COCO Dataset
  • Size: 5,000-image reproducible subset (seed=42), 80 categories
  • Models: Faster R-CNN and RetinaNet (ResNet-50-FPN) from torchvision
  • MUS formulation: Multi-label Bernoulli JSD over 80-dimensional per-class confidence vectors (detection confidence = max score across boxes, threshold 0.1)

Experiments & Results

NIH ChestX-ray14 — In-Distribution Failure Detection (DenseNet-121)

Failure defined as Brier score exceeding the 75th percentile (threshold=0.5607; 25% failure rate).

Method AUC 95% CI SCE Forward Passes
Fusion (MUS+Ent+Conf+L1) 0.832 [0.827, 0.837] 0.246 6 + logistic
Deep Ensemble (5-member) 0.813 [0.808, 0.819] 0.138 5×model
L1 Distance 0.790 [0.785, 0.796] 0.127 6
MUS (SpatialUQ, ours) 0.784 [0.778, 0.789] 0.049 6
Deep Ensemble + T-scaling 0.774 [0.768, 0.780] 0.090 5×model
ODIN 0.759 [0.752, 0.765] 0.484 1+grad
TTA-JSD (Photometric) 0.755 [0.750, 0.761] 0.043 6
DDU Score 0.754 [0.748, 0.760] 0.139 1 (+ training features)
Mahalanobis 0.754 [0.748, 0.760] 0.283 1 (+ training features)
MC-Dropout (T=30) 0.664 [0.658, 0.671] 0.121 30
TTA Variance (N=10) 0.584 [0.576, 0.591] 0.089 10
Confidence⁻¹ 0.401 [0.392, 0.409] 0.422 1
Entropy 0.177 [0.173, 0.182] 0.458 1

Key observations:

  • MUS achieves 0.784 AUC with only 6 deterministic passes, outperforming MC-Dropout (+0.120 AUC) at 5× less compute
  • MUS has the best calibration among practically viable methods (SCE=0.049 vs. 0.127 for L1, 0.121 for MC-Dropout)
  • Entropy achieves only 0.177 AUC—below chance—due to systematic overconfidence under BCE training; MUS is immune to this failure mode
  • Fusion surpasses the five-member deep ensemble (0.832 vs. 0.813, Δ=+0.019, p<10⁻⁶) without any retraining

Foundation Model Scaling

MUS scales with model quality—stronger spatial representations yield stronger spatial consistency signals:

Model MUS AUC Spearman ρ Fusion AUC
DenseNet-121 (fine-tuned) 0.784 0.523 0.832
CLIP ViT-B/32 (zero-shot) 0.825 0.631 0.883
BiomedCLIP (zero-shot) 0.899 0.846 0.925

Zero-Shot Domain Transfer

Dataset MUS AUC Fusion AUC MC-Dropout AUC Spearman ρ
NIH (in-distribution) 0.784 0.832 0.664 0.523
CheXpert (moderate shift) 0.708 0.733 0.599 0.298
VinBigData (severe shift) 0.614 0.750 0.764 0.027 ← flagged

VinBigData represents the identified failure regime: severe covariate shift causes the model to fail uniformly across global and local views, collapsing the inconsistency gradient. The ρ diagnostic (ρ=0.027 < 0.15) correctly flags this regime, at which point MC-Dropout should be preferred.

ImageNet-1k & MS COCO

On well-calibrated single-label classifiers (ImageNet), confidence already tracks correctness directly; MUS serves as a complementary secondary signal:

Dataset Model MUS AUC Confidence⁻¹ AUC Fusion AUC Spearman ρ
ImageNet EfficientNet-B4 0.717 0.913 0.917 0.392
ImageNet ViT-B/16 0.710 0.923 0.937 0.341
ImageNet ConvNeXt-Tiny 0.641 0.913 0.936 0.139
MS COCO Faster R-CNN 0.800 0.602 0.885 0.613
MS COCO RetinaNet 0.747 0.702 0.913 0.510

On MS COCO, MUS is the primary complementary signal to entropy (0.884/0.912 standalone)—unlike ImageNet where confidence dominates, the multi-label detection setting produces richer spatial inconsistency signals.

Per-Class Analysis (NIH DenseNet-121)

MUS discriminability depends strongly on lesion spatial extent:

Pathology JSD AUC Type
Pneumonia 0.979 Diffuse
Edema 0.971 Diffuse
Consolidation 0.956 Diffuse
Cardiomegaly 0.952 Diffuse
Atelectasis 0.915 Diffuse
Emphysema 0.670 Mixed
Mass 0.558 Focal
Fibrosis 0.553 Focal
Nodule 0.368 Focal (small)

Diffuse pathologies (group mean JSD AUC=0.944) substantially outperform localized lesions (0.603). A multi-scale extension using a 16-crop 56×56 fine grid partially recovers Nodule performance (0.368 → 0.589 AUC).

Clinical Triage Simulation

Using a validation-calibrated threshold at 95% sensitivity on NIH DenseNet-121:

  • Refers 9.2% of images [CI: 8.8%, 9.5%] to human review
  • Recovers 20% of all prediction failures at 54.5% referral precision
  • Misses only 1.43% of critical findings (below the 1.5% clinical requirement)
  • Demographic fairness: Female AUC 0.784 vs. Male AUC 0.784 (near-perfect parity)

Reproducibility Notes

Random Seeds

All experiments use SEED = 42 throughout:

import random, numpy as np, torch, os
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed_all(SEED)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ['PYTHONHASHSEED'] = str(SEED)

Stability

MUS AUC variance across 5 random seeds (42, 186, 456, 789, 1011) on NIH DenseNet-121: mean=0.786 ± 0.003, confirming low seed-induced variance and stable behavior.

Caching

All notebooks implement result caching (.npy/.csv files with done.flag markers). Re-running a cell skips computation if cached results exist, enabling safe interruption and resumption.

Hardware

  • All NIH training: NVIDIA Tesla T4 (Kaggle free tier)
  • Inference: Any CUDA-capable GPU; CPU inference is functional but slow for large datasets

Statistical Testing

All AUC comparisons use:

  • 95% bootstrap confidence intervals (1,000 resamples)
  • DeLong tests for pairwise AUC significance
  • Two-tailed bootstrap p-values (10,000 resamples)

Limitations

SpatialUQ has four bounded failure conditions:

  1. Severe covariate shift (e.g., VinBigData): When the model fails uniformly across global and local views, the inconsistency gradient collapses (ρ=0.027). In this regime, MC-Dropout or deep ensembles are preferred. The ρ<0.15 diagnostic on a small labeled calibration sample correctly identifies this condition.

  2. Small focal lesions: The five-crop decomposition operates at 112×112 pixel resolution; pathologies smaller than ~3 cm in diameter fall below the resolution limit. Nodule JSD AUC = 0.368 on DenseNet-121 (partially recoverable with a 16-crop fine grid: 0.589). EfficientNet-B4's compound scaling largely mitigates this issue (Nodule JSD AUC = 0.882).

  3. Global-attention architectures (ViT): ViT's global self-attention produces spatially coherent crop-level predictions regardless of evidence localization, compressing MUS dynamic range. Masking-based crops (zeroing non-crop regions to ImageNet mean) yield marginal improvement (ΔAUC=+0.008) for ViT but degrade convolutional models significantly.

  4. Fusion requires a small labeled hold-out: The optional logistic fusion (which surpasses deep ensembles) requires a labeled calibration sample to estimate the four regression coefficients. The unsupervised MUS score requires no labels.

  5. Globally pooled generative VLMs (e.g., BioViL-T): Image encoders trained via global contrastive alignment produce spatially uniform crop-level representations, eliminating the inconsistency gradient. MUS collapses to AUC=0.533 on BioViL-T (correctly flagged by ρ=-0.187<0.15).

When to use SpatialUQ: Overconfident multi-label classifiers under moderate domain shift where retraining is infeasible. When to prefer alternatives: Severe covariate shift (use MC-Dropout/ensembles); globally pooled VLMs (use entropy/confidence); single-label well-calibrated classifiers on natural images (confidence already dominates).


Citation

If you use SpatialUQ in your research, please cite:

@inproceedings{spatialuq2026,
  title     = {{SpatialUQ}: Post-Hoc Uncertainty Quantification from Spatial Consistency
               in Black-Box Vision Models},
  author    = {Anonymous Author(s)},
  booktitle = {Advances in Neural Information Processing Systems (NeurIPS)},
  year      = {2026},
  note      = {Submitted to the 40th Conference on Neural Information Processing Systems}
}

License

This project is released under the MIT License. See LICENSE for details.

All datasets used (NIH ChestX-ray14, CheXpert, VinBigData, ImageNet-1k, MS COCO) are subject to their own respective licenses and terms of use. Pretrained model weights use standard torchvision/timm licenses (Apache 2.0). Please review the applicable license for each dataset and model before use.


Acknowledgements

This work uses publicly available de-identified medical imaging datasets. We thank the NIH Clinical Center, Stanford ML Group, VinDr team, and the MS COCO consortium for making their datasets publicly available for research.

Downloads last month
284