xai4tsc.models.base

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

Attributes

logger

Classes

ModelBase

Base class for all time series classification models.

Module Contents

xai4tsc.models.base.logger
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

Epoch number of the best checkpoint (set after training).

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) 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.

Returns:

self after training (best checkpoint restored).

Return type:

ModelBase

save_model(save_path: pathlib.Path | str) None

Save the model state dict to save_path.

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