o  i!@sddlmZddlZddlmZmZddlZerddlmZ ddl Z ddl m Z m Z ddlmZGdddeZdddZe jfdddZdS)) annotationsN) TYPE_CHECKINGcast)Averagelook_up_option)CumulativeIterationMetriccs>eZdZdZejfdfdd Zdd d ZddddZZ S)AveragePrecisionMetrica Computes Average Precision (AP). AP is a useful metric to evaluate a classifier when the classes are imbalanced. It can take values between 0.0 and 1.0, 1.0 being the best possible score. It summarizes a Precision-Recall curve as the weighted mean of precisions achieved at each threshold, with the increase in recall from the previous threshold used as the weight: .. math:: \text{AP} = \sum_n (R_n - R_{n-1}) P_n :label: ap where :math:`P_n` and :math:`R_n` are the precision and recall at the :math:`n^{th}` threshold. Referring to: `sklearn.metrics.average_precision_score `_. The input `y_pred` and `y` can be a list of `channel-first` Tensor or a `batch-first` Tensor. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} Type of averaging performed if not binary classification. Defaults to ``"macro"``. - ``"macro"``: calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - ``"weighted"``: calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). - ``"micro"``: calculate metrics globally by considering each element of the label indicator matrix as a label. - ``"none"``: the scores for each class are returned. average Average | strreturnNonecst||_dSN)super__init__r )selfr  __class__a/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/metrics/average_precision.pyr@s  zAveragePrecisionMetric.__init__y_pred torch.Tensory!tuple[torch.Tensor, torch.Tensor]cCs||fSrr)rrrrrr_compute_tensorDsz&AveragePrecisionMetric._compute_tensorNAverage | str | None"np.ndarray | float | npt.ArrayLikecCs@|\}}t|tjrt|tjstdt|||p|jdS)ar Typically `y_pred` and `y` are stored in the cumulative buffers at each iteration, This function reads the buffers and computes the Average Precision. Args: average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} Type of averaging performed if not binary classification. Defaults to `self.average`. z$y_pred and y must be PyTorch Tensor.)rrr ) get_buffer isinstancetorchTensor ValueErrorcompute_average_precisionr )rr rrrrr aggregateGs z AveragePrecisionMetric.aggregate)r r r r )rrrrr rr)r rr r) __name__ __module__ __qualname____doc__rMACROrrr# __classcell__rrrrr s " r rrrr floatc Csb||krdkrntdt|t|kstd|}t|dkr8td|dtdS|t j ddg|j |j dsVtd| dtdSt|}|jd d }||}||}d }}}t|D]2}tt||} |d|kr||||dkr|| 7}qz|| 7}||7}||||d7}d}qz||S) Nrz7y and y_pred must be 1 dimension data with same length.zy values can not be all z', skip AP computation and return `Nan`.nanr)dtypedevicez y values must be 0 or 1, but in T) descendingg) ndimensionlenAssertionErroruniquewarningswarnitemr*equalrtensorr,r-tolistargsortcpunumpyranger) rrZy_uniquenindicesnposapZtmp_posiZy_irrr _calculateYs2      rBr r rcCsp|}|}|dvrtd|jd|dvr"td|jd|dkr5|jddkr5|jdd}d}|dkrF|jddkrF|jdd}|dkrOt||S|j|jkrbtd |jd |jdt|t}|tjkrut||S| d d| d d}}d d t ||D}|tj kr|S|tj krt |S|tjkrdd |D}t j||dStd|d)aComputes Average Precision (AP). AP is a useful metric to evaluate a classifier when the classes are imbalanced. It summarizes a Precision-Recall according to equation :eq:`ap`. Referring to: `sklearn.metrics.average_precision_score `_. Args: y_pred: input data to compute, typical classification model output. the first dim must be batch, if multi-classes, it must be in One-Hot format. for example: shape `[16]` or `[16, 1]` for a binary data, shape `[16, 2]` for 2 classes data. y: ground truth to compute AP metric, the first dim must be batch. if multi-classes, it must be in One-Hot format. for example: shape `[16]` or `[16, 1]` for a binary data, shape `[16, 2]` for 2 classes data. average: {``"macro"``, ``"weighted"``, ``"micro"``, ``"none"``} Type of averaging performed if not binary classification. Defaults to ``"macro"``. - ``"macro"``: calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account. - ``"weighted"``: calculate metrics for each label, and find their average, weighted by support (the number of true instances for each label). - ``"micro"``: calculate metrics globally by considering each element of the label indicator matrix as a label. - ``"none"``: the scores for each class are returned. Raises: ValueError: When ``y_pred`` dimension is not one of [1, 2]. ValueError: When ``y`` dimension is not one of [1, 2]. ValueError: When ``average`` is not one of ["macro", "weighted", "micro", "none"]. Note: Average Precision expects y to be comprised of 0's and 1's. `y_pred` must be either prob. estimates or confidence values. )rzPPredictions should be of shape (batch_size, num_classes) or (batch_size, ), got .zLTargets should be of shape (batch_size, num_classes) or (batch_size, ), got rCr)dimz.data shapes of y_pred and y do not match, got z and rcSsg|] \}}t||qSr)rB).0Zy_pred_y_rrr sz-compute_average_precision..cSsg|]}t|qSr)sum)rGrHrrrrIs)weightszUnsupported average: z?, available options are ["macro", "weighted", "micro", "none"].)r/r!shapesqueezerBrrMICROflatten transposezipNONEr(npmeanWEIGHTEDr )rrr Z y_pred_ndimZy_ndimZ ap_valuesrKrrrr"ws<$           r")rrrrr r*)rrrrr r r r) __future__rr3typingrrr;rS numpy.typingnptr monai.utilsrrmetricrr rBr(r"rrrrs    <