Measures explanation complexity as the Shannon entropy of the attribution distribution (Bhatt et al., 2020). Lower entropy means a sparser, simpler explanation. ↓ better.

Includes complexity_entropy (per-feature) and complexity_entropy_feature_grouped (pooled over feature groups defined by a mask).

complexity_entropy

Functions:

complexity_entropy

complexity_entropy(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | Tensor | list[Tensor]

Implementation of Complexity metric by Bhatt et al., 2020. 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 of attributions is defined as the entropy of the fractional contribution of feature x_i to the total magnitude of the attribution. A complex explanation is one that uses all features in its explanation to explain some decision. Even though such an explanation may be faithful to the model output, if the number of features is too large it may be too difficult for the user to understand the explanations, rendering it useless. Smaller value of complexity indicates that the explanation is simple and uses fewer features to explain the decision.

References

1) Umang Bhatt et al.: "Evaluating and aggregating feature-based model explanations." IJCAI (2020): 3016-3022.

Parameters:

  • attributions

    (Tuple[Tensor, ...]) –

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

  • 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 complexity scores 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
>>> complexity_entropy_scores = complexity(attribution)
Source code in torchxai/metrics/complexity/complexity_entropy.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
def complexity_entropy(
    attributions: tuple[torch.Tensor, ...] | list[tuple[torch.Tensor, ...]],
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Complexity metric by Bhatt et al., 2020. 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 of attributions is defined as the entropy of the fractional contribution of feature x_i to the total
    magnitude of the attribution. A complex explanation is one that uses all features in its explanation to explain
    some decision. Even though such an explanation may be faithful to the model output, if the number of features is
    too large it may be too difficult for the user to understand the explanations, rendering it useless. Smaller value
    of complexity indicates that the explanation is simple and uses fewer features to explain the decision.

    References:
        1) Umang Bhatt et al.: "Evaluating and aggregating
        feature-based model explanations." IJCAI (2020): 3016-3022.

    Args:
        attributions (Tuple[Tensor,...]): A tuple of tensors representing attributions of separate inputs. Each
            tensor in the tuple has shape (batch_size, num_features).
        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 complexity scores 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
        >>> complexity_entropy_scores = complexity(attribution)
    """
    if multi_target:
        assert isinstance(attributions, list), (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
        score = [
            _complexity_entropy(attributions=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_entropy(attributions=attributions)
        if return_dict:
            return {"score": score}
        return score

complexity_entropy_feature_grouped

complexity_entropy_feature_grouped(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    feature_mask: tuple[Tensor, ...] | None = None,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | Tensor | list[Tensor]

Implementation of Complexity metric by Bhatt et al., 2020. 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 of attributions is defined as the entropy of the fractional contribution of feature x_i to the total magnitude of the attribution. A complex explanation is one that uses all features in its explanation to explain some decision. Even though such an explanation may be faithful to the model output, if the number of features is too large it may be too difficult for the user to understand the explanations, rendering it useless.

References

1) Umang Bhatt et al.: "Evaluating and aggregating feature-based model explanations." IJCAI (2020): 3016-3022.

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
    
  • 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 complexity scores 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
>>> complexity_scores = complexity(attribution)
Source code in torchxai/metrics/complexity/complexity_entropy.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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
def complexity_entropy_feature_grouped(
    attributions: tuple[torch.Tensor, ...] | list[tuple[torch.Tensor, ...]],
    feature_mask: tuple[torch.Tensor, ...] | None = None,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Complexity metric by Bhatt et al., 2020. 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 of attributions is defined as the entropy of the fractional contribution of feature x_i to the total
    magnitude of the attribution. A complex explanation is one that uses all features in its explanation to explain
    some decision. Even though such an explanation may be faithful to the model output, if the number of features is
    too large it may be too difficult for the user to understand the explanations, rendering it useless.

    References:
        1) Umang Bhatt et al.: "Evaluating and aggregating
        feature-based model explanations." IJCAI (2020): 3016-3022.

    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
        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 complexity scores 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
        >>> complexity_scores = complexity(attribution)
    """
    if multi_target:
        assert isinstance(attributions, list), (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
        score = [
            _complexity_entropy_feature_grouped(
                attributions=attribution, feature_mask=feature_mask
            )
            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_entropy_feature_grouped(
            attributions=attributions, feature_mask=feature_mask
        )
        if return_dict:
            return {"score": score}
        return score