quantus.helpers.utils module

This module contains the utils functions of the library.

quantus.helpers.utils.blur_at_indices(arr: array, kernel: array, indices: int | Sequence[int] | Tuple[array] | Tuple[slice, ...], indexed_axes: Sequence[int]) array

Creates a version of arr that is blurred at indices.

Parameters:
arr: np.ndarray

Array to be perturbed.

kernel: np.ndarray

Kernel used for blurring.

indices: int, sequence, tuple

Array-like, with a subset shape of arr.

indexed_axes: sequence
The dimensions of arr that are indexed. These need to be consecutive and either

include the first or last dimension of array.

Returns:
np.ndarray

A version of arr that is blurred at indices.

quantus.helpers.utils.calculate_auc(values: array, dx: int = 1, batched: bool = False)

Calculate area under the curve using the composite trapezoidal rule.

Parameters:
values: np.ndarray

Input array.

dx: integer

The spacing between sample points. The default is 1.

Returns:
np.ndarray

Definite integral of values.

quantus.helpers.utils.create_patch_slice(patch_size: int | Sequence[int], coords: Sequence[int]) Tuple[slice, ...]

Create a patch slice from patch size and coordinates.

Parameters:
patch_size: int, sequence

One- or multidimensional patch size.

coords: sequence

Coordinates for creating patches.

Returns:
tuple

Patches at all provided coordinates.

quantus.helpers.utils.expand_attribution_channel(a_batch: ndarray, x_batch: ndarray)

Expand additional channel dimension(s) for attributions if needed.

Parameters:
x_batch: np.ndarray

A np.ndarray which contains the input data that are explained.

a_batch: np.ndarray

An array which contains pre-computed attributions i.e., explanations.

Returns:
np.ndarray

A x_batch with dimensions matching those of a_batch.

quantus.helpers.utils.expand_indices(arr: array, indices: int | Sequence[int] | Tuple[array] | Tuple[slice, ...], indexed_axes: Sequence[int]) Tuple
Expands indices to fit array shape. Returns expanded indices.
–> if indices are a sequence of ints, they are interpreted as indices to the flattened arr,

and subsequently expanded

–> if indices contains only slices and 1D sequences for arr, everything is interpreted as slices –> if indices contains already expanded indices, they are returned as is

Parameters:
arr: np.ndarray

The input to the expanded.

indices: int, sequence, tuple

A list of indices.

indexed_axes: sequence

Refers to all axes that are not indexed by slice(None).

Returns:
tuple

Expanded indices.

quantus.helpers.utils.filter_compatible_patch_sizes(perturb_patch_sizes: list, img_size: int) list

Remove patch sizes that are not compatible with input size.

Parameters:
perturb_patch_sizes: list:

Patch sizes for perturbation.

img_size: integer

A single dimension of an image array.

Returns:
list:

All integers within perturb_patch_sizes which are compatible with the image.

quantus.helpers.utils.get_baseline_dict(arr: ndarray, patch: ndarray | None = None, batched: bool = False, **kwargs) dict

Make a dictionary of baseline approaches depending on the input x (or patch of input).

Parameters:
arr: np.ndarray

CxWxH image array used to calculate baseline values, i.e. for “mean”, “black” and “white” methods.

patch: np.ndarray, optional

CxWxH patch array to calculate baseline values, necessary for “neighbourhood_mean” and “neighbourhood_random_min_max” methods.

batched: bool

If True, the arr and patch are assumed to be of shape B x <single_array_shape>. The aggregations are done over the individual batch elements.

kwargs: optional

Keyword arguments..

Returns:
fill_dict: dict

Maps all available baseline methods to baseline values.

quantus.helpers.utils.get_baseline_value(value: float | int | str | array, arr: ndarray, return_shape: Tuple, patch: ndarray | None = None, batched: bool = False, **kwargs) array

Get the baseline value to fill the array with, in the shape of return_shape.

Parameters:
value: float, int, str, np.ndarray

Either the value (float, int) to fill the array with, a method (string) used to construct baseline array (“mean”, “uniform”, “black”, “white”, “neighbourhood_mean” or “neighbourhood_random_min_max”), or the array (np.array) to be returned.

arr: np.ndarray

CxWxH image array used to calculate baseline values, i.e. for “mean”, “black” and “white” methods.

return_shape: tuple

CxWxH shape to be returned.

patch: np.ndarray, optional

CxWxH patch array to calculate baseline values. Necessary for “neighbourhood_mean” and “neighbourhood_random_min_max” methods.

batched: bool,

If True, the arr and patch are assumed to be of shape B x <single_array_shape>. The aggregations are done over the individual batch elements.

kwargs: optional

Keyword arguments.

Returns:
np.ndarray

Baseline array in return_shape.

quantus.helpers.utils.get_block_indices(x_batch: array, patch_size: int) array

Get blocks for a batch of images using a certain patch_size.

Parameters:
x_batch: np.array

Batch of images, shape B x C x H x W

patch_size: int

Size of the patch.

Yields:
np.array

Yields blocks of image of a certain patch_size.

quantus.helpers.utils.get_features_in_step(max_steps_per_input: int, input_shape: Tuple[int, ...])

Get the number of features in the iteration.

Parameters:
max_steps_per_input: integer

The number of repeated iterations on an image.

input_shape: tuple

Input shape.

Returns:
float

Product of the input shape divided by the maximum number of steps.

quantus.helpers.utils.get_leftover_shape(arr: array, axes: Sequence[int]) Tuple

Gets the shape of the arr dimensions not included in axes.

Parameters:
arr: np.ndarray

The input to the expanded.

axes: sequence

A sequence of ints containing the axes.

Returns:
leftover_shape: tuple

The leftover shape.

quantus.helpers.utils.get_name(name: str)

Get the name of the Metric class object.

Parameters:
name: string

A metric name.

Returns:
name: string

A cleaned version of the Metric name.

quantus.helpers.utils.get_nr_patches(patch_size: int | Sequence[int], shape: Tuple[int, ...], overlap: bool = False) int

Get number of patches for given shape.

Parameters:
patch_size: int, sequence

One- or multidimensional patch size.

shape (shape: Tuple[int, …]): The image shape.
overlap: boolean

Indicates whether overlapping patches is used or not.

Returns:
integer

Number of patches that fit into the image.

quantus.helpers.utils.get_padding_size(dim: int, patch_size: int) Tuple[int, int]

Calculate the padding size (optionally) needed for a patch_size.

Parameters:
dim: int

Input dimension to pad (for example width or height of the image).

patch_size: int

Size of the patch for this dimension of input.

Returns:
Tuple[int, int]

A tuple of values passed to the utils._pad_array method for a particular dimension.

quantus.helpers.utils.get_superpixel_segments(img: ndarray, segmentation_method: str) ndarray

Given an image, return segments or so-called ‘super-pixels’ segments i.e., an 2D mask with segment labels.

Parameters:
img: np.ndarray

CxWxH image array.

segmentation_method: string

Indicates the segmentation method, i.e. “slic” or “felzenszwalb”.

Returns:
img: np.ndarray

CxWxH segmented image array.

quantus.helpers.utils.get_wrapped_model(model, channel_first: bool, softmax: bool, device: str | None = None, model_predict_kwargs: Dict[str, Any] | None = None) ModelInterface

Identifies the type of a model object and wraps the model in an appropriate interface.

Parameters:
model: torch.nn.Module, tf.keras.Model

A model this will be wrapped in the ModelInterface:

channel_first: boolean, optional

Indicates of the image dimensions are channel first, or channel last. Inferred from the input shape if None.

softmax: boolean

Indicates whether to use softmax probabilities or logits in model prediction. This is used for this __call__ only and won’t be saved as attribute. If None, self.softmax is used.

device: string

Indicated the device on which a torch.Tensor is or will be allocated: “cpu” or “gpu”.

model_predict_kwargs: dict, optional

Keyword arguments to be passed to the model’s predict method.

Returns:
model: ModelInterface

A wrapped ModelInterface model.

quantus.helpers.utils.identity(x: T) T
quantus.helpers.utils.infer_attribution_axes(a_batch: ndarray, x_batch: ndarray) Sequence[int]

Infers the axes in x_batch that are covered by a_batch.

Parameters:
x_batch: np.ndarray

A np.ndarray which contains the input data that are explained.

a_batch: np.ndarray

An array which contains pre-computed attributions i.e., explanations.

Returns:
np.ndarray

The axes inferred.

quantus.helpers.utils.infer_channel_first(x: array) bool

Infer if the channels are first.

Assumes:
For 1D input:

nr_channels < sequence_length

For 2D input:

nr_channels < img_width and nr_channels < img_height

For higher dimensional input an error is raised. For input in n_features x n_batches format True is returned (no channel).

Parameters:
x: np.ndarray

Input image.

Returns:
For 1D input:

True for input shape (nr_batch, nr_features).

For 2D input:

True if input shape is (nr_batch, nr_channels, sequence_length). False if input shape is (nr_batch, sequence_length, nr_channels). An error is raised if the two last dimensions are equal.

For 3D input:

True if input shape is (nr_batch, nr_channels, img_width, img_height). False if input shape is (nr_batch, img_width, img_height, nr_channels). An error is raised if the three last dimensions are equal.

quantus.helpers.utils.make_channel_first(x: array, channel_first: bool = False)

Reshape batch to channel first.

Parameters:
x: np.ndarray

The input image.

channel_first: boolean, optional

Indicates of the image dimensions are channel first, or channel last. Inferred from the input shape if None.

Returns:
np.ndarray

Image in CxWxH format.

quantus.helpers.utils.make_channel_last(x: array, channel_first: bool = True)

Reshape batch to channel last.

Parameters:
x: np.ndarray

The input image.

channel_first: boolean, optional

Indicates of the image dimensions are channel first, or channel last. Inferred from the input shape if None.

Returns:
np.ndarray

Image in WxHxC format.

quantus.helpers.utils.offset_coordinates(indices: list | Sequence[int] | Tuple[Any], offset: tuple, img_shape: tuple)
Checks if offset coordinates are within the image frame.

Adapted from: https://github.com/tleemann/road_evaluation.

Parameters:
indices: list

List of indices to be offset.

offset: tuple

Offset for the coordinates, e.g. offset (1,1) adds 1 to both coordinates.

img_shape: tuple

Image shape in (channels, height, width) format.

Returns:
list

Offset coordinates for valid indices and the list of booleans which identifies valid ids.