Attribution Methods#

Attribution methods for CEBRA.

This module was added in v0.6.0 and contains attribution methods described and benchmarked in [Schneider2025].

[Schneider2025]

Schneider, S., González Laiz, R., Filippova, A., Frey, M., & Mathis, M. W. (2025). Time-series attribution maps with regularized contrastive learning. The 28th International Conference on Artificial Intelligence and Statistics. https://openreview.net/forum?id=aGrCXoTB4P

Different attribution methods#

class cebra.attribution.attribution_models.AttributionMap(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: object

Base class for computing attribution maps for CEBRA models.

Parameters:
  • model (Module) – The trained CEBRA model to analyze

  • input_data (Tensor) – Input data tensor to compute attributions for

  • output_dimension (int) – Output dimension to analyze. If None, uses model’s output dimension

  • num_samples (int) – Number of samples to use for attribution. If None, uses full dataset

  • seed (int) – Random seed which is used to subsample the data. Only relevant if num_samples is not None.

compute_attribution_map()#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

compute_metrics(attribution_map, ground_truth_map)#

Compute metrics comparing attribution map to ground truth.

This function computes various statistical metrics to compare the attribution values between connected and non-connected neurons based on a ground truth connectivity map. It separates the attribution values into two groups based on the binary ground truth, and calculates summary statistics and differences between these groups.

Parameters:
  • attribution_map – Computed attribution values representing the strength of connections between neurons

  • ground_truth_map – Binary ground truth connectivity map where True indicates a connected neuron and False indicates a non-connected neuron

Returns:

Dictionary containing the following metrics:
  • max/mean/min_nonconnected: Statistics for non-connected neurons

  • max/mean/min_connected: Statistics for connected neurons

  • gap_max: Difference between max connected and max non-connected values

  • gap_mean: Difference between mean connected and mean non-connected values

  • gap_min: Difference between min connected and min non-connected values

  • gap_minmax: Difference between min connected and max non-connected values

  • max/min_jacobian: Global max/min values across all neurons

Return type:

dict

compute_attribution_score(attribution_map, ground_truth_map)#

Compute ROC AUC score between attribution map and ground truth.

Parameters:
  • attribution_map – Computed attribution values

  • ground_truth_map – Binary ground truth connectivity map

Returns:

ROC AUC score

Return type:

float

check_moores_penrose_conditions(jacobian, jacobian_pseudoinverse)#

Check Moore-Penrose conditions for Jacobian matrices.

Parameters:
  • jacobian (ndarray) – Jacobian matrices of shape (num samples, output_dim, num_neurons)

  • jacobian_pseudoinverse (ndarray) – Pseudoinverse matrices of shape (num samples, num_neurons, output_dim)

Return type:

ndarray

Returns:

Boolean array of shape (num samples, 4) indicating satisfied conditions

class cebra.attribution.attribution_models.JFMethodBased(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: AttributionMap

Compute the attribution map using the Jacobian of the model encoder.

compute_attribution_map(selected_keys=None)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.JFMethodBasedBatched(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: JFMethodBased

Compute an attribution map based on the Jacobian using mini-batches.

See also

JFMethodBased

compute_attribution_map(batch_size=1024, selected_keys=None)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.JFMethodBasedBatchedOptimized(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: JFMethodBased

Jacobian-based attribution computed in mini-batches, with an optional running mean.

Same results as jacobian-based-batched, with less memory.

compute_attribution_map(batch_size=1024, return_full=True, selected_keys=None, latent_batch_size=None)#

Compute the attribution maps.

Parameters:
  • batch_size – Samples per Jacobian batch.

  • return_full – Return one map per sample. If False, return the mean over samples.

  • selected_keys – Maps to compute, e.g. ["jf"]. None: all of them.

  • latent_batch_size – Embedding dimensions per autograd pass. None: all at once.

Returns:

Dict from map name to array, (T, D, N) per sample or (D, N) averaged.

class cebra.attribution.attribution_models.NeuronGradientMethod(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: AttributionMap

Compute the attribution map using the neuron gradient from Captum.

Note

This method is equivalent to Jacobian-based attributions, but uses a different backend implementation.

compute_attribution_map(attribute_to_neuron_input=False)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.NeuronGradientMethodBatched(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: NeuronGradientMethod

As NeuronGradientMethod, but using mini-batches.

compute_attribution_map(attribute_to_neuron_input=False, batch_size=1024)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.FeatureAblationMethod(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: AttributionMap

Compute the attribution map using the feature ablation method from Captum.

compute_attribution_map(baselines=None, feature_mask=None, perturbations_per_eval=1, attribute_to_neuron_input=False)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.FeatureAblationMethodBAtched(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: FeatureAblationMethod

As FeatureAblationMethod, but using mini-batches.

compute_attribution_map(baselines=None, feature_mask=None, perturbations_per_eval=1, attribute_to_neuron_input=False, batch_size=1024)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.IntegratedGradientsMethod(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: AttributionMap

Compute the attribution map using the integrated gradients method from Captum.

compute_attribution_map(n_steps=50, method='gausslegendre', internal_batch_size=None, attribute_to_neuron_input=False, baselines=None)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.IntegratedGradientsMethodBatched(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: IntegratedGradientsMethod

As IntegratedGradientsMethod, but using mini-batches.

compute_attribution_map(n_steps=50, method='gausslegendre', internal_batch_size=None, attribute_to_neuron_input=False, baselines=None, batch_size=1024)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.NeuronGradientShapMethod(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: AttributionMap

Compute the attribution map using the neuron gradient SHAP method from Captum.

compute_attribution_map(baselines, n_samples=5, stdevs=0.0, attribute_to_neuron_input=False)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

class cebra.attribution.attribution_models.NeuronGradientShapMethodBatched(model, input_data, output_dimension=None, num_samples=None, seed=9712341)#

Bases: NeuronGradientShapMethod

As NeuronGradientShapMethod, but using mini-batches.

compute_attribution_map(baselines, n_samples=5, stdevs=0.0, attribute_to_neuron_input=False, batch_size=1024)#

Compute the attribution map for the model.

Returns:

Attribution maps and their variants

Return type:

dict

Raises:

NotImplementedError – Must be implemented by subclasses

Jacobian-based attribution#

Tools for computing attribution maps.

cebra.attribution.jacobian_attribution.get_attribution_map(model, input_data, double_precision=True, convert_to_numpy=True, aggregate='mean', transform='none', hybrid_solver=False)#

Estimate attribution maps using the Jacobian pseudo-inverse.

The function estimates Jacobian matrices for each point in the model, computes the pseudo-inverse (for every sample) and then aggregates the resulting matrices to compute an attribution map.

Parameters:
  • model (Module) – The neural network model for which to compute attributions.

  • input_data (Tensor) – Input tensor or numpy array to compute attributions for.

  • double_precision (bool) – If True, use double precision for computation.

  • convert_to_numpy (bool) – If True, convert the output to numpy arrays.

  • aggregate (Literal[‘mean’, ‘sum’, ‘max’]) – Method to aggregate attribution values across samples. Options are "mean", "sum", or "max".

  • transform (Literal[‘none’, ‘abs’]) – Transformation to apply to attribution values. Options are "none" or "abs".

  • hybrid_solver (bool) – If True, handle multi-objective models differently.

Returns:

A tuple containing the Jacobian matrix of shape (num_samples, output_dim, input_dim) and the pseudo-inverse of the Jacobian matrix.

Feature maps#

Feature attribution maps: how each input channel drives each feature, through the embedding.

For one trained model:

  1. W = fit_feature_readout(embedding, features, train_fraction=0.9): linear readout (D, F) from the embedding to the features.

  2. M = feature_attribution_map(solver, inputs, W): the signed map M = J^T W of shape (N, F), with J = dz/dx the forward Jacobian of the encoder, averaged over time. The solver must have been trained with the Jacobian regularizer.

  3. average_feature_maps([M_1, M_2, ...]): mean over models.

Fit W for each model separately, on that model’s own embedding: the embeddings of different models are not aligned, so a W is only valid for the model it was fitted on.

N is the number of input channels (summed over sessions for a unified model), D the embedding dimension and F the number of features. The map is signed: no absolute value and no pseudo-inverse.

Valid rows: a model with offset (left, right) gives one output per window of left + right input samples, so row r of the embedding and of the per-row maps is input sample left + r: features features[left:T - right + 1] match the rows of a session of T samples.

cebra.attribution.feature_map.fit_feature_readout(embedding, features, alpha=1.0, train_fraction=None, train_index=None)#

Fit a ridge readout from the embedding to the features.

The rows of embedding and features must be aligned 1:1 (see the module notes for the valid rows). The readout is fitted on the first 80% of the rows by default, or on the rows chosen by train_fraction (the first rows, a contiguous block) or train_index (any rows), so the other rows stay free for a held-out check. Selecting every row is only right if the rows passed are all training data; it gives a warning.

Discrete (categorical) features must be one-hot encoded, one column per category: integer labels would be fitted as one continuous target.

Parameters:
  • embedding – Array of shape (T, D).

  • features – Array of shape (T, F), or (T,) for one feature. Used as given; z-score them first to put features on a comparable scale.

  • alpha (float) – Ridge penalty.

  • train_fraction – Fit on the first round(T * train_fraction) rows, in (0, 1]. Default (neither argument given): 0.8, with a message printed.

  • train_index – Fit on these rows, as integer indices or a boolean mask of length T. Not together with train_fraction.

Return type:

ndarray

Returns:

The readout W of shape (D, F), such that embedding @ W approximates features (the intercept is dropped).

Raises:

ValueError – If both train_fraction and train_index are given, if the training rows are empty, or if the shapes do not match.

Warns:

UserWarning – If the selected rows are all the rows passed (no row held out).

Example

>>> import numpy as np
>>> from cebra.attribution import fit_feature_readout
>>> rng = np.random.default_rng(0)
>>> embedding = rng.normal(size=(100, 4))
>>> features = embedding @ rng.normal(size=(4, 2))
>>> W = fit_feature_readout(embedding, features, train_fraction=0.9)
>>> W.shape
(4, 2)
>>> W = fit_feature_readout(embedding, features)  # first 80% of the rows
fit_feature_readout: fitting on the first 80% of rows (train_fraction=0.8); pass train_fraction or train_index to choose.
>>> held_out = np.corrcoef((embedding[90:] @ W)[:, 0], features[90:, 0])[0, 1]
>>> bool(held_out > 0.99)
True
cebra.attribution.feature_map.feature_attribution_map(solver, inputs, W, *, labels=None, session_id=None, indices=None, output_slice=None, average=True, random_ties=False, seed=0, batch_size=64, latent_batch_size=32, method='jacobian-based-batched-optimized')#

Signed feature attribution map M = J^T W of one model trained with the Jacobian regularizer.

M[n, f] = sum_d dz_d/dx_n * W[d, f], with J the forward Jacobian of the embedding and W the readout from fit_feature_readout(). A positive value means that raising channel n raises the readout of feature f. J(t) is the Jacobian of z(t) with respect to the whole input window of the model, averaged over the window (CEBRA’s jf); the mean map is the mean of the per-timepoint maps.

Fit W for each model separately, on that model’s own embedding (embeddings of different models are not aligned, so a W is only valid for its model); never share a W across models. For a unified solver, inputs and labels are per-session lists, as in solver.transform, and the map has one row per channel of all sessions concatenated. Use the same random_ties and seed as the transform that gave the embedding W was fitted on.

Parameters:
  • solver – Solver trained with the Jacobian regularizer: a unified solver (e.g. "unified-xcebra") or a single-session one (an xCEBRA solver or RegularizedSolver). Plain modules, unregularized solvers and cebra.CEBRA objects raise a TypeError.

  • inputs – (T, N) array or tensor, or for a unified solver a list of (T_s, N_s).

  • W – Readout of shape (D, F), with D the output dimension (or len(output_slice)).

  • labels – Unified only, required. Auxiliary variables of each session, (T_s, d).

  • session_id – Unified only, required. Reference session.

  • indices – Rows of the (reference) session’s inputs at which the map is computed. For a unified solver the other sessions are aligned to these rows. Default: all.

  • output_slice – Single session only. Embedding columns of one head, e.g. one subspace of a SubspaceMultiobjectiveModel.

  • average (bool) – True for the time mean (N, F), False for one map per valid row (T_valid, N, F) (see the module notes).

  • random_ties (bool) – Unified only. Break nearest-label ties at random instead of taking the first.

  • seed – Unified only. Seed of the tie draws (default 0). Use the same seed as the transform that gave the embedding W was fitted on.

  • batch_size (int) – Rows per Jacobian batch, halved on CUDA out-of-memory.

  • latent_batch_size (int) – Embedding dimensions per autograd pass. Only used by the default method.

  • method (str) – Attribution method that computes the Jacobian, one of JACOBIAN_METHODS.

Return type:

ndarray

Returns:

The map as a float64 array, (N, F) for average=True and (T_valid, N, F) for average=False.

Raises:
  • TypeError – If solver was not trained with the Jacobian regularizer.

  • ValueError – If W does not match the output dimension, if the input is shorter than the model window, if labels or session_id is missing for a unified solver, if unified-only arguments are given for a single-session solver, or if method is not a Jacobian method.

Example

Readout, map, then the average over models, on small random data:

>>> import numpy as np
>>> import torch
>>> import cebra
>>> from cebra.attribution import (average_feature_maps,
...                                feature_attribution_map,
...                                fit_feature_readout)
>>> rng = np.random.default_rng(0)
>>> x = torch.tensor(rng.normal(size=(100, 10)), dtype=torch.float32)
>>> features = rng.normal(size=(100, 2))
>>> maps = []
>>> for seed in range(3):  # one model per seed; here untrained encoders
...     _ = torch.manual_seed(seed)
...     model = cebra.models.init("offset1-model", num_neurons=10, num_units=16,
...                               num_output=4)
...     solver = cebra.solver.RegularizedSolver(
...         model=model, criterion=cebra.models.InfoNCE(),
...         optimizer=torch.optim.Adam(model.parameters()))
...     embedding = model(x).detach().numpy()
...     W = fit_feature_readout(embedding, features, train_fraction=0.9)
...     maps.append(feature_attribution_map(solver, x, W))
>>> maps[0].shape
(10, 2)
>>> average_feature_maps(maps).shape
(10, 2)

For a unified model, pass the per-session data and labels, with the same random_ties and seed as in the transform that produced the embedding:

z = solver.transform(inputs, labels, session_id=0, random_ties=True, seed=0)
W = fit_feature_readout(z, features, train_fraction=0.9)
M = feature_attribution_map(solver, inputs, W, labels=labels, session_id=0,
                            random_ties=True, seed=0)
cebra.attribution.feature_map.average_feature_maps(maps)#

Mean of feature attribution maps, e.g. over models trained with different seeds.

Average the signed maps: the mean of |M| is not |mean M|. Each map must come from its own model with a W fitted on that model’s own embedding (the embeddings of different models are not aligned): never share a W across models.

Parameters:

maps – Sequence of arrays of the same shape, e.g. (N, F) per model.

Return type:

ndarray

Returns:

Array with the shape of one map.

Example

>>> import numpy as np
>>> from cebra.attribution import average_feature_maps
>>> maps = [np.ones((5, 2)), 3 * np.ones((5, 2))]
>>> average_feature_maps(maps).shape
(5, 2)
>>> float(average_feature_maps(maps)[0, 0])
2.0