Skip to content

API reference

Bases: _ConceptsBase

NAVE explainer: concepts from a vision encoder, and explanations of images with them.

Parameters:

Name Type Description Default
model "vitt16" (ViT-Ti/16, the default), "resnet18", "resnet50", "vits16", a torch.nn.Module,

a Backbone, a path to an .onnx file, or a function returning feature maps

'vitt16'
training weights of a built-in model: "random", "imagenet" or "dino" (vitt16: random, imagenet)
'imagenet'
layers built-in models: numbers (``[3, 4]``) or paper notation (``"N34"``, ``"N:9-12"``);

None: N34 for ResNets, the last block for ViTs. Other models: module names.

None
k number of concepts per projector (an upper bound with projector="bayesian")
10
projector None/"kmeans", "bayesian" (Dirichlet-prior k-means, Gibbs sampling), "pca", or

a scikit-learn-style object. Clusterers assign a pixel to the closest prototype, projections (PCA, NMF, ...) to the component with the largest absolute value.

None
bayes_alpha Dirichlet concentration, Gibbs sweeps and

discarded sweeps of projector="bayesian"

1.0
bayes_iter Dirichlet concentration, Gibbs sweeps and

discarded sweeps of projector="bayesian"

1.0
bayes_burn_in Dirichlet concentration, Gibbs sweeps and

discarded sweeps of projector="bayesian"

1.0
upsample "nearest" (default: the paper's blocky maps), "linear" or "cubic": interpolation of deeper

layers and of concept scores to pixels

'nearest'
window "auto" (windows when the longer side is at least `window_factor` times the model's

input size, 224 px for the built-in models: windows twice the input size, every half window, each pixel from the window whose centre is nearest), None (always whole), or a window size in px

'auto'
window_factor see `window`
3
features built-in ViTs: "tokens" (the blocks' outputs, default) or "keys" (the attention keys

of the same blocks, as in LOST and TokenCut). Saliency and class predictions always use the blocks' outputs, which the classifier reads.

'tokens'
fit_on "all" (every composite pixel: exact if they fit in memory, else streamed through

mini-batch k-means, with a warning) or "sample" (sample_size composite pixels)

'all'
sample_size composite pixels used with fit_on="sample" (and to seed streaming)
20000
epochs streaming passes when fit_on="all" falls back to mini-batch k-means
1
normalize per-pixel L2 normalisation of each layer (Algorithm 1, line 9)
True
scale C_min / (1 + C_b) scaling of each layer (Algorithm 1, line 10)
True
uncertainty_temp softmax temperature of the uncertainty (default 0.1). "auto": 1 for

probabilistic projectors, else the median gap between the two best concept scores

0.1
transforms "default" (ImageNet-style normalisation of the model) or a function, or a list

of functions applied in order, from image to image (e.g. a resizing lambda). They get an (H, W, 3) uint8 array. If the last one returns uint8 (or floats in [0, 1]), the model's default normalisation follows; otherwise its output is used as the normalised input. Use only resizing and colour operations: maps are returned at the original size.

'default'
classifier for the classes, correlations and saliency: None (the model's own head), a

torch.nn.Linear, a (classes, C) weight matrix, a (weight, bias) pair, or a function image -> class scores or class id

None
class_names names of the classes for `summarize` (a list or dict)
None
seed random seed
0
device for PyTorch models
'cpu'
progress False, True (progress bar) or a callable(fraction, text)
False
Attributes (after fitting)

fitted : True after an explicit fit prototypes : (K, D) concept prototypes (PCA: components) palette : (K, 3) uint8 concept colours (Spectral by default, along the concept order) patches : (K, 2, 32, 32, 3) uint8, the closest and the largest cell of every concept in the fitting set: dimmed outside the cell, with a 1 px white line around it classes : (C,) the groups given to fit, else the model's predicted classes correlation : (K, C) Pearson correlation between concept proportions and classes

Extract concepts from images.

images : an (N, H, W, 3) or (N, H, W) array (uint8, or float in [0, 1]), or a list of images groups : one label per image: one projector is fitted per group, and the groups become the classes of the correlation merge_groups : merge the groups' projectors into one (predict then ignores groups) reorder : "ward", "average", "single" or None: order of the concept ids. With groups, concepts are ordered by group first, then within each group, and every group gets a colour family.

Recompute the patches (closest and largest cell of every concept) on images.

min_size : minimum height and width, in pixels, of a cell to be the closest one. If no cell is large enough, the largest is used (with a warning); a concept with no cell at all gets an empty patch.

Explanations of images with the fitted concepts: a list of ImageExplanations.

groups : one label per image: use only that group's projector (when fitted with merge_groups=False). None: every projector scores every pixel, the closest wins. uncertainty : also compute the uncertainty map H(softmax(scores / T)) / log K

fit, then predict on the same images.

Explain images: with the fitted concepts after an explicit fit, otherwise by fitting afresh on these images (every call). One image gives one ImageExplanation, several a list.

Superpixels: explain(image).segmentation().

Concept-based saliency: the cosine between the deepest layer's features and the classifier's vector of the target class, averaged over NAVE regions from the deepest layer to the shallowest. One (H, W) float32 map per image (a list for several).

classifier : as in the constructor (overrides it); None uses the constructor's, else the model's own head target : class index; None = the class the model predicts

A figure in the style of the paper's Figure 1, for one image.

Row 1: the image | its explanation (uncertainty as opacity on white if asked) | its saliency (if asked), all at the image's size. Then, for every block of 10 concepts: their correlation with the classes (if available and asked) and their patches ("closest" or "largest"), framed in the concept's colour. Returns the matplotlib Figure. saliency_range : (vmin, vmax) of the saliency colours (default (-1, 1): saliency is a cosine), or "auto": centred on 0, up to the item's largest |saliency|

The NAVE explanation of one image.

Attributes:

Name Type Description
explanation (H, W) int32, the concept of every pixel (the explanation map)
uncertainty (H, W) float32 in [0, 1], normalised entropy of the concept assignment

(with uncertainty=True), else None

K number of concepts, e.g. for ``np.bincount(exp.explanation.ravel(), minlength=exp.K)``

(H, W) int32 connected regions of the explanation map, like skimage.segmentation.slic.

(H, W) int32 mask (0 and 1) of the inner margin, width px wide, of every region.

Time series

Bases: _SequenceBase

NAVE explainer for time series.

Parameters:

Name Type Description Default
model a torch.nn.Module, an .onnx path, a function x (1, C, T) -> {layer: (C_b, t_b)}, or a

SequenceBackbone

required
layers the layers to combine (module names or the function's keys), shallowest first
required
k number of concepts per projector
10
multiple inputs are padded (mirrored) to a multiple of this length (the model's downsampling)
1
channels_last PyTorch transformer layers output (N, t, C): set True
False
transforms None, or a function (or list) applied to each (C, T) series (e.g. normalisation)
None
channel_names names of the channels, for `summarize`
None
window None (whole series) or a window length in steps (windows every half window, every

step from the window whose centre is nearest)

None
upsample "nearest" (default), "linear" or "cubic": deeper layers and scores to every step
'nearest'
Other
required
Attributes (after fitting)

prototypes, palette, classes, correlation, fitted : as in NAVEImage snippets : for each concept, a list of up to n (series, start, end, (C, L) values, offset): the segments closest to the prototype, with context profiles : (K, C, 40, 3) the 10th, 50th and 90th percentiles of the concept's segments, resampled to 40 points, per channel positions : (K, 12) histogram of where segments sit (relative position in the series) durations : (K, 2) median and mean segment length, in steps

Recompute snippets, profiles, positions and durations on series.

The figure for one series: one row per channel (the signal over the segmentation), an uncertainty row (if asked; inferno reversed: bright = certain, black = uncertain), a saliency row (if asked), the correlation of the concepts with the classes, and per concept: position & duration, snippets, profile (one band per channel), 10 concepts per row. span=(start, end) zooms on a part. label : the series' true class, shown with the model's prediction (when it predicts). saliency_range : (vmin, vmax) of the saliency colours (default (-1, 1): saliency is a cosine), or "auto": centred on 0, up to the item's largest |saliency|

Bases: SequenceExplanation

explanation (T,), uncertainty (T,) or None, K; segments() and border().

Text

Bases: _SequenceBase

NAVE explainer for text.

Parameters:

Name Type Description Default
model "spacy" (spaCy's tok2vec, needs `pip install "nave-xai[text]"`), a function

tokens -> {layer: (C_b, n_tokens), optional "logits"}, or a SequenceBackbone. For PyTorch or Hugging Face models, wrap the model in such a function (tokens to ids inside).

'spacy'
layers layers to combine, shallowest first (spaCy: default "block2", "block3", "block4")
None
k number of concepts per projector (20 by default: text needs more than images)
20
tokenizer function text -> tokens (spaCy's with model="spacy", else words and punctuation)
None
window None (whole document) or a window length in tokens
None
n_words characteristic words shown per concept
6
Other
required
Attributes (after fitting)

prototypes, palette, classes, correlation, fitted : as in NAVEImage span_counts : (K,) number of spans (runs of consecutive tokens) of each concept mean_runs : (K,) mean number of consecutive tokens with the concept words : for each concept, its characteristic words (frequency in the concept relative to overall) spans : for each concept, its closest spans to the prototype: (tokens with context, start, end)

Recompute span counts, mean runs, characteristic words and closest spans on texts.

The figure for one document: the text wrapped, each token on its concept's colour, the background's opacity = certainty; with saliency=True, the font size shows the saliency's magnitude and black / white its sign. Then the correlation of the concepts with the classes, and one row per concept: colour | spans and mean run | characteristic words | two closest spans in context. label : the document's true class, shown with the model's prediction (when it predicts). saliency_range : (vmin, vmax) of the saliency colours (default (-1, 1): saliency is a cosine), or "auto": centred on 0, up to the item's largest |saliency|

Bases: SequenceExplanation

tokens, explanation (n_tokens,) the concept of every token, uncertainty or None, K; segments() (runs of tokens with the same concept) and border().

Images (models)

Models

Built-in models, their blocks and the trainings with weights.

nave.models.available()["vits16"] {'blocks': 12, 'trainings': ('random', 'imagenet', 'dino'), 'default_blocks': [12]}

Download a built-in model's pretrained weights now, and return where they are.

nave-xai otherwise downloads them the first time a model needs them; call this ahead of time, for instance before working offline. They are kept in cache_dir() (NAVE_XAI_CACHE sets it).

from nave_xai import download_weights download_weights("vitt16", "imagenet") # ViT-Ti/16, about 11 MB, once

Base class. Subclasses set blocks (names, shallow to deep) and implement call.

Block names, shallowest first, from None, ints (1-based), names or paper notation.

{"weight": (classes, C), "bias": (classes,) or None} of the model's classifier, or None.

Deepest block features (C, h, w) as the classifier sees them (e.g. after a final norm).

Class scores for the image, or None when unknown. valid = (rows, cols) of the deepest grid that cover the image (the rest is padding).

Bases: Backbone

Wrap a torch.nn.Module.

Parameters:

Name Type Description Default
module the model (put in eval mode; gradients are not tracked)
required
mean input normalisation (default: ImageNet)
IMAGENET_MEAN
std input normalisation (default: ImageNet)
IMAGENET_MEAN
multiple input sides must be multiples of this (e.g. 32 for CNNs, the patch size for ViTs)
32
fixed_size (height, width) if the model only accepts one input size
None
patch_size for token outputs; default: found from the number of tokens
None
prefix_tokens class/register tokens before the patch tokens; default: found automatically
None
classifier classifier for saliency: a module name (e.g. "fc", "head"), a torch.nn.Linear,

or None to look for a Linear named fc / head / classifier

None
final_norm module name of the norm applied before the classifier (e.g. "norm"), if any
None
device (cpu, cuda, ...)
'cpu'

Bases: Backbone

Any ONNX model whose outputs are block feature maps (1, C, h, w).

Parameters:

Name Type Description Default
path the .onnx file; its first input takes the normalised image (1, 3, H, W)
required
blocks output names to use as blocks, shallow to deep (default: all outputs)
None
mean input normalisation (default: ImageNet)
IMAGENET_MEAN
std input normalisation (default: ImageNet)
IMAGENET_MEAN
multiple input sides must be multiples of this
32
fixed_size (height, width) if the model only accepts one size
None

Bases: Backbone

Wrap a function fn(x) -> {name: (1, C, h, w)} or a list of such arrays.

Use it for any framework (JAX, TensorFlow, ...): convert inside fn.

Sequence models

Bases: SequenceBackbone

Any function: fn(x) -> {name: (C, t) or (1, C, t) array, ..., optional "logits"}.

For series, x is a float32 (1, C, T) array; for text, a list of tokens.

Bases: SequenceBackbone

A PyTorch model. Layers are module names; their outputs are captured with forward hooks.

channels_last : False for convolutional layers ((N, C, t), default), True for transformer layers ((N, t, C)); prefix_tokens : leading tokens to drop (class tokens) The model's own output is used as class scores when it is 2D (N, classes).

Bases: SequenceBackbone

An ONNX file whose first input takes (1, C, T) and whose named outputs are (1, C_b, t_b).

Warnings

Bases: UserWarning

The run may need more memory than is currently free.