Neuron Attribution¶
Neuron Gradient¶
- class captum.attr.NeuronGradient(forward_func, layer, device_ids=None)[source]¶
Computes the gradient of the output of a particular neuron with respect to the inputs of the network.
- Parameters
forward_func (callable) – The forward function of the model or any modification of it
layer (torch.nn.Module) – Layer for which attributions are computed. Output size of attribute matches this layer’s input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
- attribute(inputs, neuron_selector, additional_forward_args=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which neuron gradients are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neurons, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Gradients of particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_ig = NeuronGradient(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron gradient for neuron with >>> # index (4,1,2). >>> attribution = neuron_ig.attribute(input, (4,1,2))
Neuron Integrated Gradients¶
- class captum.attr.NeuronIntegratedGradients(forward_func, layer, device_ids=None, multiply_by_inputs=True)[source]¶
Approximates the integral of gradients for a particular neuron along the path from a baseline input to the given input. If no baseline is provided, the default baseline is the zero tensor. More details regarding the integrated gradient method can be found in the original paper here: https://arxiv.org/abs/1703.01365
Note that this method is equivalent to applying integrated gradients where the output is the output of the identified neuron.
- Parameters
forward_func (callable) – The forward function of the model or any modification of it
layer (torch.nn.Module) – Layer for which attributions are computed. Output size of attribute matches this layer’s input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
multiply_by_inputs (bool, optional) –
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104
In case of Neuron Integrated Gradients, if multiply_by_inputs is set to True, final sensitivity scores are being multiplied by (inputs - baselines).
- attribute(inputs, neuron_selector, baselines=None, additional_forward_args=None, n_steps=50, method='gausslegendre', internal_batch_size=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which neuron integrated gradients are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
baselines (scalar, tensor, tuple of scalars or tensors, optional) –
Baselines define the starting point from which integral is computed. Baselines can be provided as:
a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs.
a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor.
a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs’ tuple can be:
either a tensor with matching dimensions to corresponding tensor in the inputs’ tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor.
or a scalar, corresponding to a tensor in the inputs’ tuple. This scalar value is broadcasted for corresponding input tensor.
In the cases when baselines is not provided, we internally use zero scalar corresponding to each input tensor.
Default: None
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of n_steps along the integrated path. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None
n_steps (int, optional) – The number of steps used by the approximation method. Default: 50.
method (string, optional) – Method for approximating the integral, one of riemann_right, riemann_left, riemann_middle, riemann_trapezoid or gausslegendre. Default: gausslegendre if no method is provided.
internal_batch_size (int, optional) – Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Integrated gradients for particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_ig = NeuronIntegratedGradients(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron integrated gradients for neuron with >>> # index (4,1,2). >>> attribution = neuron_ig.attribute(input, (4,1,2))
Neuron Conductance¶
- class captum.attr.NeuronConductance(forward_func, layer, device_ids=None, multiply_by_inputs=True)[source]¶
Computes conductance with respect to particular hidden neuron. The returned output is in the shape of the input, showing the attribution / conductance of each input feature to the selected hidden layer neuron. The details of the approach can be found here: https://arxiv.org/abs/1805.12233
- Parameters
forward_func (callable) – The forward function of the model or any modification of it
layer (torch.nn.Module) – Layer for which neuron attributions are computed. Attributions for a particular neuron in the input or output of this layer are computed using the argument neuron_selector in the attribute method. Currently, only layers with a single tensor input or output are supported.
layer – Layer for which attributions are computed. Output size of attribute matches this layer’s input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
multiply_by_inputs (bool, optional) –
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104
In case of Neuron Conductance, if multiply_by_inputs is set to True, final sensitivity scores are being multiplied by (inputs - baselines).
- attribute(inputs, neuron_selector, baselines=None, target=None, additional_forward_args=None, n_steps=50, method='riemann_trapezoid', internal_batch_size=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which neuron conductance is computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). This can be used as long as the layer input / output is a single tensor.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a selected neuron - output shape should be 1D with length equal to batch_size (one scalar per input example)
NOTE: Callables applicable for neuron conductance are less general than those of other methods and should NOT aggregate values of the layer, only return a specific output. This option should only be used in cases where the layer input / output is a tuple of tensors, where the other options would not suffice. This limitation is necessary since neuron conductance, unlike other neuron methods, also utilizes the gradient of output with respect to the intermedite neuron, which cannot be computed for aggregations of multiple intemediate neurons.
baselines (scalar, tensor, tuple of scalars or tensors, optional) –
Baselines define the starting point from which integral is computed and can be provided as:
a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs.
a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor.
a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs’ tuple can be:
either a tensor with matching dimensions to corresponding tensor in the inputs’ tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor.
or a scalar, corresponding to a tensor in the inputs’ tuple. This scalar value is broadcasted for corresponding input tensor.
In the cases when baselines is not provided, we internally use zero scalar corresponding to each input tensor.
Default: None
target (int, tuple, tensor or list, optional) –
Output indices for which gradients are computed (for classification cases, this is usually the target class). If the network returns a scalar value per example, no target index is necessary. For general 2D outputs, targets can be either:
a single integer or a tensor containing a single integer, which is applied to all input examples
a list of integers or a 1D tensor, with length matching the number of examples in inputs (dim 0). Each integer is applied as the target for the corresponding example.
For outputs with > 2 dimensions, targets can be either:
A single tuple, which contains #output_dims - 1 elements. This target index is applied to all examples.
A list of tuples with length equal to the number of examples in inputs (dim 0), and each tuple containing #output_dims - 1 elements. Each tuple is applied as the target for the corresponding example.
Default: None
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. For a tensor, the first dimension of the tensor must correspond to the number of examples. It will be repeated for each of n_steps along the integrated path. For all other types, the given argument is used for all forward evaluations. Note that attributions are not computed with respect to these arguments. Default: None
n_steps (int, optional) – The number of steps used by the approximation method. Default: 50.
method (string, optional) – Method for approximating the integral, one of riemann_right, riemann_left, riemann_middle, riemann_trapezoid or gausslegendre. Default: gausslegendre if no method is provided.
internal_batch_size (int, optional) – Divides total #steps * #examples data points into chunks of size at most internal_batch_size, which are computed (forward / backward passes) sequentially. internal_batch_size must be at least equal to #examples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain internal_batch_size / num_devices examples. If internal_batch_size is None, then all evaluations are processed in one batch. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Conductance for particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_cond = NeuronConductance(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # Computes neuron conductance for neuron with >>> # index (4,1,2). >>> attribution = neuron_cond.attribute(input, (4,1,2))
Neuron DeepLift¶
- class captum.attr.NeuronDeepLift(model, layer, multiply_by_inputs=True)[source]¶
Implements DeepLIFT algorithm for the neuron based on the following paper: Learning Important Features Through Propagating Activation Differences, Avanti Shrikumar, et. al. https://arxiv.org/abs/1704.02685
and the gradient formulation proposed in: Towards better understanding of gradient-based attribution methods for deep neural networks, Marco Ancona, et.al. https://openreview.net/pdf?id=Sy21R9JAW
This implementation supports only Rescale rule. RevealCancel rule will be supported in later releases. Although DeepLIFT’s(Rescale Rule) attribution quality is comparable with Integrated Gradients, it runs significantly faster than Integrated Gradients and is preferred for large datasets.
Currently we only support a limited number of non-linear activations but the plan is to expand the list in the future.
Note: As we know, currently we cannot access the building blocks, of PyTorch’s built-in LSTM, RNNs and GRUs such as Tanh and Sigmoid. Nonetheless, it is possible to build custom LSTMs, RNNS and GRUs with performance similar to built-in ones using TorchScript. More details on how to build custom RNNs can be found here: https://pytorch.org/blog/optimizing-cuda-rnn-with-torchscript/
- Parameters
model (torch.nn.Module) – The reference to PyTorch model instance.
layer (torch.nn.Module) – Layer for which neuron attributions are computed. Attributions for a particular neuron for the input or output of this layer are computed using the argument neuron_selector in the attribute method. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
multiply_by_inputs (bool, optional) –
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104
In case of Neuron DeepLift, if multiply_by_inputs is set to True, final sensitivity scores are being multiplied by (inputs - baselines). This flag applies only if custom_attribution_func is set to None.
- attribute(inputs, neuron_selector, baselines=None, additional_forward_args=None, attribute_to_neuron_input=False, custom_attribution_func=None)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which layer attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
baselines (scalar, tensor, tuple of scalars or tensors, optional) –
Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided as:
a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or the first dimension is one and the remaining dimensions match with inputs.
a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor.
a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs’ tuple can be:
either a tensor with matching dimensions to corresponding tensor in the inputs’ tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor.
or a scalar, corresponding to a tensor in the inputs’ tuple. This scalar value is broadcasted for corresponding input tensor.
In the cases when baselines is not provided, we internally use zero scalar corresponding to each input tensor.
Default: None
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
custom_attribution_func (callable, optional) –
A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature:
custom_attribution_func(multipliers)
custom_attribution_func(multipliers, inputs)
custom_attribution_func(multipliers, inputs, baselines)
In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, multipliers, inputs and baselines are provided in tuples of same length. custom_attribution_func returns a tuple of attribution tensors that have the same length as the inputs. Default: None
- Returns
- attributions (tensor or tuple of tensors):
Computes attributions using Deeplift’s rescale rule for particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
attributions or 2-element tuple of attributions, delta
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = NeuronDeepLift(net, net.conv4) >>> input = torch.randn(1, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for conv4 layer and neuron >>> # index (4,1,2). >>> attribution = dl.attribute(input, (4,1,2))
Neuron DeepLiftShap¶
- class captum.attr.NeuronDeepLiftShap(model, layer, multiply_by_inputs=True)[source]¶
Extends NeuronAttribution and uses LayerDeepLiftShap algorithms and approximates SHAP values for given input layer and neuron_selector. For each input sample - baseline pair it computes DeepLift attributions with respect to inputs or outputs of given layer and neuron_selector averages resulting attributions across baselines. Whether to compute the attributions with respect to the inputs or outputs of the layer is defined by the input flag attribute_to_layer_input. More details about the algorithm can be found here:
http://papers.nips.cc/paper/7062-a-unified-approach-to-interpreting-model-predictions.pdf
- Note that the explanation model:
Assumes that input features are independent of one another
- Is linear, meaning that the explanations are modeled through
the additive composition of feature effects.
Although, it assumes a linear model for each explanation, the overall model across multiple explanations can be complex and non-linear.
- Parameters
model (torch.nn.Module) – The reference to PyTorch model instance.
layer (torch.nn.Module) – Layer for which neuron attributions are computed. Attributions for a particular neuron for the input or output of this layer are computed using the argument neuron_selector in the attribute method. Currently, only layers with a single tensor input and output are supported.
multiply_by_inputs (bool, optional) –
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104
In case of Neuron DeepLift Shap, if multiply_by_inputs is set to True, final sensitivity scores are being multiplied by (inputs - baselines). This flag applies only if custom_attribution_func is set to None.
- attribute(inputs, neuron_selector, baselines, additional_forward_args=None, attribute_to_neuron_input=False, custom_attribution_func=None)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which layer attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
baselines (tensor, tuple of tensors, callable) –
Baselines define reference samples that are compared with the inputs. In order to assign attribution scores DeepLift computes the differences between the inputs/outputs and corresponding references. Baselines can be provided as:
a single tensor, if inputs is a single tensor, with the first dimension equal to the number of examples in the baselines’ distribution. The remaining dimensions must match with input tensor’s dimension starting from the second dimension.
a tuple of tensors, if inputs is a tuple of tensors, with the first dimension of any tensor inside the tuple equal to the number of examples in the baseline’s distribution. The remaining dimensions must match the dimensions of the corresponding input tensor starting from the second dimension.
callable function, optionally takes inputs as an argument and either returns a single tensor or a tuple of those.
It is recommended that the number of samples in the baselines’ tensors is larger than one.
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
custom_attribution_func (callable, optional) –
A custom function for computing final attribution scores. This function can take at least one and at most three arguments with the following signature:
custom_attribution_func(multipliers)
custom_attribution_func(multipliers, inputs)
custom_attribution_func(multipliers, inputs, baselines)
In case this function is not provided, we use the default logic defined as: multipliers * (inputs - baselines) It is assumed that all input arguments, multipliers, inputs and baselines are provided in tuples of same length. custom_attribution_func returns a tuple of attribution tensors that have the same length as the inputs. Default: None
- Returns
- attributions (tensor or tuple of tensors):
Computes attributions using Deeplift’s rescale rule for particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
attributions or 2-element tuple of attributions, delta
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> # creates an instance of LayerDeepLift to interpret target >>> # class 1 with respect to conv4 layer. >>> dl = NeuronDeepLiftShap(net, net.conv4) >>> input = torch.randn(1, 3, 32, 32, requires_grad=True) >>> # Computes deeplift attribution scores for conv4 layer and neuron >>> # index (4,1,2). >>> attribution = dl.attribute(input, (4,1,2))
Neuron GradientShap¶
- class captum.attr.NeuronGradientShap(forward_func, layer, device_ids=None, multiply_by_inputs=True)[source]¶
Implements gradient SHAP for a neuron in a hidden layer based on the implementation from SHAP’s primary author. For reference, please, view:
https://github.com/slundberg/shap#deep-learning-example-with-gradientexplainer-tensorflowkeraspytorch-models
A Unified Approach to Interpreting Model Predictions http://papers.nips.cc/paper7062-a-unified-approach-to-interpreting-model-predictions
GradientShap approximates SHAP values by computing the expectations of gradients by randomly sampling from the distribution of baselines/references. It adds white noise to each input sample n_samples times, selects a random baseline from baselines’ distribution and a random point along the path between the baseline and the input, and computes the gradient of the neuron with index neuron_selector with respect to those selected random points. The final SHAP values represent the expected values of gradients * (inputs - baselines).
GradientShap makes an assumption that the input features are independent and that the explanation model is linear, meaning that the explanations are modeled through the additive composition of feature effects. Under those assumptions, SHAP value can be approximated as the expectation of gradients that are computed for randomly generated n_samples input samples after adding gaussian noise n_samples times to each input for different baselines/references.
In some sense it can be viewed as an approximation of integrated gradients by computing the expectations of gradients for different baselines.
Current implementation uses Smoothgrad from NoiseTunnel in order to randomly draw samples from the distribution of baselines, add noise to input samples and compute the expectation (smoothgrad).
- Parameters
forward_func (callable) – The forward function of the model or any modification of it
layer (torch.nn.Module) – Layer for which neuron attributions are computed. The output size of the attribute method matches the dimensions of the inputs or ouputs of the neuron with index neuron_selector in this layer, depending on whether we attribute to the inputs or outputs of the neuron. Currently, it is assumed that the inputs or the outputs of the neurons in this layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
multiply_by_inputs (bool, optional) –
Indicates whether to factor model inputs’ multiplier in the final attribution scores. In the literature this is also known as local vs global attribution. If inputs’ multiplier isn’t factored in then that type of attribution method is also called local attribution. If it is, then that type of attribution method is called global. More detailed can be found here: https://arxiv.org/abs/1711.06104
In case of Neuron Gradient SHAP, if multiply_by_inputs is set to True, the sensitivity scores for scaled inputs are being multiplied by (inputs - baselines).
- attribute(inputs, neuron_selector, baselines, n_samples=5, stdevs=0.0, additional_forward_args=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which SHAP attribution values are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
baselines (tensor, tuple of tensors, callable) –
Baselines define the starting point from which expectation is computed and can be provided as:
a single tensor, if inputs is a single tensor, with the first dimension equal to the number of examples in the baselines’ distribution. The remaining dimensions must match with input tensor’s dimension starting from the second dimension.
a tuple of tensors, if inputs is a tuple of tensors, with the first dimension of any tensor inside the tuple equal to the number of examples in the baseline’s distribution. The remaining dimensions must match the dimensions of the corresponding input tensor starting from the second dimension.
callable function, optionally takes inputs as an argument and either returns a single tensor or a tuple of those.
It is recommended that the number of samples in the baselines’ tensors is larger than one.
n_samples (int, optional) – The number of randomly generated examples per sample in the input batch. Random examples are generated by adding gaussian random noise to each sample. Default: 5 if n_samples is not provided.
stdevs (float, or a tuple of floats optional) – The standard deviation of gaussian noise with zero mean that is added to each input in the batch. If stdevs is a single float value then that same value is used for all inputs. If it is a tuple, then it must have the same length as the inputs tuple. In this case, each stdev value in the stdevs tuple corresponds to the input with the same index in the inputs tuple. Default: 0.0
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It can contain a tuple of ND tensors or any arbitrary python type of any shape. In case of the ND tensor the first dimension of the tensor must correspond to the batch size. It will be repeated for each n_steps for each randomly generated input sample. Note that the gradients are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Attribution score computed based on GradientSHAP with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
attributions or 2-element tuple of attributions, delta
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> neuron_grad_shap = NeuronGradientShap(net, net.linear2) >>> input = torch.randn(3, 3, 32, 32, requires_grad=True) >>> # choosing baselines randomly >>> baselines = torch.randn(20, 3, 32, 32) >>> # Computes gradient SHAP of first neuron in linear2 layer >>> # with respect to the input's of the network. >>> # Attribution size matches input size: 3x3x32x32 >>> attribution = neuron_grad_shap.attribute(input, neuron_ind=0 baselines)
Neuron Guided Backprop¶
- class captum.attr.NeuronGuidedBackprop(model, layer, device_ids=None)[source]¶
Computes attribution of the given neuron using guided backpropagation. Guided backpropagation computes the gradient of the target neuron with respect to the input, but gradients of ReLU functions are overridden so that only non-negative gradients are backpropagated.
More details regarding the guided backpropagation algorithm can be found in the original paper here: https://arxiv.org/abs/1412.6806
Warning: Ensure that all ReLU operations in the forward function of the given model are performed using a module (nn.module.ReLU). If nn.functional.ReLU is used, gradients are not overridden appropriately.
- Parameters
model (Module) – The reference to PyTorch model instance.
layer (Module) – Layer for which neuron attributions are computed. Attributions for a particular neuron in the output of this layer are computed using the argument neuron_selector in the attribute method. Currently, only layers with a single tensor output are supported.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
- attribute(inputs, neuron_selector, additional_forward_args=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neurons, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Guided backprop attribution of particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_gb = NeuronGuidedBackprop(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron guided backpropagation for neuron with >>> # index (4,1,2). >>> attribution = neuron_gb.attribute(input, (4,1,2))
Neuron Deconvolution¶
- class captum.attr.NeuronDeconvolution(model, layer, device_ids=None)[source]¶
Computes attribution of the given neuron using deconvolution. Deconvolution computes the gradient of the target output with respect to the input, but gradients of ReLU functions are overridden so that the gradient of the ReLU input is simply computed taking ReLU of the output gradient, essentially only propagating non-negative gradients (without dependence on the sign of the ReLU input).
More details regarding the deconvolution algorithm can be found in these papers: https://arxiv.org/abs/1311.2901 https://link.springer.com/chapter/10.1007/978-3-319-46466-4_8
Warning: Ensure that all ReLU operations in the forward function of the given model are performed using a module (nn.module.ReLU). If nn.functional.ReLU is used, gradients are not overridden appropriately.
- Parameters
model (Module) – The reference to PyTorch model instance.
layer (Module) – Layer for which attributions are computed. Output size of attribute matches this layer’s input or output dimensions, depending on whether we attribute to the inputs or outputs of the layer, corresponding to attribution of each neuron in the input or output of this layer. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
- attribute(inputs, neuron_selector, additional_forward_args=None, attribute_to_neuron_input=False)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples (aka batch size), and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order, following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neuron, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
- Returns
- attributions (tensor or tuple of tensors):
Deconvolution attribution of particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x32x32. >>> net = ImageClassifier() >>> neuron_deconv = NeuronDeconvolution(net, net.conv1) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x32x32, we need a tuple in the form (0..11,0..31,0..31) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron deconvolution for neuron with >>> # index (4,1,2). >>> attribution = neuron_deconv.attribute(input, (4,1,2))
Neuron Feature Ablation¶
- class captum.attr.NeuronFeatureAblation(forward_func, layer, device_ids=None)[source]¶
A perturbation based approach to computing neuron attribution, involving replacing each input feature with a given baseline / reference, and computing the difference in the neuron’s input / output. By default, each scalar value within each input tensor is taken as a feature and replaced independently. Passing a feature mask, allows grouping features to be ablated together. This can be used in cases such as images, where an entire segment or region can be ablated, measuring the importance of the segment (feature group). Each input scalar in the group will be given the same attribution value equal to the change in target as a result of ablating the entire feature group.
- Parameters
forward_func (callable) – The forward function of the model or any modification of it
layer (torch.nn.Module) – Layer for which attributions are computed. Attributions for a particular neuron in the input or output of this layer are computed using the argument neuron_selector in the attribute method. Currently, it is assumed that the inputs or the outputs of the layer, depending on which one is used for attribution, can only be a single tensor.
device_ids (list(int)) – Device ID list, necessary only if forward_func applies a DataParallel model. This allows reconstruction of intermediate outputs from batched results across devices. If forward_func is given as the DataParallel model itself, then it is not necessary to provide this argument.
- attribute(inputs, neuron_selector, baselines=None, additional_forward_args=None, feature_mask=None, attribute_to_neuron_input=False, perturbations_per_eval=1)[source]¶
- Parameters
inputs (tensor or tuple of tensors) – Input for which neuron attributions are computed. If forward_func takes a single tensor as input, a single input tensor should be provided. If forward_func takes multiple tensors as input, a tuple of the input tensors should be provided. It is assumed that for all given input tensors, dimension 0 corresponds to the number of examples, and if multiple input tensors are provided, the examples must be aligned appropriately.
neuron_selector (int, callable, or tuple of ints or slices) –
Selector for neuron in given layer for which attribution is desired. Neuron selector can be provided as:
a single integer, if the layer output is 2D. This integer selects the appropriate neuron column in the layer input or output
a tuple of integers or slice objects. Length of this tuple must be one less than the number of dimensions in the input / output of the given layer (since dimension 0 corresponds to number of examples). The elements of the tuple can be either integers or slice objects (slice object allows indexing a range of neurons rather individual ones).
If any of the tuple elements is a slice object, the indexed output tensor is used for attribution. Note that specifying a slice of a tensor would amount to computing the attribution of the sum of the specified neurons, and not the individual neurons independantly.
a callable, which should take the target layer as input (single tensor or tuple if multiple tensors are in layer) and return a neuron or aggregate of the layer’s neurons for attribution. For example, this function could return the sum of the neurons in the layer or sum of neurons with activations in a particular range. It is expected that this function returns either a tensor with one element or a 1D tensor with length equal to batch_size (one scalar per input example)
baselines (scalar, tensor, tuple of scalars or tensors, optional) –
Baselines define reference value which replaces each feature when ablated. Baselines can be provided as:
a single tensor, if inputs is a single tensor, with exactly the same dimensions as inputs or broadcastable to match the dimensions of inputs
a single scalar, if inputs is a single tensor, which will be broadcasted for each input value in input tensor.
a tuple of tensors or scalars, the baseline corresponding to each tensor in the inputs’ tuple can be:
either a tensor with matching dimensions to corresponding tensor in the inputs’ tuple or the first dimension is one and the remaining dimensions match with the corresponding input tensor.
or a scalar, corresponding to a tensor in the inputs’ tuple. This scalar value is broadcasted for corresponding input tensor.
In the cases when baselines is not provided, we internally use zero scalar corresponding to each input tensor. Default: None
additional_forward_args (any, optional) – If the forward function requires additional arguments other than the inputs for which attributions should not be computed, this argument can be provided. It must be either a single additional argument of a Tensor or arbitrary (non-tuple) type or a tuple containing multiple additional arguments including tensors or any arbitrary python types. These arguments are provided to forward_func in order following the arguments in inputs. Note that attributions are not computed with respect to these arguments. Default: None
feature_mask (tensor or tuple of tensors, optional) – feature_mask defines a mask for the input, grouping features which should be ablated together. feature_mask should contain the same number of tensors as inputs. Each tensor should be the same size as the corresponding input or broadcastable to match the input tensor. Each tensor should contain integers in the range 0 to num_features - 1, and indices corresponding to the same feature should have the same value. Note that features within each input tensor are ablated independently (not across tensors). If None, then a feature mask is constructed which assigns each scalar within a tensor as a separate feature, which is ablated independently. Default: None
attribute_to_neuron_input (bool, optional) – Indicates whether to compute the attributions with respect to the neuron input or output. If attribute_to_neuron_input is set to True then the attributions will be computed with respect to neuron’s inputs, otherwise it will be computed with respect to neuron’s outputs. Note that currently it is assumed that either the input or the output of internal neurons, depending on whether we attribute to the input or output, is a single tensor. Support for multiple tensors will be added later. Default: False
perturbations_per_eval (int, optional) – Allows ablation of multiple features to be processed simultaneously in one call to forward_fn. Each forward pass will contain a maximum of perturbations_per_eval * #examples samples. For DataParallel models, each batch is split among the available devices, so evaluations on each available device contain at most (perturbations_per_eval * #examples) / num_devices samples. Default: 1
- Returns
- attributions (tensor or tuple of tensors):
Attributions of particular neuron with respect to each input feature. Attributions will always be the same size as the provided inputs, with each value providing the attribution of the corresponding input index. If a single tensor is provided as inputs, a single tensor is returned. If a tuple is provided for inputs, a tuple of corresponding sized tensors is returned.
- Return type
tensor or tuple of tensors of attributions
Examples:
>>> # SimpleClassifier takes a single input tensor of size Nx4x4, >>> # and returns an Nx3 tensor of class probabilities. >>> # It contains an attribute conv1, which is an instance of nn.conv2d, >>> # and the output of this layer has dimensions Nx12x3x3. >>> net = SimpleClassifier() >>> # Generating random input with size 2 x 4 x 4 >>> input = torch.randn(2, 4, 4) >>> # Defining NeuronFeatureAblation interpreter >>> ablator = NeuronFeatureAblation(net, net.conv1) >>> # To compute neuron attribution, we need to provide the neuron >>> # index for which attribution is desired. Since the layer output >>> # is Nx12x3x3, we need a tuple in the form (0..11,0..2,0..2) >>> # which indexes a particular neuron in the layer output. >>> # For this example, we choose the index (4,1,2). >>> # Computes neuron gradient for neuron with >>> # index (4,1,2). >>> # Computes ablation attribution, ablating each of the 16 >>> # scalar inputs independently. >>> attr = ablator.attribute(input, neuron_selector=(4,1,2)) >>> # Alternatively, we may want to ablate features in groups, e.g. >>> # grouping each 2x2 square of the inputs and ablating them together. >>> # This can be done by creating a feature mask as follows, which >>> # defines the feature groups, e.g.: >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 0 | 0 | 1 | 1 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # | 2 | 2 | 3 | 3 | >>> # +---+---+---+---+ >>> # With this mask, all inputs with the same value are ablated >>> # simultaneously, and the attribution for each input in the same >>> # group (0, 1, 2, and 3) per example are the same. >>> # The attributions can be calculated as follows: >>> # feature mask has dimensions 1 x 4 x 4 >>> feature_mask = torch.tensor([[[0,0,1,1],[0,0,1,1], >>> [2,2,3,3],[2,2,3,3]]]) >>> attr = ablator.attribute(input, neuron_selector=(4,1,2), >>> feature_mask=feature_mask)