xai4tsc.models.base =================== .. py:module:: xai4tsc.models.base .. autoapi-nested-parse:: ``ModelBase`` ABC: training, prediction, evaluation, checkpoint persistence. Attributes ---------- .. autoapisummary:: xai4tsc.models.base.logger Classes ------- .. autoapisummary:: xai4tsc.models.base.ModelBase Module Contents --------------- .. py:data:: logger .. py:class:: ModelBase Bases: :py:obj:`torch.nn.Module`, :py:obj:`abc.ABC` Base class for all time series classification models. Subclass this to add a custom model to xai4tsc. Register the subclass with :func:`xai4tsc.register_model` to make it available by name in experiment configs. Subclasses must implement :meth:`forward`. All training, prediction, evaluation, and persistence logic is provided here and inherited. The following instance attributes are set by the model factory (:func:`~xai4tsc.models.models.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) .. py:attribute:: name :type: str :value: None Identifier used in file names and logs. .. py:attribute:: device :type: torch.device :value: None Compute device the model lives on. .. py:attribute:: save_path :type: pathlib.Path :value: None Directory for checkpoints and diagnostic plots. .. py:attribute:: model_path :type: pathlib.Path :value: None Path to the best saved checkpoint (set after training). .. py:attribute:: best_epoch :type: int :value: None Epoch number of the best checkpoint (set after training). .. py:method:: forward(x: torch.Tensor) -> torch.Tensor :abstractmethod: Forward pass. :param x: Input tensor of shape ``(B, C, T)``. :type x: torch.Tensor :returns: Logits of shape ``(B, num_classes)``. :rtype: torch.Tensor .. py:method:: count_params() -> int Return the number of trainable parameters. .. py:method:: predict(data: numpy.ndarray, labels: numpy.ndarray = None) -> tuple Run inference on a numpy array. :param data: Shape ``(n_samples, n_channels, n_timesteps)``. :type data: np.ndarray :param labels: Ground-truth labels for accuracy logging. :type labels: np.ndarray, optional :returns: ``(out_classes, out_probs)`` — both numpy arrays. :rtype: tuple[np.ndarray, np.ndarray] .. py:method:: 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. :param data_train: Training data of shape ``(n_samples, n_channels, n_timesteps)``. :type data_train: np.ndarray :param labels_train: Integer class labels. :type labels_train: np.ndarray :param hyperparams: Training hyperparameters. Recognised keys: ``epochs``, ``batchsize``, ``learn_rate``, ``patience``, ``loss_func``, ``optimizer``, ``save_best``. :type hyperparams: dict :param data_val: Validation data of shape ``(n_samples, n_channels, n_timesteps)``. When provided, validation loss drives early stopping and checkpointing. :type data_val: np.ndarray, optional :param labels_val: Integer class labels for *data_val*. :type labels_val: np.ndarray, optional :param save_path: 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. :type save_path: str or Path, optional :returns: ``self`` after training (best checkpoint restored). :rtype: ModelBase .. py:method:: save_model(save_path: pathlib.Path | str) -> None Save the model state dict to *save_path*. .. py:method:: load_from_checkpoint(model_path: pathlib.Path, device: str | torch.device = 'cpu', eval: bool = True, **init_params: object) -> ModelBase :classmethod: Instantiate the class and load weights from *model_path*. :param model_path: Path to a ``.pt`` state-dict file produced by :meth:`save_model`. :type model_path: Path :param device: Target device. :type device: str or torch.device :param eval: Set the model to evaluation mode after loading. :type eval: bool :param \*\*init_params: Keyword arguments forwarded to ``__init__``. :returns: A new instance with loaded weights. :rtype: ModelBase .. py:method:: 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*. :param data: Test data. :type data: np.ndarray :param labels: Integer ground-truth labels. :type labels: np.ndarray :param hyperparams: Used for ``batchsize``. :type hyperparams: dict :param threshold: Decision threshold for binary classification. :type threshold: float :param save_path: 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. :type save_path: Path or str, optional :returns: Metric values keyed by name. :rtype: dict