Attribution Methods#
Attribution methods for CEBRA.
This module was added in v0.6.0 and contains attribution methods described and benchmarked in [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:
objectBase class for computing attribution maps for CEBRA models.
- Parameters:
model (
Module) – The trained CEBRA model to analyzeinput_data (
Tensor) – Input data tensor to compute attributions foroutput_dimension (
int) – Output dimension to analyze. IfNone, uses model’s output dimensionnum_samples (
int) – Number of samples to use for attribution. IfNone, uses full datasetseed (
int) – Random seed which is used to subsample the data. Only relevant ifnum_samplesis notNone.
- compute_attribution_map()#
Compute the attribution map for the model.
- Returns:
Attribution maps and their variants
- Return type:
- 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:
- 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:
- check_moores_penrose_conditions(jacobian, jacobian_pseudoinverse)#
Check Moore-Penrose conditions for Jacobian matrices.
- Parameters:
- Return type:
- 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:
AttributionMapCompute 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:
- 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:
JFMethodBasedCompute an attribution map based on the Jacobian using mini-batches.
See also
- compute_attribution_map(batch_size=1024, selected_keys=None)#
Compute the attribution map for the model.
- Returns:
Attribution maps and their variants
- Return type:
- 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:
JFMethodBasedJacobian-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:
AttributionMapCompute 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:
- 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:
NeuronGradientMethodAs
NeuronGradientMethod, but using mini-batches.See also
- 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:
- 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:
AttributionMapCompute 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:
- 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:
FeatureAblationMethodAs
FeatureAblationMethod, but using mini-batches.See also
- 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:
- 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:
AttributionMapCompute 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:
- 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:
IntegratedGradientsMethodAs
IntegratedGradientsMethod, but using mini-batches.See also
- 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:
- 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:
AttributionMapCompute 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:
- 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:
NeuronGradientShapMethodAs
NeuronGradientShapMethod, but using mini-batches.See also
- 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:
- 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) – IfTrue, use double precision for computation.convert_to_numpy (
bool) – IfTrue, 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) – IfTrue, 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:
W = fit_feature_readout(embedding, features, train_fraction=0.9): linear readout(D, F)from the embedding to the features.M = feature_attribution_map(solver, inputs, W): the signed mapM = J^T Wof shape(N, F), withJ = dz/dxthe forward Jacobian of the encoder, averaged over time. The solver must have been trained with the Jacobian regularizer.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
embeddingandfeaturesmust 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 bytrain_fraction(the first rows, a contiguous block) ortrain_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 withtrain_fraction.
- Return type:
- Returns:
The readout
Wof shape(D, F), such thatembedding @ Wapproximatesfeatures(the intercept is dropped).- Raises:
ValueError – If both
train_fractionandtrain_indexare 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 Wof one model trained with the Jacobian regularizer.M[n, f] = sum_d dz_d/dx_n * W[d, f], withJthe forward Jacobian of the embedding andWthe readout fromfit_feature_readout(). A positive value means that raising channelnraises the readout of featuref.J(t)is the Jacobian ofz(t)with respect to the whole input window of the model, averaged over the window (CEBRA’sjf); the mean map is the mean of the per-timepoint maps.Fit
Wfor each model separately, on that model’s own embedding (embeddings of different models are not aligned, so aWis only valid for its model); never share aWacross models. For a unified solver,inputsandlabelsare per-session lists, as insolver.transform, and the map has one row per channel of all sessions concatenated. Use the samerandom_tiesandseedas thetransformthat gave the embeddingWwas 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 orRegularizedSolver). Plain modules, unregularized solvers andcebra.CEBRAobjects raise aTypeError.inputs –
(T, N)array or tensor, or for a unified solver a list of(T_s, N_s).W – Readout of shape
(D, F), withDthe output dimension (orlen(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) –Truefor the time mean(N, F),Falsefor 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
transformthat gave the embeddingWwas 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 defaultmethod.method (
str) – Attribution method that computes the Jacobian, one ofJACOBIAN_METHODS.
- Return type:
- Returns:
The map as a float64 array,
(N, F)foraverage=Trueand(T_valid, N, F)foraverage=False.- Raises:
TypeError – If
solverwas not trained with the Jacobian regularizer.ValueError – If
Wdoes not match the output dimension, if the input is shorter than the model window, iflabelsorsession_idis missing for a unified solver, if unified-only arguments are given for a single-session solver, or ifmethodis 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_tiesandseedas in thetransformthat 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 aWfitted on that model’s own embedding (the embeddings of different models are not aligned): never share aWacross models.- Parameters:
maps – Sequence of arrays of the same shape, e.g.
(N, F)per model.- Return type:
- 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