Skip to content

Add attribute, topology and metrics submodules in braindecode.visualization - #997

Merged
bruAristimunha merged 22 commits into
braindecode:masterfrom
ShahVandit:add-visualization
May 3, 2026
Merged

bruAristimunha merged 22 commits into
braindecode:masterfrom
ShahVandit:add-visualization

Conversation

@ShahVandit

Copy link
Copy Markdown
Contributor

Visualization Module Additions

1. braindecode/visualization/attribution.py

Unified API for computing attribution maps.

Supported methods:

  • Captum
    • Saliency
    • InputXGradient
    • IntegratedGradients
    • GuidedBackprop
    • Deconvolution
    • DeepLift
    • LRP
    • GuidedGradCam
    • LayerGradCam
  • pytorch-grad-cam
    • GradCAM
    • GradCAMPlusPlus
    • ScoreCAM
    • LayerCAM
    • FullGrad

Key functionality:

  • get_attributions
    • Computes attribution maps
    • Filters to correctly classified samples before computation

2. braindecode/visualization/metrics.py

Implements 16 attribution quality metrics comparing explanation maps against ground truth.

Metric groups:

  • SSIM ×4
  • Cosine Similarity ×4
  • Relevance Mass / Rank Accuracy ×4
  • Pearson Correlation ×4

Features:

  • Supports:
    • Channel-space evaluation
    • Topographic (scalp-projected) evaluation

3. braindecode/visualization/topology.py

Projects per-channel attribution values onto a 2D scalp topomap.

Details:

  • Uses Clough-Tocher interpolation
  • Ported from MNE internals
  • Works directly with braindecode chs_info

Testing

Full test coverage for all three submodules.

pytest test/unit_tests/visualization/test_attribution.py
pytest test/unit_tests/visualization/test_metrics.py
pytest test/unit_tests/visualization/test_topology.py

@ShahVandit

Copy link
Copy Markdown
Contributor Author

Will add whats-new later on!

@bruAristimunha

Copy link
Copy Markdown
Collaborator

amazing @ShahVandit, i will take look during the weekend

@bruAristimunha
bruAristimunha self-requested a review April 24, 2026 18:18
bruAristimunha and others added 8 commits April 28, 2026 14:34
- Move captum, grad-cam, scikit-image to a `viz` optional extra and
  defer their imports inside the relevant functions so the package
  loads cleanly without them, with a clear ImportError pointing at
  `pip install braindecode[viz]`.
- topology.py: remove unreachable branches in `_make_head_outlines`
  (only the "head" path is ever used), drop the unused `extent` return
  and `mask_pts` attribute, replace asserts with ValueError, and split
  the geometry build into `_build_topomap` so batched topo-mode metrics
  can reuse the same Delaunay triangulation across samples.
- metrics.py: int flags → bool, hoist `gt_bool` and the topomap
  interpolator out of the per-sample loop, use np.partition for
  top-K threshold, guard against constant-array min-max
  normalization and zero-mass denominators, fix the `prctile_val`
  docstring, drop narrative comments. Output remains bit-exact across
  all gt_flag/abs_condition/prctile_val combinations on random and
  topo-mode inputs.
- attribution.py: hoist LayerAttribution import (now lazy via captum
  module), validate that layer-required methods receive a layer
  argument with a clear error.
- tests: shared `chs_info_factory` fixture in conftest.py, module-scoped
  model and chs_info fixtures, deepcopy in the one test that mutates
  classifier weights, switch flag literals to bool, add a parametrized
  test that the new layer-required validation raises.
- topology.py: 270 lines -> 57. Replace the vendored copy of MNE's
  private interpolation machinery with a thin wrapper around
  `mne.viz.plot_topomap`, which produces bit-exact output. Channel
  geometry, sphere fitting, and Clough-Tocher interpolation are all
  delegated to MNE.
- attribution.py: drop the `grad-cam` dependency. Captum's
  `LayerGradCam` and `GuidedGradCam` cover the layer-CAM use case;
  the GradCAM/GradCAMPlusPlus/ScoreCAM/LayerCAM/FullGrad variants from
  pytorch-grad-cam (which required a 4D-input shape adapter) are
  removed. The CAM dispatch branch in `attribute_image_features` is
  gone with them.
- metrics.py: drop `scikit-image` and the four SSIM metrics it
  required. `METRIC_NAMES` is now 12 entries (cosine x4, mass/rank x4,
  pearson x4). Replace the per-sample `sklearn.metrics.pairwise.cosine_similarity`
  / `scipy.stats.pearsonr` calls with batched numpy ops; the inner
  loop survives only for the per-sample top-K mask (since K varies).
  Rename `gt_flag` -> `abs_reference` and `abs_condition` ->
  `abs_explanation` for readability.
- pyproject.toml: `viz` extra is now `["captum>=0.9.0"]` only.
- Tests adjusted for the smaller metric set, the dropped CAM methods,
  and the renamed flags.
- metrics.py: rename `*_top5*` metrics to `*_topperc*`. The old names
  hard-coded "5%" but the actual percentile is governed by the
  `prctile_val` parameter (default 95 → top 5%, configurable). The new
  names track what the code actually does.
- metrics.py: replace the `1.0`-as-sentinel trick in `_safe_div` with
  an explicit zero-fill via `np.divide(..., out=zeros, where=den != 0)`.
- topology.py: hoist the `sfreq=1.0` placeholder to a named constant
  `_TOPOMAP_PLACEHOLDER_SFREQ` with a comment explaining that
  `mne.create_info` requires sfreq but `plot_topomap` only reads
  positions.
- attribution.py: comment why `relu_attributions=False` is passed to
  Captum's `LayerGradCam` (overrides the library default to keep
  signed activations for downstream metrics).
- attribution.py: drop the silent `list(model.children())[-1]`
  fallback in `get_attribution_method`. Layer-required methods now
  raise a clear `ValueError` from the factory itself; non-layer methods
  simply ignore the argument.
Replaces the Captum-wrapped class-and-string-dispatch attribution API
with four direct functions on top of `torch.autograd.grad`. The full
method catalogue Captum provides (DeepLift, LRP, GuidedBackprop,
Deconvolution, GuidedGradCam) is non-trivial to reimplement and is
deferred — users who need them can call Captum directly. The methods
that are easy and idiomatic in PyTorch are kept.

Public API:
- `saliency(model, x, target)` — `|d y[target] / d x|`
- `input_x_gradient(model, x, target)` — `x * d y[target] / d x`
- `integrated_gradients(model, x, target, baseline=None, steps=50)` —
  midpoint-rule path integral; verified to satisfy the completeness
  axiom exactly on linear models (test included)
- `layer_grad_cam(model, x, target, layer)` — class activation map at a
  named layer, bilinear-interpolated back to the input shape
- `select_correctly_classified(model, X, y)` — helper that runs
  inference and filters to correctly-classified samples

The string-method-name dispatch (`attribute_image_features(...,
method="Saliency")`) and its helper `get_attributions` are removed in
favour of importing the functions directly. `pyproject.toml` drops the
`viz` optional extra entirely; the visualization module now has no
optional dependencies.
The new tutorial under examples/advanced_training/ walks through the
full visualization pipeline on BNCI2014_001 motor imagery:

- train ShallowFBCSPNet for 10 epochs
- pick correctly-classified trials with select_correctly_classified
- compute saliency, input_x_gradient, integrated_gradients, and
  layer_grad_cam attributions
- plot per-(channel, time) heatmaps and time-averaged scalp topomaps
- run a randomized-model sanity check (Adebayo et al., 2018) via
  compute_metrics

The colab tutorial linked in the request requires authentication so I
couldn't read it directly; this is built from scratch matching the
existing braindecode tutorial style.
Folds the techniques from the original CuttingGardens 2023 Braindecode
tutorial (by R. Schirrmeister) into our interpretability example so the
single tutorial covers both the legacy frequency-domain analyses and
the new gradient-based attribution.

Sections now:
- Amplitude gradients (compute_amplitude_gradients) plotted as
  per-class topomaps for the alpha (7-13 Hz) and beta (14-30 Hz)
  motor-imagery bands
- Filter -> pattern transform (Haufe et al., 2014) via amplitude
  covariance, plotted in the same band layout
- Maximally activating inputs: forward-hook on bnorm, top-5% trials
  per filter, mean receptive-field windows on a 5x8 grid (40 filters)
- Gradient-based attribution: saliency, input_x_gradient,
  integrated_gradients, layer_grad_cam, with (channel, time) heatmaps
- Topographic projection of time-averaged attribution via
  project_to_topomap, side-by-side with the amplitude-gradient
  topomaps to compare frequency-domain vs time-domain views
- Adebayo et al. (2018) sanity check via compute_metrics, comparing
  trained vs randomized model saliency

The Cosine-Similarity-Based Network section from the original tutorial
is intentionally left out - it requires shipping a custom 50+ line
architecture which doesn't fit the "use the existing API" framing of
this example.
Concrete fixes from running the tutorial end-to-end and inspecting
each figure:

Figure 1 & 2 (amplitude gradients & Haufe patterns):
- Switch from raw imshow to mne.viz.plot_topomap so the maps are
  clipped to the scalp circle with head outline / nose / ears
- Per-band 98th-percentile vmax instead of global max — a single
  outlier class no longer washes out the rest of the band
- Single shared diverging colorbar on the right of each figure
- Class titles colour-coded by Okabe-Ito palette
- Replace rotated y-labels with cleanly positioned band labels

Figure 3 (maximally activating inputs):
- Each filter's label is now coloured by the class it votes for most
  strongly (read from the conv_classifier weights)
- x-axis in milliseconds on the bottom row, y-axis in microvolts on
  the left column
- Inline class-colour legend at the bottom

Figure 4 (per-(channel, time) heatmaps):
- Drop LayerGradCam from this view — its "channel" dimension is the
  bilinear-interpolated singleton spatial dim of the conv_classifier
  output, not the original 22 electrodes (documented in a note)
- Per-method min-max normalization so each panel uses its full
  dynamic range; magnitudes across methods aren't comparable anyway
- Show every fourth channel label to keep the y-axis legible
- Shared colorbar with explicit "(0–1) per-method normalized" label

Figure 5 (topographic projection):
- Drop LayerGradCam (same channel-dim caveat)
- Use mne.viz.plot_topomap directly for proper circular scalp maps
- Per-method normalization, shared 0–1 scale

Other:
- Print final validation accuracy after training so the reader knows
  the model is in a regime where attribution is meaningful
- Hoist matplotlib import + rcParams + Okabe-Ito CLASS_COLORS to the
  top of the analysis section
@ShahVandit

Copy link
Copy Markdown
Contributor Author

Hi @bruAristimunha ! I have a few suggestions too, I will push them in a while

bruAristimunha and others added 3 commits April 29, 2026 00:10
Brings back Captum as a soft dependency and incorporates research-code
patterns from Sujatha Ravindran & Contreras-Vidal, "An empirical
comparison of deep learning explainability approaches for EEG using
simulated ground truth," Scientific Reports 13, 2023
(DOI: 10.1038/s41598-023-43871-8).

Library additions
- pyproject.toml: new `viz` extra (`captum>=0.7.0`).
- attribution.py: lazy Captum-backed wrappers `guided_backprop`,
  `deconvolution`, `deep_lift`, `lrp` (clear ImportError when captum is
  absent); pure-PyTorch primitives (saliency, IxG, IG, layer_grad_cam)
  unchanged.
- attribution.py: `random_target(target, n_classes)` for
  label-randomization sanity checks; `cascading_layer_reset(model)`
  generator implementing Adebayo's output-to-input layer-reset protocol.
- metrics.py: `compute_ssim_metrics` (4 SSIM variants) implemented in
  pure torch via F.avg_pool2d; matches skimage to machine epsilon, no
  scikit-image dependency.

Tutorial rewrite (examples/advanced_training/plot_interpretability.py)
- Subject 1, 30 epochs (val acc 59% vs 40% before); attribution maps
  carry visible signal.
- Haufe transform: subtract cross-class mean before the covariance
  multiplication to remove the rank-1 component that flattened the
  topomaps; class-distinctive structure now visible.
- New "Are the explanations trustworthy?" section is the climax of the
  tutorial: runs label randomization for each method and full cascading
  weight randomization (output -> input). Single side-by-side figure
  shows the bars + curves; reproduces the paper's headline finding on
  real EEG (Saliency invariant, IG and DeepLIFT collapse to ~0 cosine).
- Adds DeepLIFT to the demonstrated method set whenever Captum is
  importable; falls back gracefully otherwise.
- Drops the visually-empty per-(channel, time) heatmap; collapses the
  scalp projection to a single labelled topomap (C3/Cz/C4 marked).
- All imports moved to a single block at the top.
- Citations audited: removed an over-attributed SMC 2020 DOI in favour
  of the correct Sci Rep 2023 paper.
…tplotlib dependency, add grid padding to prevent hull-boundary zeros
Move scipy/mne/numpy/copy imports in visualization/topology.py and
visualization/attribution.py to module top-level (captum stays optional
via a top-level try/except). Switch the CloughTocher fill_value from
0.0 to NaN so the padded grid masks out-of-hull pixels instead of
contaminating uniform-input statistics; metrics.py already nan_to_num's
projected output.
@bruAristimunha

Copy link
Copy Markdown
Collaborator

sorry for directly inputting into your PR, now it all your back

ShahVandit and others added 7 commits April 29, 2026 12:51
- attribution.py: collapse hand-rolled time-domain primitives into thin
  captum wrappers. saliency, input_x_gradient, integrated_gradients now
  delegate to captum (IG defaults to gausslegendre, more accurate than
  the previous midpoint rule). layer_grad_cam uses LayerGradCam +
  LayerAttribution.interpolate. Captum stays a soft dep via _soft_import;
  every method raises a clear ImportError when missing.
- frequency.py (new): amplitude_gradients(model, x) primitive +
  amplitude_gradients_per_trial dataset wrapper. Renames the old
  compute_amplitude_gradients_for_X / compute_amplitude_gradients pair
  and drops the surprising in-function set_random_seeds side effect.
- sanity.py (new): random_target and cascading_layer_reset live here
  rather than mixed into attribution methods.
- metrics.py: extract _prepare_attributions to share the shape-check /
  nan_to_num / projection / abs preamble between compute_metrics and
  compute_ssim_metrics.
- Drop select_correctly_classified from the public API (and its tests);
  the tutorial inlines the equivalent five-line filter.
- gradients.py removed; tests and tutorial track the new locations.
- test_attribution.py uses pytest.importorskip("captum") so the file
  skips cleanly when the optional viz dep isn't installed.
…radients with the new public surface (saliency, IG, sanity helpers, metrics, topology, etc.)
Tutorial now loads the published ShallowFBCSPNet checkpoint from
braindecode/plot_bcic_iv_2a_moabb_trial (subject 3, 68% held-out
accuracy) instead of training from scratch, so the gallery build
finishes in ~3 min and the attribution analysis works against a
properly-fit model. Preprocessing + windowing + split match the
checkpoint's training pipeline exactly so the loaded weights apply
without fine-tuning.

Sanity-check section:
- Replaces the flat-cosine global similarity with per-trial Pearson r
  (matching the protocol in Sujatha Ravindran & Contreras-Vidal, Sci
  Rep 2023). The flat cosine collapsed (8, 22, n_times) tensors into
  one number and pushed IG/DeepLIFT scores artificially toward 0.
- Adds the paper's ~0.5 cutoff line to both bar and cascade panels.
- Reframes the section as "How sensitive is each method to
  randomization?" since the bar chart on real EEG with a well-trained
  model can have all three methods passing.

Quantitative-scoring section:
- Drops the four RelevanceMassAccuracy_* / RelevanceRankAccuracy_topK
  columns from the printed table (they saturate at 1.0 without
  simulated ground truth).
- Prints the full surviving 12-column table plus a per-metric ranking,
  so cross-metric disagreement is visible directly.

Take-aways rewritten to lead with the cascade-curve diagnostic and the
'no single metric is enough' finding rather than overstating
'DeepLIFT wins' on this particular real-EEG subject.

Prose throughout: zero em dashes, zero bold in body text, technical
terminology aligned with the paper (conservation property, class- /
model-specific, Relevance Mass Accuracy, volume conduction).

api.rst Visualization section: split into six subsections (time-domain
attribution, frequency-domain attribution, sanity protocols, quality
metrics, topography, plotting) with one-paragraph intros each, so all
public functions get autosummary stubs and the module's surface is
navigable from one page.
Three changes to make the tutorial more jupyter/gallery-friendly:

1. Quantitative-scoring section: dropped the wide ASCII to_string()
   prints (which overflowed the gallery output box) and replaced with
   a single matplotlib figure. Top panel: raw scores against a
   random-weight model, colour-scaled to the data range so cell
   contrast actually conveys sensitivity. Bottom panel: per-metric
   rank, so cross-metric disagreement reads as colour heterogeneity
   within rows. Both panels carry numerical labels and colorbar
   captions.

2. Top docstring: added a `.. note::` TL;DR ahead of the long abstract
   so a reader scrolling the gallery sees the headline finding before
   the methodology.

3. matplotlib rcParams pin font.family/sans-serif to Helvetica/Arial/
   DejaVu Sans so the docs build doesn't fall through to system fonts
   on macOS (which would render as `.SFNS-Regular` and break PDF
   export).
positive-claim suptitles, integer cascade ticks

Applied data-viz-design audit punch list across all five figures:

- Fig 5 (metric heatmap): RdYlGn_r → RdBu_r so the encoding is
  colorblind-safe. Top panel now diverges around 0 with vmin=-val_max,
  vmax=val_max. Cell text contrast tightened so rank-1 (blue) and
  rank-3 (red) cells both use white text.

- Fig 2 (Haufe patterns): _band_topomap_grid takes a new
  landmark_channels parameter; Haufe call passes {C3, Cz, C4} so the
  contralateral motor-imagery story is annotated, not just visible.
  Fig 1 (amplitude gradients) keeps the cleaner sensors-off look.

- Fig 3 (mean scalp): title now makes a claim ("All three methods
  agree the network attends to motor cortex") instead of describing
  the operation. Colorbar label replaces "Per-method normalized (0-1)"
  jargon with "Mean attribution magnitude (per-method max-normalized)".

- Fig 4 (sanity checks): suptitle flipped from a double-negative
  ("Methods that survive both randomizations are reflecting
  architecture, not learning") to a positive claim ("Lower values mean
  the attribution depends on what the network learned"). Cascade
  x-axis pinned to integer ticks (0..n_levels) so the half-integer
  artefacts no longer suggest fractional layers.
The placeholder sfreq value was its own module-level constant with a
comment; inline the literal at the single call site and keep the
explanation as an inline comment. Behaviour unchanged.
@bruAristimunha

Copy link
Copy Markdown
Collaborator

many thanks @ShahVandit 🙏🏽 this was something that i really wanted for long time

@bruAristimunha
bruAristimunha merged commit aa39d19 into braindecode:master May 3, 2026
10 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants