xai4tsc.models.base
ModelBase ABC: training, prediction, evaluation, checkpoint persistence.
Attributes
The output activations |
Classes
Base class for all time series classification models. |
Functions
|
Validate an output-activation name, returning it unchanged. |
|
Return class probabilities for data from any |
Module Contents
- xai4tsc.models.base.logger
- xai4tsc.models.base.OUTPUT_ACTIVATIONS = ('softmax', 'sigmoid')
The output activations
predict_probs()knows how to apply."softmax"is the single-label default: the outputs compete and a row sums to 1."sigmoid"is the multi-label one: each output is an independent probability and a row does not sum to anything in particular.
- xai4tsc.models.base.check_output_activation(name: str) str
Validate an output-activation name, returning it unchanged.
Called from a model’s constructor rather than from
predict_probs(), so a typo fails when the model is built instead of silently changing every probability the model ever reports.- Parameters:
name (str) – A member of
OUTPUT_ACTIVATIONS.- Returns:
name.
- Return type:
str
- Raises:
ValueError – If name is not a known activation.
- xai4tsc.models.base.predict_probs(model: torch.nn.Module, data: numpy.ndarray | torch.Tensor) numpy.ndarray
Return class probabilities for data from any
Module.Models here emit raw logits from
forward()by contract, so the activation is applied on the way out. Which one comes from the model itself -model.output_activation, defaulting to"softmax"when a module does not declare one, which keeps the “anynn.Module” contract intact.That default is why the attribute belongs on the model’s constructor: it is persisted in the checkpoint’s
init_params, so a reloaded multi-label model still reports independent per-label probabilities. Were it a training argument instead, nothing in the checkpoint would record it and a softmax would be applied to sigmoid outputs with no sign that anything was wrong.The model’s train/eval mode is left untouched and belongs to the caller.
- Parameters:
model (torch.nn.Module) – Model to run. Must return logits of shape
(n_samples, n_outputs).data (np.ndarray or torch.Tensor) – Input samples, shape
(n_samples, n_channels, n_timesteps).
- Returns:
Probabilities of shape
(n_samples, n_outputs). Rows sum to 1 under"softmax"; under"sigmoid"each column is independent.- Return type:
np.ndarray
- class xai4tsc.models.base.ModelBase
Bases:
torch.nn.Module,abc.ABCBase class for all time series classification models.
Subclass this to add a custom model to xai4tsc. Register the subclass with
xai4tsc.register_model()to make it available by name.Subclasses must implement
forward(). All training, prediction, evaluation, and persistence logic is provided here and inherited.namedefaults to the subclass name, so a model constructed directly still names its own files.deviceandsave_pathdescribe the machine and the run rather than the model, so they are not constructor arguments; set them withconfigure(), whichload_model()calls on the caller’s behalf. Until thensave_pathisNoneand the methods that write refuse to guess a destination.A subclass records its own constructor arguments by calling
_record_init_params()withlocals()as its first statement, which is what lets a checkpoint describe how to rebuild the model.Example:
class MyCNN(ModelBase): def __init__(self, in_channels: int, num_classes: int): super().__init__() self._record_init_params(locals()) self.conv = nn.Conv1d(in_channels, 32, kernel_size=3, padding=1) self.fc = nn.Linear(32, num_classes) def forward(self, x): return self.fc(self.conv(x).mean(-1)) xai4tsc.register_model("my_cnn", MyCNN)
- name: str
Identifier used in file names and logs. Defaults to the class name.
- device: torch.device | None = None
Compute device the model lives on.
- save_path: pathlib.Path | None = None
it is resolved when set, so it does not move with the working directory.
- Type:
Directory for checkpoints and diagnostic plots. Always absolute
- model_path: pathlib.Path | None = None
Path to the best saved checkpoint (set after training).
- best_epoch: int | None = None
Total epochs of training the best checkpoint represents (
Noneif unknown).
- configure(device: str | torch.device | None = None, save_path: pathlib.Path | str | None = None, name: str | None = None) ModelBase
Set where this model runs and where it writes, and return it.
These are properties of the machine and the run, not of the architecture, which is why they are set here rather than passed to the constructor.
load_model()calls this after building a model; call it yourself when constructing one directly:model = FCN(in_channels=1, num_classes=2).configure( device="cpu", save_path="results/run_1" )
- Parameters:
device (str or torch.device, optional) – Compute device. The model is moved onto it.
save_path (Path or str, optional) – Directory for checkpoints and diagnostic plots. Resolved to an absolute path.
name (str, optional) – Identifier used in file names and logs. Overrides the default class name, which is how one class registered under two keys writes distinguishable files.
- Returns:
self, so the call can be chained onto the constructor.- Return type:
Notes
An omitted argument leaves the current value alone, so a later call that sets only one attribute does not clear the others.
- abstractmethod forward(x: torch.Tensor) torch.Tensor
Forward pass.
- Parameters:
x (torch.Tensor) – Input tensor of shape
(B, C, T).- Returns:
Logits of shape
(B, num_classes).- Return type:
torch.Tensor
- count_params() int
Return the number of trainable parameters.
- predict(data: numpy.ndarray, labels: numpy.ndarray = None) tuple
Run inference on a numpy array.
- Parameters:
data (np.ndarray) – Shape
(n_samples, n_channels, n_timesteps).labels (np.ndarray, optional) – Ground-truth labels for accuracy logging.
- Returns:
(out_classes, out_probs)— both numpy arrays.- Return type:
tuple[np.ndarray, np.ndarray]
- train_model(data_train: numpy.ndarray, labels_train: numpy.ndarray, epochs: int = 20, batchsize: int = 8, learn_rate: float = 0.001, patience: int = 3, min_delta: float = 0.005, save_best: bool = True, loss_func: torch.nn.Module | None = None, optimizer: collections.abc.Callable[..., torch.optim.Optimizer] | torch.optim.Optimizer | None = None, data_val: numpy.ndarray | None = None, labels_val: numpy.ndarray | None = None, save_path: pathlib.Path | str | None = None, start_epoch: int | None = None) ModelBase
Run the full training loop with early stopping.
Early stopping and best-checkpoint selection monitor validation loss when data_val/labels_val are supplied, and fall back to training loss otherwise. Monitoring validation loss is the correct way to avoid selecting an overfit model.
- Parameters:
data_train (np.ndarray) – Training data of shape
(n_samples, n_channels, n_timesteps).labels_train (np.ndarray) – Integer class labels.
epochs (int) – Number of epochs to run in this call, 20 by default. A run resuming from a checkpoint continues its epoch count.
batchsize (int) – Samples per batch, 8 by default.
learn_rate (float) – Optimizer learning rate,
1e-3by default.patience (int) – Epochs without improvement before early stopping, 3 by default.
min_delta (float) – How far the monitored loss has to fall below its best value to count as an improvement,
5e-3by default. An absolute difference, not a fraction of the loss; the sign is ignored, so-5e-3means the same.save_best (bool) – Whether to write a checkpoint whenever the monitored loss improves,
Trueby default.loss_func (torch.nn.Module, optional) – The loss, as an object: any module whose call is
(logits, targets) -> scalar tensor, with its own arguments already applied (nn.CrossEntropyLoss(weight=w),nn.BCEWithLogitsLoss(pos_weight=w), or a custom module). It is moved to this model’s device, so a weight built on the CPU travels with it.None(default) usesCrossEntropyLoss. Losses needing more than the final logits - contrastive, triplet, distillation - are out of scope: the contract is the two-argument call above.optimizer (callable or torch.optim.Optimizer, optional) – The optimizer, in one of three forms. A class (
torch.optim.AdamW) or any callable returning an optimizer (afunctools.partial()carrying constructor arguments) is called asoptimizer(self.parameters(), lr=learn_rate). An instance built over specific parameter groups is used as given, and learn_rate then does not apply, which is reported rather than silently ignored.None(default) usesAdam.data_val (np.ndarray, optional) – Validation data of shape
(n_samples, n_channels, n_timesteps). When provided, validation loss drives early stopping and checkpointing; when omitted, both monitor training loss instead. Must be given together with labels_val: one without the other raises, rather than falling back to training loss as if nothing had been asked for.labels_val (np.ndarray, optional) – Integer class labels for data_val. Required when data_val is given.
save_path (str or Path, optional) – Directory for the best checkpoint and training plots. Takes priority over the destination given to
load_model(), and falls back to it. Raises if neither is set.start_epoch (int, optional) – Epochs of training the weights have already had, used to continue epoch numbering when resuming from a checkpoint. Defaults to
best_epoch(set byload_model()) and otherwise to0.epochsis always the number of epochs to run in this call.
- Returns:
selfafter training (best checkpoint restored).- Return type:
- static config_path_for(checkpoint_path: pathlib.Path | str) pathlib.Path
Return the config file path belonging to checkpoint_path.
The config file is named after its checkpoint with
_config.jsonin place of the suffix, e.g.FCN_epoch_10.pt->FCN_epoch_10_config.json, so the two are unambiguously paired.- Parameters:
checkpoint_path (Path or str) – Path to a
.ptcheckpoint.- Returns:
Path to the matching config file, in the same directory.
- Return type:
Path
- save_model(save_path: pathlib.Path | str, epoch: int | None = None) None
Save the model state dict to save_path, with its config file beside it.
- Parameters:
save_path (Path or str) – Destination
.ptfile for the state dict.epoch (int, optional) – Total epochs of training these weights represent, recorded in the config file. Defaults to
best_epoch.
- property epoch_label: int
Epochs of training behind the weights being scored, for file names.
best_epochisNonefor a model this process never trained and whose checkpoint recorded no epoch, which as a file name reads_eNone_. The result files, figures and log lines written here use this instead, where that case is0. A caller tabulating results wantsbest_epochitself, which can say “no epoch is known” without asserting the weights are untrained.- Returns:
best_epoch, or0when it is not set.- Return type:
int
- evaluate_model(data: numpy.ndarray, labels: numpy.ndarray, batchsize: int = 8, threshold: float = 0.5, save_path: pathlib.Path | str | None = None, class_names: collections.abc.Sequence[str] | None = None) dict
Evaluate on test data and return a metrics dict.
Computes accuracy for all tasks and additionally sensitivity, specificity, PPV, NPV, and AUC for binary classification, where
pos/negare the class balance. For more than two classes those two would be the counts of class indices 1 and 0, so they are omitted and macro-averaged rates reported instead. Either way the one-vs-rest confusion counts of every class, and every rate derived from them - that class’s own accuracy included - are written to a*_test_per_class.csvbeside the summary, which holds only the aggregate. Saves ROC and confusion-matrix plots to save_path.The summary’s columns depend on the formulation, not on the test split: a split with one class present reports a nan AUC and keeps every other column, so two runs of the same problem type return the same keys.
A 2-D labels array is one column per model output, i.e. a multi-label problem, and is dispatched to
_evaluate_multi_label(): there is no single class per sample to take an argmax of, so it reports subset and bit accuracy, the Hamming loss and the macro AUC over the outputs, and draws a 2x2 panel per output in place of a K-by-K matrix. Its per-output table has the same columns as the per-class one. The formulation picks that branch rather than the output width, so a two-label problem is not mistaken for a binary one.- Parameters:
data (np.ndarray) – Test data.
labels (np.ndarray) – Integer ground-truth labels: 1-D class indices, or a 2-D multi-hot array with one column per model output.
batchsize (int) – Samples per batch, 8 by default.
threshold (float) – Decision threshold for binary classification.
save_path (Path or str, optional) – Directory for the ROC and confusion-matrix plots. Takes priority over the destination given to
load_model(), and falls back to it. Raises if neither is set.class_names (sequence of str, optional) – One display name per class index, as
class_names()returns them, used to label the plots and the per-class results. Classes are named by index when this is not given.
- Returns:
Metric values keyed by name. The summary only; the per-class counts are written to file.
- Return type:
dict