geowatch.utils.ext_monai module

Monai extensions.

class geowatch.utils.ext_monai.FocalLoss(include_background: bool = True, to_onehot_y: bool = False, gamma: float = 2.0, weight: Sequence[float] | float | int | Tensor | None = None, reduction: LossReduction | str = mean, ohem_ratio: float | None = None)[source]

Bases: _Loss

FocalLoss is an extension of BCEWithLogitsLoss that down-weights loss from high confidence correct predictions.

Reimplementation of the Focal Loss (with a build-in sigmoid activation) described in:

  • “Focal Loss for Dense Object Detection”, T. Lin et al., ICCV 2017

  • “AnatomyNet: Deep learning for fast and fully automated whole‐volume segmentation of head and neck anatomy”, Zhu et al., Medical Physics 2018

Example

>>> import torch
>>> #from monai.losses import FocalLoss
>>> from torch.nn import BCEWithLogitsLoss
>>> shape = B, N, *DIMS = 2, 3, 5, 7, 11
>>> input = torch.rand(*shape)
>>> target = torch.rand(*shape)
>>> # Demonstrate equivalence to BCE when gamma=0
>>> fl_g0_criterion = FocalLoss(reduction='none', gamma=0)
>>> fl_g0_loss = fl_g0_criterion(input, target)
>>> bce_criterion = BCEWithLogitsLoss(reduction='none')
>>> bce_loss = bce_criterion(input, target)
>>> assert torch.allclose(fl_g0_loss, bce_loss)
>>> # Demonstrate "focus" by setting gamma > 0.
>>> fl_g2_criterion = FocalLoss(reduction='none', gamma=2)
>>> fl_g2_loss = fl_g2_criterion(input, target)
>>> # Mark easy and hard cases
>>> is_easy = (target > 0.7) & (input > 0.7)
>>> is_hard = (target > 0.7) & (input < 0.3)
>>> easy_loss_g0 = fl_g0_loss[is_easy].mean()
>>> hard_loss_g0 = fl_g0_loss[is_hard].mean()
>>> easy_loss_g2 = fl_g2_loss[is_easy].mean()
>>> hard_loss_g2 = fl_g2_loss[is_hard].mean()
>>> # Gamma > 0 causes the loss function to "focus" on the hard
>>> # cases.  IE, easy cases are downweighted, so hard cases
>>> # receive a higher proportion of the loss.
>>> hard_to_easy_ratio_g2 = hard_loss_g2 / easy_loss_g2
>>> hard_to_easy_ratio_g0 = hard_loss_g0 / easy_loss_g0
>>> assert hard_to_easy_ratio_g2 > hard_to_easy_ratio_g0
Parameters:
  • include_background – if False, channel index 0 (background category) is excluded from the calculation.

  • to_onehot_y – whether to convert y into the one-hot format. Defaults to False.

  • gamma – value of the exponent gamma in the definition of the Focal loss.

  • weight – weights to apply to the voxels of each class. If None no weights are applied. This corresponds to the weights lpha in [1]. The input can be a single value (same weight for all classes), a sequence of values (the length of the sequence should be the same as the number of classes, if not include_background, the number should not include class 0). The value/values should be no less than 0. Defaults to None.

  • reduction – {"none", "mean", "sum"} Specifies the reduction to apply to the output. Defaults to "mean".

    • "none": no reduction will be applied.

    • "mean": the sum of the output will be divided by the number of elements in the output.

    • "sum": the output will be summed.

  • ohem_ratio – whether to use OHEM (online hard example mining) to train the model. Defaults to None aka inactive.

Example

>>> import torch
>>> #from monai.losses import FocalLoss
>>> pred = torch.tensor([[1, 0], [0, 1], [1, 0]], dtype=torch.float32)
>>> grnd = torch.tensor([[0], [1], [0]], dtype=torch.int64)
>>> fl = FocalLoss(to_onehot_y=True)
>>> fl(pred, grnd)
forward(input: Tensor, target: Tensor) Tensor[source]
Parameters:
  • input – the shape should be BNH[WD], where N is the number of classes. The input should be the original logits since it will be transformed by a sigmoid in the forward function.

  • target – the shape should be BNH[WD] or B1H[WD], where N is the number of classes.

Raises:
  • ValueError – When input and target (after one hot transform if set) have different shapes.

  • ValueError – When self.reduction is not one of [“mean”, “sum”, “none”].

  • ValueError – When self.weight is a sequence and the length is not equal to the number of classes.

  • ValueError – When self.weight is/contains a value that is less than 0.

class geowatch.utils.ext_monai.DiceLoss(include_background: bool = True, to_onehot_y: bool = False, sigmoid: bool = False, softmax: bool = False, other_act: Callable | None = None, squared_pred: bool = False, jaccard: bool = False, reduction: LossReduction | str = mean, smooth_nr: float = 1e-05, smooth_dr: float = 1e-05, batch: bool = False)[source]

Bases: _Loss

Compute average Dice loss between two tensors. It can support both multi-classes and multi-labels tasks. Input logits input (BNHW[D] where N is number of classes) is compared with ground truth target (BNHW[D]). Axis N of input is expected to have logit predictions for each class rather than being image channels, while the same axis of target can be 1 or N (one-hot format). The smooth_nr and smooth_dr parameters are values added to the intersection and union components of the inter-over-union calculation to smooth results respectively, these values should be small. The include_background class attribute can be set to False for an instance of DiceLoss to exclude the first category (channel index 0) which is by convention assumed to be background. If the non-background segmentations are small compared to the total image size they can get overwhelmed by the signal from the background so excluding it in such cases helps convergence.

Milletari, F. et. al. (2016) V-Net: Fully Convolutional Neural Networks forVolumetric Medical Image Segmentation, 3DV, 2016.

Parameters:
  • include_background – if False, channel index 0 (background category) is excluded from the calculation.

  • to_onehot_y – whether to convert y into the one-hot format. Defaults to False.

  • sigmoid – if True, apply a sigmoid function to the prediction.

  • softmax – if True, apply a softmax function to the prediction.

  • other_act – if don’t want to use sigmoid or softmax, use other callable function to execute other activation layers, Defaults to None. for example: other_act = torch.tanh.

  • squared_pred – use squared versions of targets and predictions in the denominator or not.

  • jaccard – compute Jaccard Index (soft IoU) instead of dice or not.

  • reduction – {"none", "mean", "sum"} Specifies the reduction to apply to the output. Defaults to "mean".

    • "none": no reduction will be applied.

    • "mean": the sum of the output will be divided by the number of elements in the output.

    • "sum": the output will be summed.

  • smooth_nr – a small constant added to the numerator to avoid zero.

  • smooth_dr – a small constant added to the denominator to avoid nan.

  • batch – whether to sum the intersection and union areas over the batch dimension before the dividing. Defaults to False, a Dice loss value is computed independently from each item in the batch before any reduction.

Raises:
  • TypeError – When other_act is not an Optional[Callable].

  • ValueError – When more than 1 of [sigmoid=True, softmax=True, other_act is not None]. Incompatible values.

forward(input: Tensor, target: Tensor) Tensor[source]
Parameters:
  • input – the shape should be BNH[WD], where N is the number of classes.

  • target – the shape should be BNH[WD] or B1H[WD], where N is the number of classes.

Raises:
  • AssertionError – When input and target (after one hot transform if set) have different shapes.

  • ValueError – When self.reduction is not one of [“mean”, “sum”, “none”].

Example

>>> #from monai.losses.dice import *  # NOQA
>>> import torch
>>> #from monai.losses.dice import DiceLoss
>>> B, C, H, W = 7, 5, 3, 2
>>> input = torch.rand(B, C, H, W)
>>> target_idx = torch.randint(low=0, high=C - 1, size=(B, H, W)).long()
>>> target = one_hot(target_idx[:, None, ...], num_classes=C)
>>> self = DiceLoss(reduction='none')
>>> loss = self(input, target)
class geowatch.utils.ext_monai.MaskedDiceLoss(*args, **kwargs)[source]

Bases: DiceLoss

Add an additional masking process before DiceLoss, accept a binary mask ([0, 1]) indicating a region, input and target will be masked by the region: region with mask 1 will keep the original value, region with 0 mask will be converted to 0. Then feed input and target to normal DiceLoss computation. This has the effect of ensuring only the masked region contributes to the loss computation and hence gradient calculation.

Args follow monai.losses.DiceLoss.

forward(input: Tensor, target: Tensor, mask: Tensor | None = None)[source]
Parameters:
  • input – the shape should be BNH[WD].

  • target – the shape should be BNH[WD].

  • mask – the shape should B1H[WD] or 11H[WD].

class geowatch.utils.ext_monai.GeneralizedWassersteinDiceLoss(dist_matrix: ndarray | Tensor, weighting_mode: str = 'default', reduction: LossReduction | str = mean, smooth_nr: float = 1e-05, smooth_dr: float = 1e-05)[source]

Bases: _Loss

Compute the generalized Wasserstein Dice Loss defined in:

Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.

Or its variant (use the option weighting_mode=”GDL”) defined in the Appendix of:

Tilborghs, S. et al. (2020) Comparative study of deep learning methods for the automatic segmentation of lung, lesion and lesion type in CT scans of COVID-19 patients. arXiv preprint arXiv:2007.15546

Adapted from:

https://github.com/LucasFidon/GeneralizedWassersteinDiceLoss

Parameters:
  • dist_matrix – 2d tensor or 2d numpy array; matrix of distances between the classes.

  • It must have dimension C x C where C is the number of classes.

  • weighting_mode – {"default", "GDL"} Specifies how to weight the class-specific sum of errors. Default to "default".

    • "default": (recommended) use the original weighting method as in:

      Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.

    • "GDL": use a GDL-like weighting method as in the Appendix of:

      Tilborghs, S. et al. (2020) Comparative study of deep learning methods for the automatic segmentation of lung, lesion and lesion type in CT scans of COVID-19 patients. arXiv preprint arXiv:2007.15546

  • reduction – {"none", "mean", "sum"} Specifies the reduction to apply to the output. Defaults to "mean".

    • "none": no reduction will be applied.

    • "mean": the sum of the output will be divided by the number of elements in the output.

    • "sum": the output will be summed.

  • smooth_nr – a small constant added to the numerator to avoid zero.

  • smooth_dr – a small constant added to the denominator to avoid nan.

Raises:

ValueError – When dist_matrix is not a square matrix.

Example

import torch
import numpy as np
from monai.losses import GeneralizedWassersteinDiceLoss

# Example with 3 classes (including the background: label 0).
# The distance between the background class (label 0) and the other classes is the maximum, equal to 1.
# The distance between class 1 and class 2 is 0.5.
dist_mat = np.array([[0.0, 1.0, 1.0], [1.0, 0.0, 0.5], [1.0, 0.5, 0.0]], dtype=np.float32)
wass_loss = GeneralizedWassersteinDiceLoss(dist_matrix=dist_mat)

pred_score = torch.tensor([[1000, 0, 0], [0, 1000, 0], [0, 0, 1000]], dtype=torch.float32)
grnd = torch.tensor([0, 1, 2], dtype=torch.int64)
wass_loss(pred_score, grnd)  # 0
forward(input: Tensor, target: Tensor) Tensor[source]
Parameters:
  • input – the shape should be BNH[WD].

  • target – the shape should be BNH[WD].

wasserstein_distance_map(flat_proba: Tensor, flat_target: Tensor) Tensor[source]

Compute the voxel-wise Wasserstein distance between the flattened prediction and the flattened labels (ground_truth) with respect to the distance matrix on the label space M. This corresponds to eq. 6 in:

Fidon L. et al. (2017) Generalised Wasserstein Dice Score for Imbalanced Multi-class Segmentation using Holistic Convolutional Networks. BrainLes 2017.

Parameters:
  • flat_proba – the probabilities of input(predicted) tensor.

  • flat_target – the target tensor.

class geowatch.utils.ext_monai.DiceCELoss(include_background: bool = True, to_onehot_y: bool = False, sigmoid: bool = False, softmax: bool = False, other_act: Callable | None = None, squared_pred: bool = False, jaccard: bool = False, reduction: str = 'mean', smooth_nr: float = 1e-05, smooth_dr: float = 1e-05, batch: bool = False, ce_weight: Tensor | None = None, lambda_dice: float = 1.0, lambda_ce: float = 1.0)[source]

Bases: _Loss

Compute both Dice loss and Cross Entropy Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in monai.losses.DiceLoss. The details of Cross Entropy Loss is shown in torch.nn.CrossEntropyLoss. In this implementation, two deprecated parameters size_average and reduce, and the parameter ignore_index are not supported.

Parameters:
  • ``ce_weight`` and ``lambda_ce`` are only used for cross entropy loss.

  • ``reduction`` is used for both losses and other parameters are only used for dice loss.

  • include_background – if False channel index 0 (background category) is excluded from the calculation.

  • to_onehot_y – whether to convert y into the one-hot format. Defaults to False.

  • sigmoid – if True, apply a sigmoid function to the prediction, only used by the DiceLoss, don’t need to specify activation function for CrossEntropyLoss.

  • softmax – if True, apply a softmax function to the prediction, only used by the DiceLoss, don’t need to specify activation function for CrossEntropyLoss.

  • other_act – if don’t want to use sigmoid or softmax, use other callable function to execute other activation layers, Defaults to None. for example: other_act = torch.tanh. only used by the DiceLoss, don’t need to specify activation function for CrossEntropyLoss.

  • squared_pred – use squared versions of targets and predictions in the denominator or not.

  • jaccard – compute Jaccard Index (soft IoU) instead of dice or not.

  • reduction – {"mean", "sum"} Specifies the reduction to apply to the output. Defaults to "mean". The dice loss should as least reduce the spatial dimensions, which is different from cross entropy loss, thus here the none option cannot be used.

    • "mean": the sum of the output will be divided by the number of elements in the output.

    • "sum": the output will be summed.

  • smooth_nr – a small constant added to the numerator to avoid zero.

  • smooth_dr – a small constant added to the denominator to avoid nan.

  • batch – whether to sum the intersection and union areas over the batch dimension before the dividing. Defaults to False, a Dice loss value is computed independently from each item in the batch before any reduction.

  • ce_weight – a rescaling weight given to each class for cross entropy loss. See torch.nn.CrossEntropyLoss() for more information.

  • lambda_dice – the trade-off weight value for dice loss. The value should be no less than 0.0. Defaults to 1.0.

  • lambda_ce – the trade-off weight value for cross entropy loss. The value should be no less than 0.0. Defaults to 1.0.

ce(input: Tensor, target: Tensor)[source]

Compute CrossEntropy loss for the input and target. Will remove the channel dim according to PyTorch CrossEntropyLoss: https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?#torch.nn.CrossEntropyLoss.

forward(input: Tensor, target: Tensor) Tensor[source]
Parameters:
  • input – the shape should be BNH[WD].

  • target – the shape should be BNH[WD] or B1H[WD].

Raises:
  • ValueError – When number of dimensions for input and target are different.

  • ValueError – When number of channels for target is neither 1 nor the same as input.

class geowatch.utils.ext_monai.DiceFocalLoss(include_background: bool = True, to_onehot_y: bool = False, sigmoid: bool = False, softmax: bool = False, other_act: Callable | None = None, squared_pred: bool = False, jaccard: bool = False, reduction: str = 'mean', smooth_nr: float = 1e-05, smooth_dr: float = 1e-05, batch: bool = False, gamma: float = 2.0, focal_weight: Sequence[float] | float | int | Tensor | None = None, lambda_dice: float = 1.0, lambda_focal: float = 1.0, ohem_ratio_focal: float | None = None)[source]

Bases: _Loss

Compute both Dice loss and Focal Loss, and return the weighted sum of these two losses. The details of Dice loss is shown in monai.losses.DiceLoss. The details of Focal Loss is shown in monai.losses.FocalLoss.

Parameters:
  • ``gamma``, ``focal_weight`` and ``lambda_focal`` are only used for focal loss.

  • ``include_background``, ``to_onehot_y``and ``reduction`` are used for both losses

  • and other parameters are only used for dice loss.

  • include_background – if False channel index 0 (background category) is excluded from the calculation.

  • to_onehot_y – whether to convert y into the one-hot format. Defaults to False.

  • sigmoid – if True, apply a sigmoid function to the prediction, only used by the DiceLoss, don’t need to specify activation function for FocalLoss.

  • softmax – if True, apply a softmax function to the prediction, only used by the DiceLoss, don’t need to specify activation function for FocalLoss.

  • other_act – if don’t want to use sigmoid or softmax, use other callable function to execute other activation layers, Defaults to None. for example: other_act = torch.tanh. only used by the DiceLoss, don’t need to specify activation function for FocalLoss.

  • squared_pred – use squared versions of targets and predictions in the denominator or not.

  • jaccard – compute Jaccard Index (soft IoU) instead of dice or not.

  • reduction – {"none", "mean", "sum"} Specifies the reduction to apply to the output. Defaults to "mean".

    • "none": no reduction will be applied.

    • "mean": the sum of the output will be divided by the number of elements in the output.

    • "sum": the output will be summed.

  • smooth_nr – a small constant added to the numerator to avoid zero.

  • smooth_dr – a small constant added to the denominator to avoid nan.

  • batch – whether to sum the intersection and union areas over the batch dimension before the dividing. Defaults to False, a Dice loss value is computed independently from each item in the batch before any reduction.

  • gamma – value of the exponent gamma in the definition of the Focal loss.

  • focal_weight – weights to apply to the voxels of each class. If None no weights are applied. The input can be a single value (same weight for all classes), a sequence of values (the length of the sequence should be the same as the number of classes).

  • lambda_dice – the trade-off weight value for dice loss. The value should be no less than 0.0. Defaults to 1.0.

  • lambda_focal – the trade-off weight value for focal loss. The value should be no less than 0.0. Defaults to 1.0.

  • ohem_ratio_focal – Whether to use OHEM (online hard example mining) to train the model during focal loss. Defaults to None aka inactive.

forward(input: Tensor, target: Tensor) Tensor[source]
Parameters:
  • input – the shape should be BNH[WD]. The input should be the original logits due to the restriction of monai.losses.FocalLoss.

  • target – the shape should be BNH[WD] or B1H[WD].

Raises:
  • ValueError – When number of dimensions for input and target are different.

  • ValueError – When number of channels for target is neither 1 nor the same as input.

geowatch.utils.ext_monai.Dice

alias of DiceLoss

geowatch.utils.ext_monai.dice_ce

alias of DiceCELoss

geowatch.utils.ext_monai.dice_focal

alias of DiceFocalLoss

geowatch.utils.ext_monai.generalized_wasserstein_dice

alias of GeneralizedWassersteinDiceLoss