xai4tsc.models.base

ModelBase ABC: training, prediction, evaluation, checkpoint persistence.

Attributes

logger

t_con_defaults

Training hyperparameter defaults.

Classes

ModelBase

Base class for all time series classification models.

Functions

predict_probs(→ numpy.ndarray)

Return softmax class probabilities for data from any Module.

Module Contents

xai4tsc.models.base.logger
xai4tsc.models.base.t_con_defaults

Training hyperparameter defaults.

ModelBase.train_model() falls back to these per key, so a hyperparameter the caller omits behaves the same whether the pipeline is driven from a YAML config or from the package API. master.yaml documents them in comments and a test holds the two in step; it does not supply them.

xai4tsc.models.base.predict_probs(model: torch.nn.Module, data: numpy.ndarray | torch.Tensor) → numpy.ndarray

Return softmax class probabilities for data from any Module.

Models here emit raw logits from forward() by contract, so the softmax is applied on the way out. 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_classes).

  • data (np.ndarray or torch.Tensor) – Input samples, shape (n_samples, n_channels, n_timesteps).

Returns:

Probabilities of shape (n_samples, n_classes), rows summing to 1.

Return type:

np.ndarray

class xai4tsc.models.base.ModelBase

Bases: torch.nn.Module, abc.ABC

Base 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 in experiment configs.

Subclasses must implement forward(). All training, prediction, evaluation, and persistence logic is provided here and inherited.

The following instance attributes are set by the model factory (load_model()) after construction:

Example:

class MyCNN(ModelBase):
    def __init__(self, in_channels: int, num_classes: int):
        super().__init__()
        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 = None

Identifier used in file names and logs.

device: torch.device = None

Compute device the model lives on.

save_path: pathlib.Path = None

Directory for checkpoints and diagnostic plots.

model_path: pathlib.Path = None

Path to the best saved checkpoint (set after training).

best_epoch: int = None

Total epochs of training the best checkpoint represents (None if unknown).

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, hyperparams: dict, 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.

  • hyperparams (dict) – Training hyperparameters. Recognised keys: epochs, batchsize, learn_rate, patience, loss_func, optimizer, save_best.

  • data_val (np.ndarray, optional) – Validation data of shape (n_samples, n_channels, n_timesteps). When provided, validation loss drives early stopping and checkpointing.

  • labels_val (np.ndarray, optional) – Integer class labels for data_val.

  • save_path (str or Path, optional) – Directory for the best checkpoint and training plots. Takes priority over the destination set at construction time; falls back to that value and finally to the current working directory.

  • 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 by load_model()) and otherwise to 0. epochs is always the number of epochs to run in this call.

Returns:

self after training (best checkpoint restored).

Return type:

ModelBase

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.json in 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 .pt checkpoint.

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 .pt file for the state dict.

  • epoch (int, optional) – Total epochs of training these weights represent, recorded in the config file. Defaults to best_epoch.

classmethod load_from_checkpoint(model_path: pathlib.Path, device: str | torch.device = 'cpu', eval: bool = True, **init_params: object) → ModelBase

Instantiate the class and load weights from model_path.

Parameters:
  • model_path (Path) – Path to a .pt state-dict file produced by save_model().

  • device (str or torch.device) – Target device.

  • eval (bool) – Set the model to evaluation mode after loading.

  • **init_params – Keyword arguments forwarded to __init__.

Returns:

A new instance with loaded weights.

Return type:

ModelBase

evaluate_model(data: numpy.ndarray, labels: numpy.ndarray, hyperparams: dict, threshold: float = 0.5, save_path: pathlib.Path | 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. Saves ROC and confusion-matrix plots to save_path.

Parameters:
  • data (np.ndarray) – Test data.

  • labels (np.ndarray) – Integer ground-truth labels.

  • hyperparams (dict) – Used for batchsize.

  • 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 set at construction time; falls back to that value and finally to the current working directory.

Returns:

Metric values keyed by name.

Return type:

dict