U PhI @svddlmZddlZddlmZmZddlmZmZm Z ddl m Z Gddde Z d ej fd d d d d d ddZdS)) annotationsN)do_metric_reductionignore_background)MetricReductionWeightlook_up_option)CumulativeIterationMetriccs\eZdZdZdejejfdddddfdd Zd d d d d d Z ddd dddZ Z S)GeneralizedDiceScoreaCompute the Generalized Dice Score metric between tensors, as 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 channel-first or batch-first tensors, i.e., CHW[D] or BCHW[D]. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: include_background (bool, optional): whether to include the background class (assumed to be in channel 0), in the score computation. Defaults to True. reduction (str, optional): define mode of reduction to the metrics. Available reduction modes: {``"none"``, ``"mean_batch"``, ``"sum_batch"``}. Default to ``"mean_batch"``. If "none", will not do reduction. weight_type (Union[Weight, str], optional): {``"square"``, ``"simple"``, ``"uniform"``}. Type of function to transform ground truth volume into a weight factor. Defaults to ``"square"``. Raises: ValueError: when the `weight_type` is not one of {``"none"``, ``"mean"``, ``"sum"``}. TboolzMetricReduction | str Weight | strNone)include_background reduction weight_typereturncsTt||_dddtjtjtjg}||_|j|krDtd|t |t |_ dS)Nnone mean_batch sum_batchreduction must be one of ) super__init__rrNONE MEAN_BATCH SUM_BATCHr ValueErrorrrr)selfrrrreduction_options __class__S/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/generalized_dice.pyr-s  zGeneralizedDiceScore.__init__ torch.Tensor)y_predyrcCst|||j|jdS)afComputes 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`. 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$rr)compute_generalized_dicerr)rr#r$r r r!_compute_tensorBs z$GeneralizedDiceScore._compute_tensorNzMetricReduction | str | None)rrcCs`|}t|tjstd|dk rHdddddg}||krHtd|t||pT|j\}}|S) a Execute reduction logic for the output of `compute_generalized_dice`. Args: reduction (Union[MetricReduction, str, None], optional): define mode of reduction to the metrics. Available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``}. Defaults to ``"mean"``. If "none", will not do reduction. z/The data to aggregate must be a PyTorch Tensor.Nrmeansumrrr) get_buffer isinstancetorchTensorrrr)rrdatarf_r r r! aggregateQs  zGeneralizedDiceScore.aggregate)N) __name__ __module__ __qualname____doc__rrrSQUARErr&r0 __classcell__r r rr!r sr Tr"r r )r#r$rrrcCs|}|dkr td|d|j|jkrFtd|jd|jd|sZt||d\}}ttd|}tj|||d }tj||d }tj||d }||} t|t }|t j krt | } n0|t j krt | | } nt| } | D]$} t| } d | | <t| | | <qd || jd d } | | jd d }| |}|jd d }|d k}t|d k|tjd|jdtjd|jd||<|S)aComputes 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 (bool, optional): 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"``. 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@rg?)deviceg)r:rshaperlistranger+r(rrSIMPLE reciprocalfloatr5 ones_likeisinfmaxwheretensorr<)r#r$rrdims reduce_axis intersectionZy_oZy_pred_o denominatorwbinfsnumerdenomZgeneralized_dice_scoreZ denom_zerosr r r!r%jsB       r%) __future__rr+monai.metrics.utilsrr monai.utilsrrrmetricr r r5r%r r r r! s  U