U Ph:@sddlmZddlZddlmZddlZddlmZmZddl m Z m Z ddl m Z Gdd d e Zdd d d d d ddZdd d dddZdddddZdS)) annotationsN)Sequence)do_metric_reductionignore_background)MetricReduction ensure_tuple)CumulativeIterationMetriccsdeZdZdZdddejdfddddddd fd d Zd d d d ddZdddddddZZ S)ConfusionMatrixMetrica Compute confusion matrix related metrics. This function supports to calculate all metrics mentioned in: `Confusion matrix `_. It can support both multi-classes and multi-labels classification and segmentation tasks. `y_preds` is expected to have binarized predictions and `y` should be in one-hot format. You can use suitable transforms in ``monai.transforms.post`` first to achieve binarized values. The `include_background` parameter can be set to ``False`` for an instance 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. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: include_background: whether to include metric computation on the first channel of the predicted output. Defaults to True. metric_name: [``"sensitivity"``, ``"specificity"``, ``"precision"``, ``"negative predictive value"``, ``"miss rate"``, ``"fall out"``, ``"false discovery rate"``, ``"false omission rate"``, ``"prevalence threshold"``, ``"threat score"``, ``"accuracy"``, ``"balanced accuracy"``, ``"f1 score"``, ``"matthews correlation coefficient"``, ``"fowlkes mallows index"``, ``"informedness"``, ``"markedness"``] Some of the metrics have multiple aliases (as shown in the wikipedia page aforementioned), and you can also input those names instead. Except for input only one metric, multiple metrics are also supported via input a sequence of metric names, such as ("sensitivity", "precision", "recall"), if ``compute_sample`` is ``True``, multiple ``f`` and ``not_nans`` will be returned with the same order as input names when calling the class. compute_sample: when reducing, if ``True``, each sample's metric will be computed based on each confusion matrix first. if ``False``, compute reduction on the confusion matrices first, defaults to ``False``. 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), ...]. If False, aggregate() returns [metric, ...]. Here `not_nans` count the number of not nans for True Positive, False Positive, True Negative and False Negative. Its shape depends on the shape of the metric, and it has one more dimension with size 4. For example, if the shape of the metric is [3, 3], `not_nans` has the shape [3, 3, 4]. Thit_rateFboolzSequence[str] | strzMetricReduction | strNone)include_background metric_namecompute_sample reduction get_not_nansreturncs0t||_t||_||_||_||_dS)N)super__init__rrrrrr)selfrrrrr __class__S/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/confusion_matrix.pyrAs   zConfusionMatrixMetric.__init__ torch.Tensor)y_predyrcCs\|}|dkrtd|dks6|dkrL|jddkrL|jrLtdd|_t|||jdS) a Args: y_pred: input data to compute. It must be one-hot format and first dim is batch. The values should be binarized. y: ground truth to compute the metric. It must be one-hot format and first dim is batch. The values should be binarized. Raises: ValueError: when `y_pred` has less than two dimensions. z+y_pred should have at least two dimensions.rz;As for classification task, compute_sample should be False.F)rrr) ndimension ValueErrorshaperwarningswarnget_confusion_matrixr)rrrdimsrrr_compute_tensorPs  z%ConfusionMatrixMetric._compute_tensorNzMetricReduction | str | Nonez6list[torch.Tensor | tuple[torch.Tensor, torch.Tensor]])rrrc Cs|}t|tjstdg}|jD]l}|s4|jrTt||}t||pJ|j \}}nt||p`|j \}}t||}|j r| ||fq&| |q&|S)a Execute reduction for the confusion matrix values. Args: compute_sample: when reducing, if ``True``, each sample's metric will be computed based on each confusion matrix first. if ``False``, compute reduction on the confusion matrices first, defaults to ``False``. 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. z-the data to aggregate must be PyTorch Tensor.) get_buffer isinstancetorchTensorr"rrcompute_confusion_matrix_metricrrrappend) rrrdataresultsrZsub_confusion_matrixfnot_nansrrr aggregatees      zConfusionMatrixMetric.aggregate)FN) __name__ __module__ __qualname____doc__rMEANrr(r3 __classcell__rrrrr s)r Trr )rrrrc Cs|st||d\}}|j|jkr:td|jd|jd|jdd\}}|||d}|||d}||dk}||dk}|jdgd }|jdgd }|jdgd }|jd|}||} ||} tj|| || gdd S) am Compute confusion matrix. A tensor with the shape [BC4] will be returned. Where, the third dimension represents the number of true positive, false positive, true negative and false negative values for each channel of each sample within the input batch. Where, B equals to the batch size and C equals to the number of classes that need to be computed. Args: y_pred: input data to compute. It must be one-hot format and first dim is batch. The values should be binarized. y: ground truth to compute the metric. It must be one-hot format and first dim is batch. The values should be binarized. include_background: whether to include metric computation on the first channel of the predicted output. Defaults to True. Raises: ValueError: when `y_pred` and `y` have different shapes. )rrz*y_pred and y should have same shapes, got z and .Nrr rdim)rr#r"reshapesumfloatr+stack) rrr batch_sizen_classtptnpnfnfprrrr&s    r&str)rconfusion_matrixrcCst|}|}|dkr$|jdd}|jddkr:td|d}|d}|d }|d }||}||} tjtd |jd } |d kr||} } n|dkr|| } } n|dkr|||} } n|dkr|||} } n|dkr||} } n|dkr || } } n|dkr(|||} } nh|dkrD|||} } nL|dkrt |dk||| } t | dk|| | }t | d||d} | |d} n|dkr||||} } n|dkr|||| } } n|dkr,t |dk||| } t | dk|| | }| |d} } nd|dkrT|d|d||} } n<|dkr||||} t ||||||||} n|dkrt |dk||| } t ||dk|||| }t || } d} n|dkr0t |dk||| } t | dk|| | }| |d} d} n`|dkrt ||dk|||| }t ||dk|||| }||d} d} nt d t | tj rt | dk| | | S| | S)!a This function is used to compute confusion matrix related metric. Args: metric_name: [``"sensitivity"``, ``"specificity"``, ``"precision"``, ``"negative predictive value"``, ``"miss rate"``, ``"fall out"``, ``"false discovery rate"``, ``"false omission rate"``, ``"prevalence threshold"``, ``"threat score"``, ``"accuracy"``, ``"balanced accuracy"``, ``"f1 score"``, ``"matthews correlation coefficient"``, ``"fowlkes mallows index"``, ``"informedness"``, ``"markedness"``] Some of the metrics have multiple aliases (as shown in the wikipedia page aforementioned), and you can also input those names instead. confusion_matrix: Please see the doc string of the function ``get_confusion_matrix`` for more details. Raises: ValueError: when the size of the last dimension of confusion_matrix is not 4. NotImplementedError: when specify a not implemented metric_name. rrr;r z?the size of the last dimension of confusion_matrix should be 4.).r).r).r).rnan)devicetprtnrppvnpvfnrfprfdrforptg?tsaccbag@f1mccfmbmmkthe metric is not implemented.)"check_confusion_matrix_metric_namer! unsqueezer#r"r+tensorr?rMwheresqrtNotImplementedErrorr*r,)rrJmetric input_dimrCrHrDrGrErFZ nan_tensor numerator denominatorrNrOrPrQrrrr-s          (     r-)rrcCs|dd}|}|dkr dS|dkr,dS|dkr8dS|d krDd S|d krPd S|d kr\dS|dkrhdS|dkrtdS|dkrdS|dkrdS|dkrdS|dkrdS|dkrdS|dkrdS|dkrd S|d!krd"S|d#krd$Std%d&S)'ab There are many metrics related to confusion matrix, and some of the metrics have more than one names. In addition, some of the names are very long. Therefore, this function is used to check and simplify the name. Returns: Simplified metric name. Raises: NotImplementedError: when the metric is not implemented.  _)Z sensitivityrecallr Ztrue_positive_raterNrN)Z specificityZ selectivityZtrue_negative_raterOrO) precisionZpositive_predictive_valuerPrP)Znegative_predictive_valuerQrQ)Z miss_rateZfalse_negative_raterRrR)Zfall_outZfalse_positive_raterSrS)Zfalse_discovery_raterTrT)Zfalse_omission_raterUrU)Zprevalence_thresholdrVrV)Z threat_scoreZcritical_success_indexrWZcsirW)accuracyrXrX)Zbalanced_accuracyrYrY)Zf1_scorerZrZ)Z matthews_correlation_coefficientr[r[)Zfowlkes_mallows_indexr\r\)Z informednessZbookmaker_informednessr]Z youden_indexZyoudenr])Z markednessZdeltapr^r^r_N)replacelowerre)rrrrr`sJ r`)T) __future__rr$collections.abcrr+monai.metrics.utilsrr monai.utilsrrrfr r r&r-r`rrrr s   m-_