Computes the Gini index of attribution magnitudes (Chalasani et al.). Higher score means attributions are more concentrated on a small number of features, making the explanation simpler. Does not require a model forward pass or a baseline. ↑ better.

Includes sparseness (per-feature) and sparseness_feature_grouped (pooled over feature groups defined by a mask).

sparseness

Functions:

  • sparseness

    Implementation of Sparseness metric by Chalasani et al., 2020. This implementation

  • sparseness_feature_grouped

    Implementation of Sparseness metric by Chalasani et al., 2020. This implementation

sparseness

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

Implementation of Sparseness metric by Chalasani 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.

Sparseness is quantified using the Gini Index applied to the vector of the absolute values of attributions. The test asks that features that are truly predictive of the output F(x) should have significant contributions, and similarly, that irrelevant (or weakly-relevant) features should have negligible contributions. A higher sparseness score indicates that the attributions are more sparse, i.e., a few features have high attribution values and the rest have low attribution values. This is desirable as it indicates that the model is using a few features to make decisions.

Sparseness does not require the attributions be normalized to return correct outputs.

Assumptions

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 sparseness 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
>>> sparseness_scores = sparseness(attribution)
Source code in torchxai/metrics/complexity/sparseness.py
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
def sparseness(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Sparseness metric by Chalasani 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.

    Sparseness is quantified using the Gini Index applied to the vector of the absolute values of attributions. The
    test asks that features that are truly predictive of the output F(x) should have significant contributions, and
    similarly, that irrelevant (or weakly-relevant) features should have negligible contributions. A higher sparseness
    score indicates that the attributions are more sparse, i.e., a few features have high attribution values and the
    rest have low attribution values. This is desirable as it indicates that the model is using a few features to make
    decisions.

    Sparseness does not require the attributions be normalized to return correct outputs.

    Assumptions:
        - Based on the implementation of the authors as found on the following link:
        <https://github.com/jfc43/advex/blob/master/DNN-Experiments/Fashion-MNIST/utils.py>.

    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 sparseness 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
        >>> sparseness_scores = sparseness(attribution)
    """
    is_attributions_list = isinstance(attributions, list)
    if multi_target:
        assert is_attributions_list, (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
    attributions_list = [attributions] if not is_attributions_list else attributions
    score = [_sparseness(attributions=attribution) for attribution in attributions_list]
    if not is_attributions_list:
        score = score[0]
    if return_dict:
        return {"score": score}
    return score

sparseness_feature_grouped

sparseness_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 Sparseness metric by Chalasani 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.

Sparseness is quantified using the Gini Index applied to the vector of the absolute values of attributions. The test asks that features that are truly predictive of the output F(x) should have significant contributions, and similarly, that irrelevant (or weakly-relevant) features should have negligible contributions. A higher sparseness score indicates that the attributions are more sparse, i.e., a few features have high attribution values and the rest have low attribution values. This is desirable as it indicates that the model is using a few features to make decisions.

Sparseness does not require the attributions be normalized to return correct outputs.

Assumptions

Parameters:

  • attributions

    (Tuple[Tensor, ...]) –

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

        Default: None
    
  • 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 sparseness 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
>>> sparseness_scores = sparseness(attribution)
Source code in torchxai/metrics/complexity/sparseness.py
193
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 sparseness_feature_grouped(
    attributions: tuple[Tensor, ...] | list[tuple[Tensor, ...]],
    feature_mask: tuple[torch.Tensor, ...] | None = None,
    multi_target: bool = False,
    return_dict: bool = False,
) -> dict | torch.Tensor | list[torch.Tensor]:
    """
    Implementation of Sparseness metric by Chalasani 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.

    Sparseness is quantified using the Gini Index applied to the vector of the absolute values of attributions. The
    test asks that features that are truly predictive of the output F(x) should have significant contributions, and
    similarly, that irrelevant (or weakly-relevant) features should have negligible contributions. A higher sparseness
    score indicates that the attributions are more sparse, i.e., a few features have high attribution values and the
    rest have low attribution values. This is desirable as it indicates that the model is using a few features to make
    decisions.

    Sparseness does not require the attributions be normalized to return correct outputs.

    Assumptions:
        - Based on the implementation of the authors as found on the following link:
        <https://github.com/jfc43/advex/blob/master/DNN-Experiments/Fashion-MNIST/utils.py>.

    Args:
        attributions (Tuple[Tensor,...]): A tuple of tensors representing attributions of separate inputs. Each
            tensor in the tuple has shape (batch_size, num_features).

                    Default: None

        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 sparseness 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
        >>> sparseness_scores = sparseness(attribution)
    """
    is_attributions_list = isinstance(attributions, list)
    if multi_target:
        assert is_attributions_list, (
            "attributions must be a list of tensors or list of tuples of tensors"
        )
    attributions_list = [attributions] if not is_attributions_list else attributions
    score = [
        _sparseness_feature_grouped(attributions=attribution, feature_mask=feature_mask)
        for attribution in attributions_list
    ]
    if not is_attributions_list:
        score = score[0]
    if return_dict:
        return {"score": score}
    return score