xai4tsc.xai.explain
generate_explanation() entry point, EXPLAINERS registry, plot helpers.
Attributes
Functions
|
Generate an explanation for the given indices or for random samples. |
|
Render and save relevance plots for every sample in exp. |
|
Instantiate a registered explainer, filtering params to its |
|
Register a custom |
Module Contents
- xai4tsc.xai.explain.logger
- xai4tsc.xai.explain.generate_explanation(method: str, model: xai4tsc.models.base.ModelBase, data: numpy.ndarray, labels: numpy.ndarray | None = None, targets: str = 'predicted', params: dict | None = None, call_params: dict | None = None, encoder: object | None = None, indices: list | None = None, n_samples: int = 5, prng: numpy.random.Generator | None = None, device: str = 'cpu', save_path: pathlib.Path | str | None = None, visualization_type: collections.abc.Sequence[str] = ('points',), data_domain: str | xai4tsc.xai._types.Domain = Domain.TIME, threshold: float = 0.5) xai4tsc.xai._types.Explanation | None
Generate an explanation for the given indices or for random samples.
Set indices to an empty list or
Noneto choose random samples.- Parameters:
method (str) – Explanation method to use, as keyed in
EXPLAINERS.model (ModelBase) – Model to explain.
data (np.ndarray) – Dataset to generate an explanation for.
labels (np.ndarray, optional) – Labels of the dataset, by default None. Required for
targets="label". Without them a per-output (multi-label) model is recognised by itsoutput_activation="sigmoid".targets (str, optional) – Which class to explain:
"predicted"(default),"label"(ground truth), or"all"(one explanation per class). Under a per-output (2-D) label encoding all three stack one attribution per output;"label"and"predicted"then setExplanation.target_maskto say which of them apply per sample.threshold (float, optional) – Decision threshold on a per-output probability, 0.5 by default. Only read for a per-output (multi-label) encoding with
targets="predicted", where it decides which outputs each sample is explained for.params (dict, optional) – Parameters for the explanation method, by default None
call_params (dict, optional) – Per-call options given into the explainer’s
explain()as keyword arguments, by default None. Construction options go in params; use this for options an explainer takes per call. Recorded on the returned explanation so the re-explaining metrics replay the same call.encoder (object, optional) – Fitted label encoder, used to name the explained classes.
Noneby default, in which case classes are named by index and the class count is the model’s output width.indices (list, optional) – Indices of samples to explain, by default None
n_samples (int, optional) – Number of random samples to explain if no indices supplied, by default 5
prng (np.random.Generator, optional) – Generator used to pick random sample indices. When
Nonea generator seeded withDEFAULT_SEEDis used, so the selection is reproducible. Pass one generator to several explainers to have them all explain the same samples.device (str, optional) – Device to calculate on, by default
"cpu".save_path (Path | str, optional) – Path to save the explanation visualisation to, by default None
visualization_type (Sequence[str], optional) – Plot styles to render when saving, by default
("points",).data_domain (str or Domain, optional) – Signal domain data is expressed in, i.e. the domain the model consumes (
"time"by default; seexai4tsc.data.DatasetBase.data_domain). A plain attributor explains in this domain; a domain-changing explainer is refused on data it cannot transform from.
- Returns:
An object of the Explanation dataclass.
- Return type:
Explanation
- xai4tsc.xai.explain.plot_exp(exp: xai4tsc.xai._types.Explanation, norm: bool = True, save_path: pathlib.Path | str | None = None, visualization_type: collections.abc.Sequence[str] = ('points',)) None
Render and save relevance plots for every sample in exp.
Plots are written flat under save_path, one file per sample (and, for
targets="all"explanations, per class), namedrelevance_index_<idx>_class_<name>...so samples sharing a directory do not overwrite one another.<name>is the class the attribution explains (exp.explained_targets, falling back toexp.labels), spelled asclass_names()spells it - so a multi-hot class reads0-0-1rather than[0 0 1], which is not a usable filename - and then reduced to filesystem-safe characters.The renderer is chosen by
exp.explanation_domain: time-domain explanations use the 1-Dplot_relevance()overlay styles; frequency and time-frequency explanations useplot_relevance_f()andplot_relevance_tf()respectively. Frequency and time-frequency explanations plot against the transformed signal, derived on demand viaexp.transform.- Parameters:
exp (Explanation) – The explanation to render. Multi-target (“all”) explanations are detected via
is_multi_target()(domain-aware), so a single-target time-frequency explanation is not mistaken for a multi-target one.norm (bool, optional) – Whether to normalize explanation values, by default True.
save_path (Path | str | None, optional) – Directory to save the plots to, by default None.
visualization_type (Sequence[str], optional) – Overlay styles for time / frequency plots: any of
"points"(default),"background","intensity","graph", or"bar". Ignored for time-frequency, which renders a single fixed heatmap view.
- Raises:
ValueError – If exp is a frequency / time-frequency explanation but carries no
exp.transformto derive the transformed signal from.
- xai4tsc.xai.explain.EXPLAINERS
- xai4tsc.xai.explain.build_explainer(method: str, params: dict | None) xai4tsc.xai.base.ExplainerBase
Instantiate a registered explainer, filtering params to its
__init__.Shared by
_get_explanation()and by wrapper explainers (WrapperExplainer), so a wrapped base method is built exactly as a top-level one is.- Parameters:
method (str) – Explainer name; looked up case-insensitively in
EXPLAINERS.params (dict or None) – Parameters to pass to the explainer’s
__init__. Keys not matching the constructor signature are dropped viadict_to_args(). If the class defines no__init__, no parameters are passed.
- Returns:
A ready-to-use explainer instance.
- Return type:
- Raises:
NotImplementedError – If method is not registered in
EXPLAINERS.
- xai4tsc.xai.explain.register_explainer(name: str, explainer_class: type) None
Register a custom
ExplainerBasesubclass.After registration the explainer is available by name to
_get_explanation()and to anything else resolvingEXPLAINERS.- Parameters:
name – Key used to look up the explainer (case-insensitive).
explainer_class – A concrete subclass of
ExplainerBase(or one of its mid-level subclasses).
- Raises:
TypeError – If explainer_class is not an
ExplainerBasesubclass.