Skip to content

Domain modules

One entry point per kind of data, each a subclass of Interpreter that only sets defaults and handles the inputs. The modules load on first access (fa.tabular, fa.image, fa.text, fa.tree), so import fannar stays light.

fannar.tabular

TabularInterpreter

TabularInterpreter(
    model,
    X,
    y=None,
    *,
    layers: Sequence[str] | None = None,
    feature_names: Sequence[str] | None = None,
    class_names: Sequence[str] | None = None,
    **kwargs,
)

Bases: Interpreter

Interpreter for a PyTorch model over tabular rows.

Parameters:

Name Type Description Default
model

A trained PyTorch classifier returning logits (N, K).

required
X

Rows to interpret: a (n, F) array, tensor or pandas.DataFrame (its columns become the feature names).

required
y

True labels: integers 0 .. K-1 in the model's output order, or a categorical/string pandas.Series or array (encoded as described in encode_labels; its order must be the one used to train the model).

None
layers Sequence[str] | None

Module names to probe, as in model.named_modules(); None probes every direct child with parameters.

None
**kwargs

Everything else is passed to Interpreter (reference_model, pipeline, baselines, k) and from it to TorchSources (target, fixed_class, device, batch_size...).

{}
Source code in src\fannar\tabular.py
def __init__(self, model, X, y=None, *, layers: Sequence[str] | None = None,
             feature_names: Sequence[str] | None = None, class_names: Sequence[str] | None = None,
             **kwargs) -> None:
    require_torch("fannar.tabular")
    X, y, feature_names, class_names = as_table(X, y, feature_names, class_names)
    super().__init__(model, X, y, layers=layers, feature_names=feature_names, class_names=class_names,
                     **kwargs)

as_table

as_table(
    X,
    y=None,
    feature_names: Sequence[str] | None = None,
    class_names: Sequence[str] | None = None,
    classes: Sequence | None = None,
    dtype=float32,
)

(X, y, feature_names, class_names) from arrays or pandas objects.

Explicit feature_names/class_names take precedence over what the DataFrame and the labels provide. X becomes a dtype array (float32 by default, the usual dtype of a model).

Source code in src\fannar\tabular.py
def as_table(X, y=None, feature_names: Sequence[str] | None = None, class_names: Sequence[str] | None = None,
             classes: Sequence | None = None, dtype=np.float32):
    """``(X, y, feature_names, class_names)`` from arrays or pandas objects.

    Explicit ``feature_names``/``class_names`` take precedence over what the DataFrame and the labels
    provide. ``X`` becomes a ``dtype`` array (``float32`` by default, the usual dtype of a model).
    """
    if hasattr(X, "columns") and feature_names is None:
        feature_names = [str(c) for c in X.columns]
    if hasattr(X, "to_numpy"):
        X = X.to_numpy()
    if not hasattr(X, "detach"):  # leave tensors to the model's own dtype handling
        X = np.asarray(X, dtype=dtype)
    y, names = encode_labels(y, classes)
    return X, y, feature_names, class_names if class_names is not None else names

encode_labels

encode_labels(
    y, classes: Sequence | None = None
) -> tuple[ndarray | None, list[str] | None]

y as class indices 0 .. K-1 plus the class names, when y is not already numeric.

A pandas categorical keeps its category order. Strings, objects and booleans are matched against classes when given (e.g. tree.classes_), otherwise against their sorted unique values, the same order as scikit-learn's LabelEncoder. Numeric labels are returned unchanged with no names.

Source code in src\fannar\tabular.py
def encode_labels(y, classes: Sequence | None = None) -> tuple[np.ndarray | None, list[str] | None]:
    """``y`` as class indices ``0 .. K-1`` plus the class names, when ``y`` is not already numeric.

    A pandas categorical keeps its category order. Strings, objects and booleans are matched against
    ``classes`` when given (e.g. ``tree.classes_``), otherwise against their sorted unique values, the
    same order as scikit-learn's ``LabelEncoder``. Numeric labels are returned unchanged with no names.
    """
    if y is None:
        return None, None
    cat = getattr(y, "cat", None)
    if cat is not None and str(getattr(y, "dtype", "")) == "category":
        return np.asarray(cat.codes, dtype=np.int64), [str(c) for c in cat.categories]
    y = np.asarray(y)
    if classes is not None:
        classes = np.asarray(classes)
        if np.issubdtype(classes.dtype, np.integer) and np.array_equal(classes, np.arange(len(classes))):
            return y, None
        index = {c: t for t, c in enumerate(classes.tolist())}
        unknown = sorted({str(c) for c in y.tolist() if c not in index})
        if unknown:
            raise ValueError(f"labels {unknown[:5]} are not among the model's classes {classes.tolist()}")
        return np.array([index[c] for c in y.tolist()], dtype=np.int64), [str(c) for c in classes]
    if np.issubdtype(y.dtype, np.number):
        return y, None
    names, codes = np.unique(y, return_inverse=True)
    return codes.astype(np.int64), [str(c) for c in names]

fannar.image

ImageInterpreter

ImageInterpreter(
    model,
    X,
    y=None,
    *,
    layers: Sequence[str] | None = None,
    grid: int | None = 4,
    class_names: Sequence[str] | None = None,
    **kwargs,
)

Bases: Interpreter

Interpreter for PyTorch image classifiers.

Parameters:

Name Type Description Default
model

A trained PyTorch classifier returning logits (N, K).

required
X

Images (n, C, H, W) as an array or tensor, or a DataLoader.

required
y

True labels (integers 0 .. K-1).

None
layers Sequence[str] | None

Module names to probe, as in model.named_modules().

None
grid int | None

Positions kept per spatial axis when pooling each probed output (None keeps all of them, which makes the sources much larger).

4
class_names Sequence[str] | None

Names of the classes, used by the plots and the error explanations.

None
**kwargs

Passed to Interpreter (reference_model, pipeline, baselines, k) and from it to TorchSources (target, fixed_class, device, batch_size...).

{}
Source code in src\fannar\image.py
def __init__(self, model, X, y=None, *, layers: Sequence[str] | None = None, grid: int | None = 4,
             class_names: Sequence[str] | None = None, **kwargs) -> None:
    require_torch("fannar.image")
    kwargs.setdefault("layout", "channels")
    super().__init__(model, X, y, layers=layers, class_names=class_names, grid=grid, **kwargs)

fannar.text

TextInterpreter

TextInterpreter(
    model,
    X,
    y=None,
    *,
    layers: Sequence[str] | None = None,
    grid: int | None = 8,
    **kwargs,
)

Bases: Interpreter

Interpreter for PyTorch models over token sequences.

Parameters:

Name Type Description Default
model

A trained PyTorch classifier taking one tensor (e.g. token ids (N, L)) and returning logits (N, K). Wrap a Hugging Face model with wrap_hf first.

required
X

The sequences: an array or tensor of token ids (or embeddings), or a DataLoader.

required
y

True labels (integers 0 .. K-1).

None
layers Sequence[str] | None

Module names to probe; None uses block_names.

None
grid int | None

Positions kept along the sequence when pooling each hidden state (None keeps every token, which requires sequences of the same length).

8
**kwargs

Passed to Interpreter (reference_model, pipeline, baselines, class_names, k) and from it to TorchSources (target, fixed_class, device, batch_size, weight_modules...).

{}
Source code in src\fannar\text.py
def __init__(self, model, X, y=None, *, layers: Sequence[str] | None = None, grid: int | None = 8,
             **kwargs) -> None:
    _need_torch()
    if layers is None:
        layers = block_names(model)
    kwargs.setdefault("layout", "tokens")
    super().__init__(model, X, y, layers=layers, grid=grid, **kwargs)

wrap_hf

wrap_hf(model, pad_token_id: int | None = None, **forward_kwargs)

Wraps a Hugging Face sequence classifier (or anything called as model(input_ids=...)) into an HFClassifier whose forward(input_ids) returns the logits.

Extra keyword arguments are passed to every call of the wrapped model.

Source code in src\fannar\text.py
def wrap_hf(model, pad_token_id: int | None = None, **forward_kwargs):
    """Wraps a Hugging Face sequence classifier (or anything called as ``model(input_ids=...)``)
    into an :class:`HFClassifier` whose ``forward(input_ids)`` returns the logits.

    Extra keyword arguments are passed to every call of the wrapped model.
    """
    _need_torch()
    return HFClassifier(model, pad_token_id, **forward_kwargs)

HFClassifier

HFClassifier(model: Module, pad_token_id: int | None = None, **forward_kwargs)

Bases: Module

A classifier taking one tensor of token ids and returning its logits (N, K).

The wrapped model is stored as self.model, so the probed layer names gain the prefix model. (model.bert.encoder.layer.0...). With pad_token_id the attention mask is input_ids != pad_token_id; otherwise every token is attended to.

Source code in src\fannar\text.py
def __init__(self, model: nn.Module, pad_token_id: int | None = None, **forward_kwargs) -> None:
    super().__init__()
    self.model = model
    self.pad_token_id = pad_token_id
    self.forward_kwargs = forward_kwargs

block_names

block_names(model) -> list[str]

Names of the children of the longest nn.ModuleList in model: the transformer blocks.

Raises ValueError when the model has no nn.ModuleList; pass layers= explicitly then.

Source code in src\fannar\text.py
def block_names(model) -> list[str]:
    """Names of the children of the longest ``nn.ModuleList`` in ``model``: the transformer blocks.

    Raises ``ValueError`` when the model has no ``nn.ModuleList``; pass ``layers=`` explicitly then.
    """
    _need_torch()
    lists = [(name, m) for name, m in model.named_modules() if isinstance(m, nn.ModuleList) and len(m)]
    if not lists:
        raise ValueError("no nn.ModuleList found in the model; pass `layers=` explicitly")
    name, blocks = max(lists, key=lambda item: len(item[1]))  # first of the longest, in module order
    return [f"{name}.{t}" if name else str(t) for t in range(len(blocks))]

fannar.tree

TreeInterpreter

TreeInterpreter(
    tree,
    X,
    y=None,
    *,
    X_train=None,
    scale=None,
    depths: Sequence[int] | None = None,
    feature_names: Sequence[str] | None = None,
    class_names: Sequence[str] | None = None,
    **kwargs,
)

Bases: Interpreter

Interpreter for a fitted scikit-learn decision tree classifier.

Parameters:

Name Type Description Default
tree

A fitted DecisionTreeClassifier (anything with tree_, decision_path and predict_proba).

required
X

Rows to interpret: a (n, F) array or a pandas.DataFrame (its columns become the feature names).

required
y

True labels, with the same values the tree was trained on (tree.classes_).

None
X_train

Optional training rows. Their per-feature standard deviation becomes the scale of the slack source, so distances to the thresholds are comparable across features.

None
scale

An explicit per-feature scale for the slack (overrides X_train).

None
depths Sequence[int] | None

Depths used as layers (default 1 .. max_depth).

None
**kwargs

Passed to Interpreter (pipeline, baselines, reference_model, k).

{}
Source code in src\fannar\tree.py
def __init__(self, tree, X, y=None, *, X_train=None, scale=None, depths: Sequence[int] | None = None,
             feature_names: Sequence[str] | None = None, class_names: Sequence[str] | None = None,
             **kwargs) -> None:
    classes = getattr(tree, "classes_", None)
    X, y, feature_names, class_names = as_table(X, y, feature_names, class_names, classes=classes,
                                                dtype=np.float64)
    if class_names is None and classes is not None and y is not None and not np.array_equal(
            np.asarray(classes), np.arange(len(classes))):
        class_names = [str(c) for c in classes]
    if scale is None and X_train is not None:
        Xt = np.asarray(X_train.to_numpy() if hasattr(X_train, "to_numpy") else X_train, dtype=np.float64)
        scale = np.where(Xt.std(0) > 0, Xt.std(0), 1.0)
    reference = kwargs.pop("reference_model", None)
    extractor = _IndexedTreeSources(tree, scale=scale, depths=depths)
    super().__init__(tree, X, y, extractor=extractor, feature_names=feature_names,
                     class_names=class_names, **kwargs)
    if reference is not None:  # another tree (e.g. a shallower or randomised one) as the floor
        self.reference_extractor = _IndexedTreeSources(reference, scale=scale, depths=depths)