U tPh@s:ddlmZddlZddlmZmZddlmZddlZ ddl Z ddl m Z ddl m mZddlmZddlmZddlmZddlmZdd lmZmZmZmZmZmZGd d d eZGd d d eZ GdddeZ!GdddeZ"GdddeZ#GdddeZ$GdddeZ%eZ&e#Z'e$Z(e!Z)e%Z*e"Z+dS)) annotationsN)CallableSequence)Any)_Loss) FocalLoss) MaskedLoss)one_hot)DiceCEReduction LossReductionWeightdeprecated_arglook_up_option pytorch_aftercsleZdZdZdddddddejddddf ddddddddd d dd d d fd d ZddddddZZS)DiceLossaN Compute average Dice loss between two tensors. It can support both multi-classes and multi-labels tasks. The data `input` (BNHW[D] where N is number of classes) is compared with ground truth `target` (BNHW[D]). Note that axis N of `input` is expected to be logits or probabilities for each class, if passing logits as input, must set `sigmoid=True` or `softmax=True`, or specifying `other_act`. And 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 original paper: Milletari, F. et. al. (2016) V-Net: Fully Convolutional Neural Networks forVolumetric Medical Image Segmentation, 3DV, 2016. TFNh㈵>boolCallable | NoneLossReduction | strfloat3Sequence[float] | float | int | torch.Tensor | NoneNone) include_background to_onehot_ysigmoidsoftmax other_act squared_predjaccard reduction smooth_nr smooth_drbatchweightreturnc stjt|jd|dk r:t|s:tdt|jdt|t|t|dk dkrbt d||_ ||_ ||_ ||_ ||_||_||_t| |_t| |_| |_| dk rt| nd} |d| |dS)a Args: include_background: if False, channel index 0 (background category) is excluded from the calculation. 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. to_onehot_y: whether to convert the ``target`` into the one-hot format, using the number of classes inferred from `input` (``input.shape[1]``). 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: 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`. 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. If not ``include_background``, the number of classes should not include the background category class 0). The value/values should be no less than 0. Defaults to None. 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. rN*other_act must be None or callable but is .XIncompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None]. class_weight)super__init__r valuecallable TypeErrortype__name__int ValueErrorrrrrrrrrr r!r"torch as_tensorregister_buffer) selfrrrrrrrrr r!r"r# __class__F/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/losses/dice.pyr,/s$4    zDiceLoss.__init__ torch.Tensorinputtargetr$c Cs|jrt|}|jd}|jr@|dkr4tdn t|d}|jdk rT||}|jrz|dkrntdn t||d}|j s|dkrtdn(|ddddf}|ddddf}|j|jkrt d|jd|jd t d t |j }|jr d g|}tj|||d }|jrJtj|d |d }tj|d |d }ntj||d }tj||d }||}|jrd ||}dd ||j||j} |jd} |jdk r$| dkr$|jjd krt|jg| |_n|jjd | krtd|jd krtd| |j| } |jtjjkr@t| } np|jtjjkr\t| } nT|jtj jkrt!| jd d dgt |jd } | "| } ntd|jd| S)a Args: 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) >>> assert np.broadcast_shapes(loss.shape, input.shape) == input.shape r(2single channel prediction, `softmax=True` ignored.N6single channel prediction, `to_onehot_y=True` ignored. num_classes>single channel prediction, `include_background=False` ignored.z"ground truth has different shape () from input ()rdim@?zthe length of the `weight` sequence should be the same as the number of classes. If `include_background=False`, the weight should not include the background category class 0.z:the value/values of the `weight` should be no less than 0.Unsupported reduction: 0, available options are ["mean", "sum", "none"].)#rr4shaperwarningswarnrrr rAssertionErrorarangelentolistr"sumrrr r!r*ndimr5r3mintorr MEANr-meanSUMNONElistview) r7r>r? n_pred_ch reduce_axis intersectionground_opred_o denominatorfZnum_of_classesbroadcast_shaper:r:r;forwardvsj               & zDiceLoss.forward) r1 __module__ __qualname____doc__r rYr,rg __classcell__r:r:r8r;rs,Grcs@eZdZdZddddfdd Zd ddd dd d d ZZS)MaskedDiceLossa 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. rr)argskwargsr$cs"tj||ttjd|_dS)z@ Args follow :py:class:`monai.losses.DiceLoss`. )lossN)r+r,rrgspatial_weighted)r7rmrnr8r:r;r,szMaskedDiceLoss.__init__Nr<torch.Tensor | None)r>r?maskr$cCs|j|||dS)z Args: input: the shape should be BNH[WD]. target: the shape should be BNH[WD]. mask: the shape should B1H[WD] or 11H[WD]. )r>r?rr)rp)r7r>r?rrr:r:r;rgszMaskedDiceLoss.forward)N)r1rhrirjr,rgrkr:r:r8r;rls rlc sneZdZdZdddddejejdddf ddddddd d d dd d fd d ZddZ ddddddZ Z S)GeneralizedDiceLossa> Compute the generalised Dice loss defined in: Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning loss function for highly unbalanced segmentations. DLMIA 2017. Adapted from: https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/layer/loss_segmentation.py#L279 TFNrrr Weight | strrrr) rrrrrw_typerr r!r"r$c stjt|jd|dk r:t|s:tdt|jdt|t|t|dk dkrbt d||_ ||_ ||_ ||_ ||_t|t|_t||_t| |_| |_dS)al Args: include_background: If False channel index 0 (background category) is excluded from the calculation. to_onehot_y: whether to convert the ``target`` into the one-hot format, using the number of classes inferred from `input` (``input.shape[1]``). 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: callable function to execute other activation layers, Defaults to ``None``. for example: ``other_act = torch.tanh``. w_type: {``"square"``, ``"simple"``, ``"uniform"``} Type of function to transform ground truth volume to a weight factor. Defaults to ``"square"``. 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, intersection over union is computed from each item in the batch. If True, the class-weighted intersection and union areas are first summed across the batches. 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. r%Nr&r'r(r))r+r,r r-r.r/r0r1r2r3rrrrrrr rurr r!r") r7rrrrrrurr r!r"r8r:r;r,s*    zGeneralizedDiceLoss.__init__cCsB|jttjkrt|S|jttjkr8t||St|S)N)rustrr SIMPLEr4 reciprocalSQUARE ones_like)r7Zgrndr:r:r;w_funcCs  zGeneralizedDiceLoss.w_funcr<r=cCs|jrt|}|jd}|jr@|dkr4tdn t|d}|jdk rT||}|jrz|dkrntdn t||d}|j s|dkrtdn(|ddddf}|ddddf}|j|jkrt d|jd|jd t d t |j }|jr d g|}t|||}t||}t||}||}||} t| } |jrvd | | <| | t| } n.d | | <tj| dd d jdd } | | | } |jrd nd} d|| j| dd|j} || j| dd|j}d| |}|jtjjkrt|}np|jtjjkr,t|}nT|jtjjkrnt|jd d dgt |jd }||}nt d|jd|S)z Args: input: the shape should be BNH[WD]. target: the shape should be BNH[WD]. Raises: ValueError: When ``self.reduction`` is not one of ["mean", "sum", "none"]. r(r@NrArBrDz"ground truth has differing shape (rErFrGrrHrJT)keepdimrKrLrM)!rr4rNrrOrPrrr rrQrRrSrTr"rUr{risinfmax unsqueezer r!rr rYr-rZr[r\r]r^r3)r7r>r?r_r`rarbrcrdwinfsZ max_valuesZfinal_reduce_dimnumerdenomrerfr:r:r;rgJs`                   & zGeneralizedDiceLoss.forward) r1rhrirjr ryr rYr,r{rgrkr:r:r8r;rss (<rscseZdZdZdejddfddddddd fd d Zd d d d ddZd d d dddZd d d d dddZ d d d d dddZ d d dddZ Z S)GeneralizedWassersteinDiceLossa{ 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 defaultrznp.ndarray | torch.Tensorrvrrr) dist_matrixweighting_moderr r!r$cstjt|jd|jd|jdkrJtd|jdd|jdd|dkr^td|||_t|jtj rt |j|_t |jdkr|jt |j|_||_ |jd|_t||_t||_d S) a Args: 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: .. code-block:: python 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 r%rr(zdist_matrix must be C x C, got z x r')rGDLz8weighting_mode must be either 'default' or 'GDL, got %s.N)r+r,r r-rNr3m isinstancenpndarrayr4 from_numpyr alpha_modesizerCrr r!)r7rrrr r!r8r:r;r,s5"  z'GeneralizedWassersteinDiceLoss.__init__r<r=cCsJ||d|dd}||dd}tj|dd}|||}||}|jdkr|||||}| |||} n(||||}t j |dd} d|| } d||j | |j } d| } |jtjjkrt | } nh|jtjjkrt | } nN|jtjjkr4|jddd t|jd} | | } ntd |jd | S) zy Args: input: the shape should be BNH[WD]. target: the shape should be BNH[WD]. rr(rHrrGrJrK)r(rLrM)reshaperlongFrwasserstein_distance_map)_compute_alpha_generalized_true_positivesr"_compute_generalized_true_positive_compute_denominatorr4rUr r!rr rYr-rZr[r\rNrSr^r3)r7r>r? flat_input flat_targetprobsZ wass_dist_mapalphaZtrue_posrZ all_errorZ wass_diceZwass_dice_lossrfr:r:r;rgs,        z&GeneralizedWassersteinDiceLoss.forward) flat_probarr$cCstt|j|j}tj|dd}tj|dd}||d|d|d|df}tj|dd}||d|d|df}tj|dd}tj |d|d}tj |dd}||}tj |dd}|S)a( 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. Args: flat_proba: the probabilities of input(predicted) tensor. flat_target: the target tensor. rrHr(rG)rIindex) r4cloner5rrXdevicerexpandrgathersqueezerU)r7rrrZ m_extendedflat_target_extendedZwasserstein_mapr:r:r;r%s*z7GeneralizedWassersteinDiceLoss.wasserstein_distance_map)rrrr$cCsdtj|dd}||d|j|df}tj|dd}tj||dd}tj|d|ddgdS) Args: alpha: generalised number of true positives of target class. flat_target: the target tensor. wasserstein_distance_map: the map obtained from the above function. rGrHrr(rrIrKr4rrrrCrrUr7rrrZalpha_extendedrr:r:r;rKs zAGeneralizedWassersteinDiceLoss._compute_generalized_true_positivecCsdtj|dd}||d|j|df}tj|dd}tj||dd}tj|d|ddgdS)rrGrHrr(rrJrrr:r:r;r\s z3GeneralizedWassersteinDiceLoss._compute_denominator)rr$cCszt|d|jf|j}|jdkrftj ||jd ddd}tj |dd}d|d}nd|d d df<|S) zC Args: flat_target: the target tensor. rrrBrGr(rHrKr|N) r4onesrrCrrXrrrr permuterU)r7rrZ one_hot_fZvolumesr:r:r;rms" zHGeneralizedWassersteinDiceLoss._compute_alpha_generalized_true_positives) r1rhrirjr rYr,rgrrrrrkr:r:r8r;rsG3&rcseZdZdZeddddddddddddddddddddddddfdd ZddddddZddddddZddddddZZ S) DiceCELossa 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`` and ``torch.nn.BCEWithLogitsLoss()``. In this implementation, two deprecated parameters ``size_average`` and ``reduce``, and the parameter ``ignore_index`` are not supported. ce_weight1.21.4r#please use `weight` instead.sinceremovednew_name msg_suffixTFNrZrrKrrrvrrqr)rrrrrrrrr r!r"rr# lambda_dice lambda_cer$cstt|tj}| dk r"| n| } | dk r@|s@| dd}n| }t||||||||| | | |d |_tj| |d|_ tj | |d|_ |dkrt d|dkrt d||_ ||_tdd  |_dS) ao Args: ``lambda_ce`` are only used for cross entropy loss. ``reduction`` and ``weight`` 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 the ``target`` into the one-hot format, using the number of classes inferred from `input` (``input.shape[1]``). 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` and `BCEWithLogitsLoss`. softmax: if True, apply a softmax function to the prediction, only used by the `DiceLoss`, don't need to specify activation function for `CrossEntropyLoss` and `BCEWithLogitsLoss`. other_act: callable function to execute other activation layers, Defaults to ``None``. for example: ``other_act = torch.tanh``. only used by the `DiceLoss`, not for the `CrossEntropyLoss` and `BCEWithLogitsLoss`. 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`. weight: a rescaling weight given to each class for cross entropy loss for `CrossEntropyLoss`. or a weight of positive examples to be broadcasted with target used as `pos_weight` for `BCEWithLogitsLoss`. See ``torch.nn.CrossEntropyLoss()`` or ``torch.nn.BCEWithLogitsLoss()`` for more information. The weight is also used in `DiceLoss`. 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. Nr( rrrrrrrrr r!r"r#)r#r) pos_weightrr|'lambda_dice should be no less than 0.0.z%lambda_ce should be no less than 0.0. )r+r,rr r-rdicennCrossEntropyLoss cross_entropyBCEWithLogitsLossbinary_cross_entropyr3rrr old_pt_ver)r7rrrrrrrrr r!r"rr#rrZ dice_weightr8r:r;r,s:<   zDiceCELoss.__init__r<r=cCs|jd|jd}}||kr>|dkr>tj|dd}|}nB|jrhtdtjdtj|dd}nt |s|j |j d}| ||S)a Compute CrossEntropy loss for the input logits and target. Will remove the channel dim according to PyTorch CrossEntropyLoss: https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html?#torch.nn.CrossEntropyLoss. r(rHzEMultichannel targets are not supported in this older Pytorch version zG. Using argmax (as a workaround) to convert target to a single channel.dtype) rNr4rrrrOrP __version__argmaxis_floating_pointrXrr)r7r>r?r_Z n_target_chr:r:r;ces   z DiceCELoss.cecCs$t|s|j|jd}|||S)zh Compute Binary CrossEntropy loss for the input logits and target in one single class. r)r4rrXrr)r7r>r?r:r:r;bces zDiceCELoss.bcec Cs||krBtd|jdt|jd|jdt|jd |jddkr~|jd|jdkr~td|jd|jd|||}|jddkr|||n |||}|j||j|}|S) a Args: 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 (without one-hot encoding) nor the same as input. Returns: torch.Tensor: value of the loss. Lthe number of dimensions for input and target should be the same, got shape (nb dims: ) and P). if target is not one-hot encoded, please provide a tensor with shape B1H[WD].r(gnumber of channels for target is neither 1 (without one-hot encoding) nor the same as input, got shape  and r') rIr3rNrSrrrrr)r7r>r? dice_lossce_loss total_lossr:r:r;rgs," &zDiceCELoss.forward)TFFFNFFrZrrFNNrKrK) r1rhrirjr r,rrrgrkr:r:r8r;rs6 4Y rcsleZdZdZedddddddddddddddddddddddddfdd ZddddddZZS) DiceFocalLossa 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``. ``gamma`` and ``lambda_focal`` are only used for the focal loss. ``include_background``, ``weight`` and ``reduction`` are used for both losses and other parameters are only used for dice loss. focal_weightrrr#rrTFNrZrrJrKrrrvrrr)rrrrrrrrr r!r"gammarr#r lambda_focalr$cst| dk r| n|}t|d||||||| | | |d |_t|d| ||d|_|dkr`td|dkrptd||_||_||_ dS)a Args: include_background: if False channel index 0 (background category) is excluded from the calculation. to_onehot_y: whether to convert the ``target`` into the one-hot format, using the number of classes inferred from `input` (``input.shape[1]``). 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: callable function to execute other activation layers, Defaults to ``None``. for example: `other_act = torch.tanh`. only used by the `DiceLoss`, not 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. 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. NFrrrrr#rr|r(lambda_focal should be no less than 0.0.) r+r,rrrfocalr3rrr)r7rrrrrrrrr r!r"rrr#rrr8r:r;r,3s<9 zDiceFocalLoss.__init__r<r=c Cs||krBtd|jdt|jd|jdt|jd |jddkr~|jd|jdkr~td|jd|jd|jr|jd}|dkrtd n t||d }|||}| ||}|j ||j |}|S) a Args: 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 (without one-hot encoding) nor the same as input. Returns: torch.Tensor: value of the loss. rrrrr(rrr'rArB) rIr3rNrSrrOrPr rrrr)r7r>r?r_r focal_lossrr:r:r;rgs","     zDiceFocalLoss.forward)TFFFNFFrZrrFrJNNrKrK)r1rhrirjr r,rgrkr:r:r8r;r's4 6QrcseZdZdZedddddddd d d d ejejd d d d d d d d fdddddddddddddddddfdd Z ddddddZ Z S)GeneralizedDiceFocalLossa Compute both Generalized Dice Loss and Focal Loss, and return their weighted average. The details of Generalized Dice Loss and Focal Loss are available at ``monai.losses.GeneralizedDiceLoss`` and ``monai.losses.FocalLoss``. Args: include_background (bool, optional): if False channel index 0 (background category) is excluded from the calculation. Defaults to True. to_onehot_y: whether to convert the ``target`` into the one-hot format, using the number of classes inferred from `input` (``input.shape[1]``). Defaults to False. sigmoid (bool, optional): if True, apply a sigmoid function to the prediction. Defaults to False. softmax (bool, optional): if True, apply a softmax function to the prediction. Defaults to False. other_act (Optional[Callable], optional): callable function to execute other activation layers, Defaults to ``None``. for example: `other_act = torch.tanh`. only used by the `GeneralizedDiceLoss`, not for the `FocalLoss`. w_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform ground-truth volume to a weight factor. Defaults to ``"square"``. reduction (Union[LossReduction, str], optional): {``"none"``, ``"mean"``, ``"sum"``}. Specified 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 (float, optional): a small constant added to the numerator to avoid zero. Defaults to 1e-5. smooth_dr (float, optional): a small constant added to the denominator to avoid nan. Defaults to 1e-5. batch (bool, optional): whether to sum the intersection and union areas over the batch dimension before the dividing. Defaults to False, i.e., the areas are computed for each item in the batch. gamma (float, optional): value of the exponent gamma in the definition of the Focal loss. Defaults to 2.0. weight (Optional[Union[Sequence[float], float, int, torch.Tensor]], optional): 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 hould be the same as the number of classes). Defaults to None. lambda_gdl (float, optional): the trade-off weight value for Generalized Dice Loss. The value should be no less than 0.0. Defaults to 1.0. lambda_focal (float, optional): the trade-off weight value for Focal Loss. The value should be no less than 0.0. Defaults to 1.0. Raises: ValueError: if either `lambda_gdl` or `lambda_focal` is less than 0. rrrr#rrTFNrrJrKrrrtrrrr)rrrrrrurr r!r"rrr# lambda_gdlrr$c s|tt||||||||| | d |_| dk r4| n| } t||| | |d|_|dkr\td|dkrltd||_||_dS)N) rrrrrrurr r!r"rr|z&lambda_gdl should be no less than 0.0.r) r+r,rsgeneralized_dicerrr3rr)r7rrrrrrurr r!r"rrr#rrr8r:r;r,s6  z!GeneralizedDiceFocalLoss.__init__r<r=c Cs||krBtd|jdt|jd|jdt|jd |jddkr~|jd|jdkr~td|jd|jd|||}|||}|j||j|}|S) a/ Args: input (torch.Tensor): the shape should be BNH[WD]. The input should be the original logits due to the restriction of ``monai.losses.FocalLoss``. target (torch.Tensor): 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 (without one-hot encoding) nor the same as input. Returns: torch.Tensor: value of the loss. rrrrr(rrr')rIr3rNrSrrrr)r7r>r?Zgdl_lossrrr:r:r;rgs,"  z GeneralizedDiceFocalLoss.forward) r1rhrirjr r ryr rYr,rgrkr:r:r8r;rs2&4.r), __future__rrOcollections.abcrrtypingrnumpyrr4torch.nnrtorch.nn.functional functionalrtorch.nn.modules.lossrZmonai.losses.focal_lossrZmonai.losses.spatial_maskrmonai.networksr monai.utilsr r r r rrrrlrsrrrrDicedice_ce dice_focalrgeneralized_dice_focalgeneralized_wasserstein_dicer:r:r:r; s<        Df)y