Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
2333cdd
Initial pass LRP
Nimanui Jan 26, 2026
c0d766a
Update Notebook
Nimanui Jan 26, 2026
44455a3
Some cleanup
Nimanui Jan 26, 2026
e76dd1b
More cleanup
Nimanui Jan 26, 2026
7e8a279
more clean up
Nimanui Jan 30, 2026
dec963c
Fixing unit tests
Nimanui Feb 13, 2026
5881140
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Mar 15, 2026
ea28a0d
Adding more examples
Nimanui Mar 15, 2026
3ca3469
Clean up
Nimanui Mar 20, 2026
fdaa8d8
Test fixes and cleaning up some examples
Nimanui Mar 29, 2026
e01c151
Testing and refactoring for some initial review comments
Nimanui Apr 17, 2026
be16931
Fix tests
Nimanui Apr 17, 2026
8da6744
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Apr 24, 2026
6354deb
Review comments and improvements
Nimanui Apr 24, 2026
1398365
Review comments and test updates
Nimanui Jun 10, 2026
f740cde
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Jun 10, 2026
a7d80c9
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Jul 20, 2026
8800ba5
Merge remote-tracking branch 'origin/master' into lrp-for-review
Nimanui Sep 11, 2026
24cccbe
Clean-up
Nimanui Sep 25, 2026
06bceb6
Merge branch 'master' into lrp-for-review
Logiquo Oct 20, 2026
f1d253d
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Oct 27, 2026
20e30f5
Merge remote-tracking branch 'sunlabuiuc/master' into lrp-for-review
Nimanui Nov 3, 2026
ab5604f
Move examples to a follow-up PR and trim LRP tests
Nimanui Nov 3, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 3 additions & 6 deletions docs/api/interpret.rst
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
Interpretability
===============
================

We implement the following interpretability techniques to help you understand model predictions and identify important features in healthcare data.

Expand All @@ -13,7 +13,7 @@ New to interpretability in PyHealth? Check out these complete examples:

**Basic Gradient Example:**

- ``examples/ChestXrayClassificationWithSaliency.ipynb`` - Interactive notebook demonstrating gradient-based saliency mapping for medical image classification. Shows how to:
- ``examples/cxr/ChestXrayClassificationWithSaliency.ipynb`` - Interactive notebook demonstrating gradient-based saliency mapping for medical image classification. Shows how to:

- Load and classify chest X-ray images using PyHealth's TorchvisionModel
- Generate gradient saliency maps to visualize model attention
Expand Down Expand Up @@ -81,14 +81,11 @@ Attribution Methods
interpret/pyhealth.interpret.methods.chefer
interpret/pyhealth.interpret.methods.attention_rollout
interpret/pyhealth.interpret.methods.deeplift
interpret/pyhealth.interpret.methods.lrp

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Existing API doc pages removed from the toctree without explanation

The toctree drops interpret/pyhealth.interpret.methods.ig_gim, ensemble, baseline and base_interpreter. Their RST files still exist under docs/api/interpret/, so Sphinx will report them as not included in any toctree, and the public API for those classes disappears from the rendered docs. The PR description does not mention this. Restore those entries, or move the removal into a separate, explained change.

interpret/pyhealth.interpret.methods.integrated_gradients
interpret/pyhealth.interpret.methods.shap
interpret/pyhealth.interpret.methods.lime
interpret/pyhealth.interpret.methods.tree_shap
interpret/pyhealth.interpret.methods.ig_gim
interpret/pyhealth.interpret.methods.ensemble
interpret/pyhealth.interpret.methods.baseline
interpret/pyhealth.interpret.methods.base_interpreter

Visualization Utilities
-----------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ classification models. This helps identify which regions of medical images most
model's prediction by visualizing gradients of model outputs with respect to input pixels.

For a complete working example, see:
``examples/ChestXrayClassificationWithSaliency.ipynb``
``examples/cxr/ChestXrayClassificationWithSaliency.ipynb``

API Reference
-------------
Expand Down
124 changes: 124 additions & 0 deletions docs/api/interpret/pyhealth.interpret.methods.lrp.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
pyhealth.interpret.methods.lrp
===============================

Overview
--------

Layer-wise Relevance Propagation (LRP) explains a prediction by redistributing
the model's output score backwards through the network, layer by layer, until
every input feature carries a share of the relevance. Unlike gradient-based
saliency, which measures local sensitivity, LRP conserves a *quantity* of
relevance as it flows, so attributions are directly comparable across features
of the same sample.

The implementation follows Bach et al. (2015), "On Pixel-Wise Explanations for
Non-Linear Classifier Decisions by Layer-Wise Relevance Propagation"
(https://doi.org/10.1371/journal.pone.0130140), with the local-renormalization
handling of Binder et al. (2016) (https://arxiv.org/abs/1604.00825).

This method is particularly useful for:

- **Multi-modal EHR models**: Attributing a prediction across discrete codes and continuous labs in one pass
- **Medical imaging**: Producing pixel-level relevance heatmaps for CNN classifiers
- **Model debugging**: Checking that relevance concentrates on clinically meaningful inputs
- **Method comparison**: Serving as a conservation-based counterpart to gradient and perturbation methods

Propagation Rules
-----------------

- ``rule="epsilon"`` — the :math:`\varepsilon`-rule stabilises the denominator
with :math:`z_j + \varepsilon \cdot \mathrm{sign}(z_j)`. Larger ``epsilon``
absorbs more relevance and yields sparser, less noisy attributions.
- ``rule="alphabeta"`` — the :math:`\alpha\beta`-rule separates positive and
negative contributions and recombines them as
:math:`\alpha R^{+} - \beta R^{-}`, with ``alpha - beta == 1`` by convention.
The split is taken over the *contributions* :math:`z_{ij} = x_i w_{ij}`, not
over the weights alone -- for :math:`x_i < 0` a positive weight yields a
negative contribution, so both the input and the weight are split. With
``beta=0`` the negative path is disabled and relevance keeps the sign of the
output relevance.

Layer Handlers
--------------

Per-layer propagation lives in :mod:`pyhealth.interpret.methods.lrp_base`, which
defines an abstract :class:`~pyhealth.interpret.methods.lrp_base.LRPLayerHandler`
and an :class:`~pyhealth.interpret.methods.lrp_base.LRPHandlerRegistry` that maps
a layer type to its handler. ``LayerwiseRelevancePropagation`` builds a registry
at construction and dispatches each layer through it, so support for a custom
layer can be added without subclassing the interpreter::

lrp._registry.register(MyLayerHandler())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Docs advertise the private _registry attribute as an extension point

The docs tell users to call lrp._registry.register(...) to add a custom layer handler. Documenting a leading-underscore attribute as public API makes it hard to change later. Expose a public register_handler method on LayerwiseRelevancePropagation and document that instead.


Handlers ship for ``Linear``, ``Conv2d``, ``ReLU``, ``MaxPool2d``, ``AvgPool2d``,
``AdaptiveAvgPool2d``, ``Flatten``, ``BatchNorm2d``, ``Dropout`` and the
recurrent ``LSTM``/``GRU`` layers. Layer types with no registered handler pass
relevance through unchanged.

Usage Notes
-----------

1. **Batch size**: Use ``batch_size=1`` for per-sample explanations.
2. **Evaluation mode**: Call ``model.eval()`` first so dropout and batch-norm
behave deterministically.
3. **Embeddings**: With ``use_embeddings=True`` the model must implement the
:class:`~pyhealth.interpret.api.Interpretable` interface (or expose both
``forward_from_embedding`` and ``get_embedding_model``), and relevance is
propagated from the embedding output rather than the raw token indices.
4. **Conservation is approximate**: Per-layer conservation is exact only for a
bias-free linear layer under the :math:`\varepsilon`-rule. Biases, the
stabiliser itself, and pooling all absorb relevance, so
``sum(attributions)`` tracks the logit rather than matching it exactly. The
gap is largest for models whose logit is small relative to their biases.
5. **Recurrent models**: ``StageNet`` applies the same ``nn.Linear`` repeatedly
inside a Python loop, so a forward hook retains only the final time step.
Relevance for recurrent layers is therefore distributed uniformly across
time steps, and per-time-step attributions from these models should be read
as a feature-level summary rather than a precise temporal attribution.

Quick Start
-----------

.. code-block:: python

from pyhealth.datasets import get_dataloader
from pyhealth.interpret.methods import LayerwiseRelevancePropagation
from pyhealth.models import StageNet

# Assume you have a trained model and dataset
model = StageNet(dataset=sample_dataset)
# ... train the model ...
model.eval()

# Per-sample explanations
test_loader = get_dataloader(test_dataset, batch_size=1, shuffle=False)
batch = next(iter(test_loader))

lrp = LayerwiseRelevancePropagation(
model, rule="epsilon", epsilon=0.01, use_embeddings=True
)
attributions = lrp.attribute(**batch)

for feature_key, relevance in attributions.items():
print(f"{feature_key}: {relevance.shape}, total={relevance.sum():.4f}")

For complete working examples, see:

- ``examples/interpretability/lrp_stagenet_synthetic.py`` — self-contained run on synthetic data, no external dataset required

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Docs reference example files that do not exist

The Quick Start section lists three example files: examples/interpretability/lrp_stagenet_synthetic.py, examples/interpretability/lrp_stagenet_mimic4.py and examples/ChestXray-Classification-ResNet-with-Saliency.ipynb. None of them exists in the repository, and the PR does not add them. Either add the examples in this PR or remove these references (and the matching note in the PR description about pruning examples) so the docs do not point to missing files.

- ``examples/interpretability/lrp_stagenet_mimic4.py`` — mortality prediction on MIMIC-IV
- ``examples/ChestXray-Classification-ResNet-with-Saliency.ipynb`` — LRP heatmaps on chest X-rays, compared against gradient saliency

API Reference
-------------

.. autoclass:: pyhealth.interpret.methods.LayerwiseRelevancePropagation
:members:
:undoc-members:
:show-inheritance:
:member-order: bysource

.. automodule:: pyhealth.interpret.methods.lrp_base
:members:
:undoc-members:
:show-inheritance:
:member-order: bysource
12 changes: 10 additions & 2 deletions pyhealth/interpret/methods/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,29 @@
from pyhealth.interpret.methods.ensemble_crh import CrhEnsemble
from pyhealth.interpret.methods.ensemble_avg import AvgEnsemble
from pyhealth.interpret.methods.ensemble_var import VarEnsemble
from pyhealth.interpret.methods.lrp import LayerwiseRelevancePropagation
from pyhealth.interpret.methods.saliency_visualization import (
SaliencyVisualizer,
visualize_attribution,
)

__all__ = [
"BaseInterpreter",
"BasicGradientSaliencyMaps",
"CheferRelevance",
"AttentionRollout",
"DeepLift",
"GIM",
"IntegratedGradientGIM",
"IntegratedGradients",
"BasicGradientSaliencyMaps",
"RandomBaseline",
"LayerwiseRelevancePropagation",
"SaliencyVisualizer",
"visualize_attribution",
"ShapExplainer",
"LimeExplainer",
"TreeSHAP",
"CrhEnsemble",
"AvgEnsemble",
"VarEnsemble"
"VarEnsemble",
]
108 changes: 48 additions & 60 deletions pyhealth/interpret/methods/basic_gradient.py
Comment thread
Nimanui marked this conversation as resolved.
Resolved
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import torch
import numpy as np
from typing import Dict

from pyhealth.interpret.methods.base_interpreter import BaseInterpreter


class BasicGradientSaliencyMaps(BaseInterpreter):
"""Compute gradient-based saliency maps for image classification models.

Expand All @@ -28,47 +28,43 @@ class BasicGradientSaliencyMaps(BaseInterpreter):
where c iterates over color channels (RGB or grayscale)

Examples:
Basic usage with a batch::

from pyhealth.interpret.methods.basic_gradient import BasicGradientSaliencyMaps
import matplotlib.pyplot as plt

# Create batch
batch = {
'image': torch.randn(2, 3, 224, 224),
'disease': torch.tensor([0, 1])
}

# Compute saliency maps
saliency = BasicGradientSaliencyMaps(model, input_batch=batch)

# Visualize
saliency.visualize_saliency_map(
plt,
image_index=0,
title="Saliency Map",
id2label={0: "Normal", 1: "COVID"}
)

Using the attribute() interface::

# Initialize without batch
saliency = BasicGradientSaliencyMaps(model)

# Compute attributions for new data
attributions = saliency.attribute(**batch)
# Returns: {'image': tensor with saliency maps}

# Save to batch history
attributions = saliency.attribute(save_to_batch=True, **batch)

>>> import torch
>>> import matplotlib.pyplot as plt
>>> from pyhealth.interpret.methods.basic_gradient import (
... BasicGradientSaliencyMaps,
... )
>>>
>>> batch = {
... "image": torch.randn(2, 3, 224, 224),
... "disease": torch.tensor([0, 1]),
... }
>>> # ... train an image classification model ...
>>>
>>> # Compute saliency maps up front for a batch
>>> saliency = BasicGradientSaliencyMaps(model, input_batch=batch)
>>> saliency.visualize_saliency_map(
... plt,
... image_index=0,
... title="Saliency Map",
... id2label={0: "Normal", 1: "COVID"},
... )
>>>
>>> # Or use the attribute() interface on new data
>>> saliency = BasicGradientSaliencyMaps(model)
>>> attributions = saliency.attribute(**batch)
>>> # Returns dict: {"image": tensor of saliency maps}
>>> attributions["image"].shape # [batch, H, W]
>>>
>>> # Append the result to the interpreter's batch history
>>> attributions = saliency.attribute(save_to_batch=True, **batch)

Note:
- Do not use within ``torch.no_grad()`` context as gradients are required
- Works with any PyHealth image classification model
- For best results, normalize input images consistently with training

See Also:
- ``examples/ChestXrayClassificationWithSaliency.ipynb``: Complete tutorial
- ``examples/cxr/ChestXrayClassificationWithSaliency.ipynb``: Complete tutorial
- :class:`~pyhealth.interpret.methods.IntegratedGradients`: Alternative attribution method
"""
def __init__(self, model, input_batch=None, image_key='image', label_key='disease'):
Expand Down Expand Up @@ -99,7 +95,7 @@ def __init__(self, model, input_batch=None, image_key='image', label_key='diseas
if input_batch is not None:
self._compute_saliency_maps()

def attribute(self, save_to_batch=False, **data) -> Dict[str, torch.Tensor]:
def attribute(self, save_to_batch=False, **data) -> dict[str, torch.Tensor]:
"""Compute attribution scores for input features.

This method implements the BaseInterpreter interface by computing
Expand Down Expand Up @@ -210,13 +206,18 @@ def _process_batch(self, batch):
def visualize_saliency_map(self, plt, *, image_index, title=None, id2label=None, alpha=0.3):
"""Display an image with its saliency map overlay.

This method uses the SaliencyVisualizer for rendering and adds model
prediction information to the visualization.

Args:
plt: matplotlib.pyplot instance
image_index: Index of image within batch
title: Optional title for the plot
id2label: Optional dictionary mapping class indices to labels
alpha: Transparency of saliency overlay (default: 0.3)
"""
from pyhealth.interpret.methods.saliency_visualization import SaliencyVisualizer

if plt is None:
import matplotlib.pyplot as plt

Expand Down Expand Up @@ -258,26 +259,13 @@ def visualize_saliency_map(self, plt, *, image_index, title=None, id2label=None,
title = f"True: {true_label_str}, Predicted: {pred_label_str}"
else:
title = f"{title} - True: {true_label_str}, Predicted: {pred_label_str}"

# Convert image to numpy for display
if img_tensor.dim() == 4:
img_tensor = img_tensor[0]
img_np = img_tensor.detach().cpu().numpy()
if img_np.shape[0] in [1, 3]: # CHW to HWC
img_np = np.transpose(img_np, (1, 2, 0))
if img_np.shape[-1] == 1:
img_np = img_np.squeeze(-1)

# Convert saliency to numpy
if saliency.dim() > 2:
saliency = saliency[0]
saliency_np = saliency.detach().cpu().numpy()

# Create visualization
plt.figure(figsize=(15, 7))
plt.axis('off')
plt.imshow(img_np, cmap='gray')
plt.imshow(saliency_np, cmap='hot', alpha=alpha)
if title:
plt.title(title)
plt.show()
# Use SaliencyVisualizer for rendering
visualizer = SaliencyVisualizer(default_alpha=alpha)
visualizer.plot_saliency_overlay(
plt,
image=img_tensor[0],
saliency=saliency,
title=title,
alpha=alpha
)
Loading
Loading