U Ph4@s~ddlmZddlZddlmZddlmZddlmZddd gZ Gd ddeZ dd d d d dd dddZ Gdd d Z dS)) annotationsN)do_metric_reduction)MetricReduction)CumulativeIterationMetric DiceMetric compute_dice DiceHelperc sfeZdZdZdejddddfddddddd d fd d Zd d d dddZddddddZZ S)ra Compute average Dice score for a set of pairs of prediction-groundtruth segmentations. It supports both multi-classes and multi-labels tasks. Input `y_pred` is compared with ground truth `y`. `y_pred` is expected to have binarized predictions and `y` can be single-channel class indices or in the one-hot format. The `include_background` parameter can be set to ``False`` 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. `y_preds` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]), `y` can also be in the format of `B1HW[D]`. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: include_background: whether to include Dice computation on the first channel of the predicted output. Defaults to ``True``. reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric. ignore_empty: whether to ignore empty ground truth cases during calculation. If `True`, NaN value will be set for empty ground truth cases. If `False`, 1 will be set if the predictions of empty ground truth cases are also empty. num_classes: number of input channels (always including the background). When this is None, ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are single-channel class indices and the number of classes is not automatically inferred from data. return_with_label: whether to return the metrics with label, only works when reduction is "mean_batch". If `True`, use "label_{index}" as the key corresponding to C channels; if 'include_background' is True, the index begins at "0", otherwise at "1". It can also take a list of label names. The outcome will then be returned as a dictionary. TFNboolMetricReduction | str int | Nonezbool | list[str]None)include_background reduction get_not_nans ignore_empty num_classesreturn_with_labelreturncsPt||_||_||_||_||_||_t|jt j dd|j|jd|_ dS)NFrrrsoftmaxrr) super__init__rrrrrrr rNONE dice_helper)selfrrrrrr __class__K/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/meandice.pyr<s zDiceMetric.__init__ torch.Tensory_predyrcCs.|}|dkr td|d|j||dS)a Args: y_pred: input data to compute, typical segmentation model output. It must be one-hot format and first dim is batch, example shape: [16, 3, 32, 32]. The values should be binarized. y: ground truth to compute mean Dice metric. `y` can be single-channel class indices or in the one-hot format. Raises: ValueError: when `y_pred` has less than three dimensions. zHy_pred should have at least 3 dimensions (batch, channel, spatial), got .r"r#) ndimension ValueErrorr)rr"r#dimsrrr_compute_tensorUs zDiceMetric._compute_tensorzMetricReduction | str | None0torch.Tensor | tuple[torch.Tensor, torch.Tensor])rrc Cs|}t|tjs(tdt|dt||p4|j\}}|jtj kr|j ri}t|j t rt |D]8\}}|j sd|dnd|}t|d||<qfn(t|j |D]\} }t|d|| <q|}|jr||fS|S)a Execute reduction and aggregation logic for the output of `compute_dice`. Args: reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. z2the data to aggregate must be PyTorch Tensor, got r%label_r) get_buffer isinstancetorchTensorr(typerrr MEAN_BATCHrr enumeraterrounditemzipr) rrdatafnot_nans_fivZ _label_keykeyrrr aggregategs   zDiceMetric.aggregate)N) __name__ __module__ __qualname____doc__rMEANrr*r? __classcell__rrrrrs% Tr r r )r"r#rrrrcCst|tjdd||d||dS)aComputes Dice score metric for a batch of predictions. Args: y_pred: input data to compute, typical segmentation model output. `y_pred` can be single-channel class indices or in the one-hot format. y: ground truth to compute mean dice metric. `y` can be single-channel class indices or in the one-hot format. include_background: whether to include Dice computation on the first channel of the predicted output. Defaults to True. ignore_empty: whether to ignore empty ground truth cases during calculation. If `True`, NaN value will be set for empty ground truth cases. If `False`, 1 will be set if the predictions of empty ground truth cases are also empty. num_classes: number of input channels (always including the background). When this is None, ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are single-channel class indices and the number of classes is not automatically inferred from data. Returns: Dice scores per batch and per class, (shape: [batch_size, num_classes]). Frr&)r rr)r"r#rrrrrrrsc @sfeZdZdZdddddejddfddddddddd d d d Zd d d dddZd d ddddZdS)r a Compute Dice score between two tensors `y_pred` and `y`. `y_pred` and `y` can be single-channel class indices or in the one-hot format. Example: .. code-block:: python import torch from monai.metrics import DiceHelper n_classes, batch_size = 5, 16 spatial_shape = (128, 128, 128) y_pred = torch.rand(batch_size, n_classes, *spatial_shape).float() # predictions y = torch.randint(0, n_classes, size=(batch_size, 1, *spatial_shape)).long() # ground truth score, not_nans = DiceHelper(include_background=False, sigmoid=True, softmax=True)(y_pred, y) print(score, not_nans) NFTz bool | Noner r r r ) rsigmoidractivaterrrrrc CsN||_||_||_|dkr|n||_|dkr2| n||_||_||_||_dS)aV Args: include_background: whether to include the score on the first channel (default to the value of `sigmoid`, False). sigmoid: whether ``y_pred`` are/will be sigmoid activated outputs. If True, thresholding at 0.5 will be performed to get the discrete prediction. Defaults to False. softmax: whether ``y_pred`` are softmax activated outputs. If True, `argmax` will be performed to get the discrete prediction. Defaults to the value of ``not sigmoid``. activate: whether to apply sigmoid to ``y_pred`` if ``sigmoid`` is True. Defaults to False. This option is only valid when ``sigmoid`` is True. get_not_nans: whether to return the number of not-nan values. reduction: define mode of reduction to the metrics ignore_empty: if `True`, NaN value will be set for empty ground truth cases. If `False`, 1 will be set if the Union of ``y_pred`` and ``y`` is empty. num_classes: number of input channels (always including the background). When this is None, ``y_pred.shape[1]`` will be used. This option is useful when both ``y_pred`` and ``y`` are single-channel class indices and the number of classes is not automatically inferred from data. N)rFrrrrrGrr) rrrFrrGrrrrrrrrszDiceHelper.__init__r r!cCst|}|dkr6dtt|||t|S|jrPtjtd|jdS|t|}|dkrvtjd|jdStjd|jdS)rg@nan)deviceg?g)r0sum masked_selectrtensorfloatrJ)rr"r#y_oZdenormrrrcompute_channels $zDiceHelper.compute_channelr+cCs~|j|j}}|jdkr$|jd}n&|j}|jddkrJ|jdkrJd}}|rh|dkrtj|ddd}n|r|jr|t|}|dk}|jrdnd}g}t|jdD]}g} |dkrt||ndgD]p} |jddkr||df| kn||| f } |jddkr||df| kn ||| f} | | | | q| t | qtj |dd }t||j\} }|jrz| |fS| S) a< Args: y_pred: input predictions with shape (batch_size, num_classes or 1, spatial_dims...). the number of channels is inferred from ``y_pred.shape[1]`` when ``num_classes is None``. y: ground truth with shape (batch_size, num_classes or 1, spatial_dims...). NrFT)dimkeepdimg?r)rQ)rrFrshaper0argmaxrGrranger appendrPstack contiguousrrr)rr"r#_softmaxZ_sigmoid n_pred_chZfirst_chr8bZc_listcZx_predxr9r:rrr__call__s2   .,zDiceHelper.__call__) r@rArBrCrr3rrPr^rrrrr s ' )TTN) __future__rr0monai.metrics.utilsr monai.utilsrmetricr__all__rrr rrrr s     q$