experiment_runner.losses ======================== .. py:module:: experiment_runner.losses .. autoapi-nested-parse:: Loss lookup: the config string to a ``torch.nn`` loss object. The package takes the loss object itself (see :meth:`~xai4tsc.models.base.ModelBase.train_model`), so every ``nn.*Loss`` and every custom :class:`~torch.nn.Module` with a ``(logits, targets) -> scalar`` call works without a table entry. The table exists only because YAML cannot hold an object; see :mod:`experiment_runner.lookups` for the shared mechanics. Attributes ---------- .. autoapisummary:: experiment_runner.losses.logger experiment_runner.losses.LOSSES Functions --------- .. autoapisummary:: experiment_runner.losses.build_loss experiment_runner.losses.as_tensors Module Contents --------------- .. py:data:: logger .. py:data:: LOSSES :type: dict[str, type[torch.nn.Module]] Config name -> loss class. Anything else resolves by dotted path. .. py:function:: build_loss(name: str | None, params: dict | None = None) -> torch.nn.Module | None Return the loss object for the config value *name*. :param name: A key of :data:`LOSSES` (matched case-insensitively, since configs spell it ``"CrossEntropy"``), or a dotted import path to a loss class. ``None`` returns ``None``, which leaves :meth:`~xai4tsc.models.base.ModelBase.train_model` on its own default so the default lives in one place. :type name: str or None :param params: Constructor arguments, e.g. ``{"weight": [1.0, 3.0, 1.0]}``. List values become ``float32`` tensors - see :func:`as_tensors`. :type params: dict, optional :returns: The constructed loss, or ``None`` when no name was given. :rtype: torch.nn.Module or None :raises ValueError: If *name* resolves to nothing, if construction fails, or if *params* were given without a *name* to apply them to. .. py:function:: as_tensors(params: dict) -> dict Return *params* with every list value converted to a ``float32`` tensor. The tensor-valued arguments of the torch loss family - ``weight`` for :class:`~torch.nn.CrossEntropyLoss` and :class:`~torch.nn.NLLLoss`, ``weight`` and ``pos_weight`` for :class:`~torch.nn.BCEWithLogitsLoss` - are registered buffers, and a list cannot be assigned to one: the constructor raises ``cannot assign 'list' object to buffer 'weight'``. YAML has no tensor, so the conversion happens here. ``float32`` specifically, because a ``float64`` weight makes the loss raise ``expected scalar type Float but found Double`` at the first call. :param params: Constructor arguments as they came from YAML. :type params: dict :returns: The same mapping with list and tuple values as tensors. :rtype: dict