Custom loss functions


source

CustomLoss


def CustomLoss(
    loss_func
):

A custom loss wrapper class for loss functions to allow them to work with the ‘show_results’ method in fastai.


source

TverskyFocalLoss


def TverskyFocalLoss(
    include_background:bool=True, to_onehot_y:bool=False, sigmoid:bool=False, softmax:bool=False, gamma:float=2,
    alpha:float=0.5, beta:float=0.99
):

Focal Tversky loss: (1 - TI)**gamma (TI = Tversky index; see monai.losses.TverskyLoss). gamma=1 reduces to the plain Tversky loss.

DynUNet deep-supervision adapter


source

DynUNetDSAdapter


def DynUNetDSAdapter(
    model
):

Wrap a MONAI DynUNet with deep supervision so its output matches what monai.losses.DeepSupervisionLoss (used via [CustomLoss](https://fastmonai.no/vision_loss_functions.html#customloss)) expects.

A DynUNet(deep_supervision=True) returns a stacked [B, N, C, ...] tensor in training (a TorchScript workaround), but DeepSupervisionLoss only unbinds a list of tensors – a stacked tensor would fall through to the base loss and be scored incorrectly. This adapter unbinds the stack into that list in training, and passes the plain prediction through in eval mode (MONAI’s DynUNet docstring prescribes exactly this torch.unbind).

Note: wrapping registers the network as self.model, so it adds a model. prefix to state-dict keys – relevant when loading raw .pth checkpoints of a wrapped model.