peal.explainers.lrp_explainer.LRPExplainer

class peal.explainers.lrp_explainer.LRPExplainer[source]

Bases: object

Heatmap explainer using zennit Integrated Gradients with an LRP composite.

The explainer config (a yaml path or loaded config) is read for the keys predictor (fallback if none is passed), data_config (fallback to the predictor’s data config), canonizers (list of keys into CANONIZERS), composite_kwargs (forwarded to EpsilonGammaBox), explanations_dir and max_samples.

Parameters:
  • explainer_config (str or dict-like) – Path to the explainer yaml or an already loaded config.

  • predictor (torch.nn.Module or str, optional) – Model or path to a model; resolved through get_predictor.

  • num_classes (int, optional) – Number of output classes, used to build one-hot targets.

  • datasets (sequence, optional) – (train, val) datasets; when omitted they are created from the data config.

Variables:
  • attributor (zennit.attribution.IntegratedGradients) – The attributor whose context manager is entered in explain_batch.

  • predictor_datasets (sequence) – The first two datasets (train, val); run iterates over the second.

Methods

explain_batch

Compute attribution heatmaps for a batch of images.

run

Explain the validation split and write one image per sample.

__init__(explainer_config, predictor=None, num_classes=None, datasets=None)[source]
explain_batch(batch, labels)[source]

Compute attribution heatmaps for a batch of images.

Parameters:
  • batch (torch.Tensor) – Images of shape (N, C, H, W) (a single (C, H, W) image works as well since the attributor broadcasts).

  • labels (torch.Tensor or int) – Class index per image; turned into one-hot targets with num_classes entries.

Returns:

  • heatmaps (torch.Tensor) – Shape (N, 3, H, W): per-pixel relevance (input-normalised, summed over channels, scaled to [0, 1] per image, squared and repeated over three channels) on CPU.

  • overlays (torch.Tensor) – Shape (N, 3, H, W): zennit imgify renderings of the raw attributions with the wred colormap.

  • predictions (torch.Tensor) – Shape (N,): argmax of the model output on CPU.

run(*args, **kwargs)[source]

Explain the validation split and write one image per sample.

Iterates over predictor_datasets[1] (enabling hints if the dataset has them), predicts each sample, attributes the predicted class and saves explanation_<i>.png (input stacked with its heatmap) into explainer_config.explanations_dir. Stops after explainer_config.max_samples samples when that is set.

Returns:

Keys "heatmap", "x" and "prediction" holding the values of the last processed sample.

Return type:

dict