Counts the number of features (or feature groups) with non-zero attribution (Sundararajan & Najmi, 2020). Simpler explanations have fewer active features. ↓ better.

Includes complexity_sundararajan (per-feature) and complexity_sundararajan_feature_grouped (pooled over feature groups defined by a mask).

complexity_sundararajan

Functions:

complexity_sundararajan

complexity_sundararajan(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    eps: float = 1e-05,
    normalize_attribution: bool = True,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | Tensor | list[Tensor]

Implementation of Complexity metric by Sundararajan at el., 2017. This implementation reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library. In addition, the implementation takes some ideas about the implementation of the metric from the python Quantus library.

Complexity measures how many attributions in absolute values are exceeding a certain threshold (eps) where a value above the specified threshold implies that the features are important and under indicates it is not. Complexity requires the attributions to be normalized to return reasonable outputs since the original attributions may have different scales and effective complexity is sensitive to the scale of the attributions.

References

1) Mukund Sundararajan, Ankur Taly, and Qiqi Yan. Axiomatic Attribution for Deep Networks. In Proceedings of the 34th International Conference on Machine Learning - Volume 70, ICML’17, pages 3319–3328. JMLR.org, 2017. 1) An-phi Nguyen and María Rodríguez Martínez.: "On quantitative aspects of model interpretability." arXiv preprint arXiv:2007.07584 (2020).

Parameters:

  • attributions

    (Tuple[Tensor, ...]) –

    A tuple of tensors representing attributions of separate inputs. Each tensor in the tuple has shape (batch_size, num_features).

  • eps

    (float, default: 1e-05 ) –

    The threshold value for attributions to be considered important.

  • normalize_attribution

    (bool, default: True ) –

    If True, the attributions are normalized to sum to 1.

  • multi_target

    (bool, default: False ) –

    A boolean flag that indicates whether the metric computation is for multi-target explanations. if set to true, the targets are required to be a list of integers each corresponding to a required target class in the output. The corresponding metric outputs are then returned as a list of metric outputs corresponding to each target class. Default is False.

  • return_dict

    (bool, default: False ) –

    A boolean flag that indicates whether the metric outputs are returned as a dictionary with keys as the metric names and values as the corresponding metric outputs. Default is False.

Returns: Tensor: A tensor of scalar effective complexity per input example. The first dimension is equal to the number of examples in the input batch and the second dimension is one.

Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> saliency = Saliency(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> baselines = torch.zeros(2, 3, 32, 32) >>> # Computes saliency maps for class 3. >>> attribution = saliency.attribute(input, target=3) >>> # define a perturbation function for the input

>>> # Computes the monotonicity correlation and non-sensitivity scores for saliency maps
>>> effective_complexity_scores = effective_complexity(attribution)
Source code in torchxai/metrics/complexity/complexity_sundararajan.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def complexity_sundararajan(
    attributions: tuple[torch.Tensor, ...] | list[tuple[torch.Tensor, ...]],
    eps: float = 1e-5,
    normalize_attribution: bool = True,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Complexity metric by Sundararajan at el., 2017. This implementation
    reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library.
    In addition, the implementation takes some ideas about the implementation of the metric from the python
    Quantus library.

    Complexity measures how many attributions in absolute values are exceeding a certain threshold (eps)
    where a value above the specified threshold implies that the features are important and under indicates it is not.
    Complexity requires the attributions to be normalized to return reasonable outputs since the original
    attributions may have different scales and effective complexity is sensitive to the scale of the attributions.

    References:
        1) Mukund Sundararajan, Ankur Taly, and Qiqi Yan. Axiomatic Attribution for Deep Networks.
        In Proceedings of the 34th International Conference on Machine Learning - Volume 70, ICML’17,
        pages 3319–3328. JMLR.org, 2017.
        1) An-phi Nguyen and María Rodríguez Martínez.: "On quantitative aspects of model
        interpretability." arXiv preprint arXiv:2007.07584 (2020).

    Args:
        attributions (Tuple[Tensor,...]): A tuple of tensors representing attributions of separate inputs. Each
            tensor in the tuple has shape (batch_size, num_features).
        eps (float): The threshold value for attributions to be considered important.
        normalize_attribution (bool): If True, the attributions are normalized to sum to 1.
        multi_target (bool, optional): A boolean flag that indicates whether the metric computation is for
                multi-target explanations. if set to true, the targets are required to be a list of integers
                each corresponding to a required target class in the output. The corresponding metric outputs
                are then returned as a list of metric outputs corresponding to each target class.
                Default is False.
        return_dict (bool, optional): A boolean flag that indicates whether the metric outputs are returned as a dictionary
                with keys as the metric names and values as the corresponding metric outputs.
                Default is False.
    Returns:
        Tensor: A tensor of scalar effective complexity per
                input example. The first dimension is equal to the
                number of examples in the input batch and the second
                dimension is one.

    Examples::
        >>> # ImageClassifier takes a single input tensor of images Nx3x32x32,
        >>> # and returns an Nx10 tensor of class probabilities.
        >>> net = ImageClassifier()
        >>> saliency = Saliency(net)
        >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
        >>> baselines = torch.zeros(2, 3, 32, 32)
        >>> # Computes saliency maps for class 3.
        >>> attribution = saliency.attribute(input, target=3)
        >>> # define a perturbation function for the input

        >>> # Computes the monotonicity correlation and non-sensitivity scores for saliency maps
        >>> effective_complexity_scores = effective_complexity(attribution)
    """
    if multi_target:
        assert isinstance(attributions, list), (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
        score = [
            _complexity_sundararajan(
                attributions=attribution,
                eps=eps,
                normalize_attribution=normalize_attribution,
            )
            for attribution in attributions
        ]
        if return_dict:
            return {"score": score}
        return score
    else:
        assert not isinstance(attributions, list), (
            "attributions must be a single tensor or tuple of tensors when multi_target is False"
        )
        score = _complexity_sundararajan(
            attributions=attributions,
            eps=eps,
            normalize_attribution=normalize_attribution,
        )
        if return_dict:
            return {"score": score}
        return score

complexity_sundararajan_feature_grouped

complexity_sundararajan_feature_grouped(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    feature_mask: tuple[Tensor, ...] | None = None,
    eps: float = 1e-05,
    normalize_attribution: bool = True,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | Tensor | list[Tensor]

Implementation of Complexity metric by Sundararajan at el., 2017. This implementation reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library. In addition, the implementation takes some ideas about the implementation of the metric from the python Quantus library. In this particular implementation, the attributions are grouped into feature groups and the complexity is computed based on the entropy of the fractional contribution of feature groups to the total magnitude of the attribution.

Complexity measures how many attributions in absolute values are exceeding a certain threshold (eps) where a value above the specified threshold implies that the features are important and under indicates it is not. Complexity requires the attributions to be normalized to return reasonable outputs since the original attributions may have different scales and effective complexity is sensitive to the scale of the attributions.

References

1) Mukund Sundararajan, Ankur Taly, and Qiqi Yan. Axiomatic Attribution for Deep Networks. In Proceedings of the 34th International Conference on Machine Learning - Volume 70, ICML’17, pages 3319–3328. JMLR.org, 2017. 1) An-phi Nguyen and María Rodríguez Martínez.: "On quantitative aspects of model interpretability." arXiv preprint arXiv:2007.07584 (2020).

Parameters:

  • attributions

    (Tuple[Tensor, ...]) –

    A tuple of tensors representing attributions of separate inputs. Each tensor in the tuple has shape (batch_size, num_features).

  • feature_mask

    (Tensor or tuple[Tensor, ...], default: None ) –
        feature_mask defines a mask for the input, grouping
        features which should be perturbed 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 perturbed
        independently (not across tensors).
        If the forward function returns a single scalar per batch,
        we enforce that the first dimension of each mask must be 1,
        since attributions are returned batch-wise rather than per
        example, so the attributions must correspond to the
        same features (indices) in each input example.
        If None, then a feature mask is constructed which assigns
        each scalar within a tensor as a separate feature, which
        is perturbed independently.
        Default: None
    
  • eps

    (float, default: 1e-05 ) –

    The threshold value for attributions to be considered important.

  • normalize_attribution

    (bool, default: True ) –

    If True, the attributions are normalized to sum to 1.

  • multi_target

    (bool, default: False ) –

    A boolean flag that indicates whether the metric computation is for multi-target explanations. if set to true, the targets are required to be a list of integers each corresponding to a required target class in the output. The corresponding metric outputs are then returned as a list of metric outputs corresponding to each target class. Default is False.

  • return_dict

    (bool, default: False ) –

    A boolean flag that indicates whether the metric outputs are returned as a dictionary with keys as the metric names and values as the corresponding metric outputs. Default is False.

Returns: Tensor: A tensor of scalar effective complexity per input example. The first dimension is equal to the number of examples in the input batch and the second dimension is one.

Examples:: >>> # ImageClassifier takes a single input tensor of images Nx3x32x32, >>> # and returns an Nx10 tensor of class probabilities. >>> net = ImageClassifier() >>> saliency = Saliency(net) >>> input = torch.randn(2, 3, 32, 32, requires_grad=True) >>> baselines = torch.zeros(2, 3, 32, 32) >>> # Computes saliency maps for class 3. >>> attribution = saliency.attribute(input, target=3) >>> # define a perturbation function for the input

>>> # Computes the monotonicity correlation and non-sensitivity scores for saliency maps
>>> effective_complexity_scores = effective_complexity(attribution)
Source code in torchxai/metrics/complexity/complexity_sundararajan.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def complexity_sundararajan_feature_grouped(
    attributions: tuple[torch.Tensor, ...] | list[tuple[torch.Tensor, ...]],
    feature_mask: tuple[torch.Tensor, ...] | None = None,
    eps: float = 1e-5,
    normalize_attribution: bool = True,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Complexity metric by Sundararajan at el., 2017. This implementation
    reuses the batch-computation ideas from captum and therefore it is fully compatible with the Captum library.
    In addition, the implementation takes some ideas about the implementation of the metric from the python
    Quantus library. In this particular implementation, the attributions are grouped into feature groups and the
    complexity is computed based on the entropy of the fractional contribution of feature groups to the total
    magnitude of the attribution.


    Complexity measures how many attributions in absolute values are exceeding a certain threshold (eps)
    where a value above the specified threshold implies that the features are important and under indicates it is not.
    Complexity requires the attributions to be normalized to return reasonable outputs since the original
    attributions may have different scales and effective complexity is sensitive to the scale of the attributions.

    References:
        1) Mukund Sundararajan, Ankur Taly, and Qiqi Yan. Axiomatic Attribution for Deep Networks.
        In Proceedings of the 34th International Conference on Machine Learning - Volume 70, ICML’17,
        pages 3319–3328. JMLR.org, 2017.
        1) An-phi Nguyen and María Rodríguez Martínez.: "On quantitative aspects of model
        interpretability." arXiv preprint arXiv:2007.07584 (2020).

    Args:
        attributions (Tuple[Tensor,...]): A tuple of tensors representing attributions of separate inputs. Each
            tensor in the tuple has shape (batch_size, num_features).
        feature_mask (Tensor or tuple[Tensor, ...], optional):
                    feature_mask defines a mask for the input, grouping
                    features which should be perturbed 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 perturbed
                    independently (not across tensors).
                    If the forward function returns a single scalar per batch,
                    we enforce that the first dimension of each mask must be 1,
                    since attributions are returned batch-wise rather than per
                    example, so the attributions must correspond to the
                    same features (indices) in each input example.
                    If None, then a feature mask is constructed which assigns
                    each scalar within a tensor as a separate feature, which
                    is perturbed independently.
                    Default: None
        eps (float): The threshold value for attributions to be considered important.
        normalize_attribution (bool): If True, the attributions are normalized to sum to 1.
        multi_target (bool, optional): A boolean flag that indicates whether the metric computation is for
                multi-target explanations. if set to true, the targets are required to be a list of integers
                each corresponding to a required target class in the output. The corresponding metric outputs
                are then returned as a list of metric outputs corresponding to each target class.
                Default is False.
        return_dict (bool, optional): A boolean flag that indicates whether the metric outputs are returned as a dictionary
                with keys as the metric names and values as the corresponding metric outputs.
                Default is False.
    Returns:
        Tensor: A tensor of scalar effective complexity per
                input example. The first dimension is equal to the
                number of examples in the input batch and the second
                dimension is one.

    Examples::
        >>> # ImageClassifier takes a single input tensor of images Nx3x32x32,
        >>> # and returns an Nx10 tensor of class probabilities.
        >>> net = ImageClassifier()
        >>> saliency = Saliency(net)
        >>> input = torch.randn(2, 3, 32, 32, requires_grad=True)
        >>> baselines = torch.zeros(2, 3, 32, 32)
        >>> # Computes saliency maps for class 3.
        >>> attribution = saliency.attribute(input, target=3)
        >>> # define a perturbation function for the input

        >>> # Computes the monotonicity correlation and non-sensitivity scores for saliency maps
        >>> effective_complexity_scores = effective_complexity(attribution)
    """

    if multi_target:
        assert isinstance(attributions, list), (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
        score = [
            _complexity_sundararajan_feature_grouped(
                attributions=attribution,
                feature_mask=feature_mask,
                eps=eps,
                normalize_attribution=normalize_attribution,
            )
            for attribution in attributions
        ]
        if return_dict:
            return {"score": score}
        return score
    else:
        assert not isinstance(attributions, list), (
            "attributions must be a single tensor or tuple of tensors when multi_target is False"
        )
        score = _complexity_sundararajan_feature_grouped(
            attributions=attributions,
            feature_mask=feature_mask,
            eps=eps,
            normalize_attribution=normalize_attribution,
        )
        if return_dict:
            return {"score": score}
        return score