o  i!@spddlmZddlZddlmZmZddlmZmZm Z m Z ddl m Z Gddde Z d ejd fdddZdS)) annotationsN)do_metric_reductionignore_background)MetricReductionWeightdeprecated_arglook_up_option)CumulativeIterationMetriccsTeZdZdZdejejfdfd d ZdddZ e dddddddddZ Z S)GeneralizedDiceScorea Compute the Generalized Dice Score metric between tensors. This metric is the complement of the Generalized Dice Loss defined in: Sudre, C. et. al. (2017) Generalised Dice overlap as a deep learning loss function for highly unbalanced segmentations. DLMIA 2017. The inputs `y_pred` and `y` are expected to be one-hot, binarized batch-first tensors, i.e., NCHW[D]. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: include_background: Whether to include the background class (assumed to be in channel 0) in the score computation. Defaults to True. reduction: Define mode of reduction to the metrics. Available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. Default value is changed from `MetricReduction.MEAN_BATCH` to `MetricReduction.MEAN` in v1.5.0. Old versions computed `mean` when `mean_batch` was provided due to bug in reduction. weight_type: {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform ground truth volume into a weight factor. Defaults to ``"square"``. Raises: ValueError: When the `reduction` is not one of MetricReduction enum. Tinclude_backgroundbool reductionMetricReduction | str weight_type Weight | strreturnNonecsHt||_t|t|_t|t|_|jtjtj tj tj hv|_ dSN) super__init__r rrrrrSUMMEAN MEAN_CHANNEL SUM_CHANNELsum_over_classes)selfr rr __class__`/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/metrics/generalized_dice.pyr1s    zGeneralizedDiceScore.__init__y_pred torch.TensorycCst|||j|j|jdS)a Computes the Generalized Dice Score and returns a tensor with its per image values. Args: y_pred (torch.Tensor): Binarized segmentation model output. It must be in one-hot format and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the remaining are the spatial dimensions. y (torch.Tensor): Binarized ground-truth. It must be in one-hot format and have the same shape as `y_pred`. Returns: torch.Tensor: Generalized Dice Score averaged across batch and class Raises: ValueError: If `y_pred` and `y` have less than 3 dimensions, or `y_pred` and `y` don't have the same shape. )r!r#r rr)compute_generalized_dicer rr)rr!r#rrr _compute_tensorBsz$GeneralizedDiceScore._compute_tensorz1.3.3z1.7.0zYReduction will be ignored. Set reduction during init. as gen.dice needs it during compute)sinceremoved msg_suffixNMetricReduction | str | NonecCs0|}t|tjstdt||j\}}|S)z Execute reduction logic for the output of `compute_generalized_dice`. Returns: torch.Tensor: Aggregated metric value. Raises: ValueError: If the data to aggregate is not a PyTorch Tensor. z/The data to aggregate must be a PyTorch Tensor.) get_buffer isinstancetorchTensor ValueErrorrr)rrdataf_rrr aggregateYs  zGeneralizedDiceScore.aggregate)r r rrrrrr)r!r"r#r"rr"r)rr)rr") __name__ __module__ __qualname____doc__rrrSQUARErr%rr2 __classcell__rrrr r s r TFr!r"r#r r rrrrcCs|}|dkrtd|d|j|jkr#td|jd|jd|s-t||d\}}ttd|}tj|||d }tj||d }tj||d } || } t|t }|t j krct | } n|t j krtt | | } nt| } | D]} t| } d | | <t| | | <q}|rd || jd d d}| | jd d d}| jdd d} n d || }| | }| } ||}|d k}t| d k|tjd|jdtjd|jd||<|S)a Computes the Generalized Dice Score and returns a tensor with its per image values. Args: y_pred (torch.Tensor): Binarized segmentation model output. It should be binarized, in one-hot format and in the NCHW[D] format, where N is the batch dimension, C is the channel dimension, and the remaining are the spatial dimensions. y (torch.Tensor): Binarized ground-truth. It should be binarized, in one-hot format and have the same shape as `y_pred`. include_background: Whether to include score computation on the first channel of the predicted output. Defaults to True. weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform ground truth volume into a weight factor. Defaults to ``"square"``. sum_over_labels (bool): Whether to sum the numerator and denominator across all labels before the final computation. Returns: torch.Tensor: Per batch and per class Generalized Dice Score, i.e., with the shape [batch_size, num_classes]. Raises: ValueError: If `y_pred` or `y` are not PyTorch tensors, if `y_pred` and `y` have less than three dimensions, or `y_pred` and `y` don't have the same shape. zHy_pred should have at least 3 dimensions (batch, channel, spatial), got .z y_pred - z - and y - z - should have the same shapes.)r!r#)dimrg@r T)r<keepdimg?)deviceg)r<r.shaperlistranger,sumrrSIMPLE reciprocalfloatr7 ones_likeisinfmaxwheretensorr?)r!r#r rrdims reduce_axis intersectionZy_oZy_pred_o denominatorwbinfsnumerdenomZgeneralized_dice_scoreZ denom_zerosrrr r$ssJ       r$) r!r"r#r"r r rrrr rr") __future__rr,monai.metrics.utilsrr monai.utilsrrrrmetricr r r7r$rrrr s  `