
    ёi-x                    j   S SK Jr  S SKrS SKJrJrJr  S SKrS SK	r	S SK	J
r
Jr  SSKJr  SSKJrJr  SSKJr  SS	KJr  \(       a  S S
KJr  S SKJr  S SK	Jr  / rS r " S S\R8                  S9r " S S\5      r " S S\5      r " S S\5      r  " S S\5      r!    S             SS jjr"g)    )annotationsN)TYPE_CHECKINGAnyLiteral)_C_ops_legacy_C_ops   )check_variable_and_dtype)_create_tensorin_pir_mode)LayerHelper)in_dynamic_mode)Sequence)Tensorc                V    [        U [        R                  [        R                  45      $ N)
isinstancenpndarraygeneric)vars    U/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/metric/metrics.py
_is_numpy_r   (   s    cBJJ

344    c                      \ rS rSrSrSS jr\R                  SS j5       r\R                  SS j5       r	\R                  SS j5       r
\R                  SS j5       rSS jrS	rg
)Metric,   a  
Base class for metric, encapsulates metric logic and APIs
Usage:

    .. code-block:: text

        m = SomeMetric()
        for prediction, label in ...:
            m.update(prediction, label)
        m.accumulate()

Advanced usage for :code:`compute`:

Metric calculation can be accelerated by calculating metric states
from model outputs and labels by built-in operators not by Python/NumPy
in :code:`compute`, metric states will be fetched as NumPy array and
call :code:`update` with states in NumPy format.
Metric calculated as follows (operations in Model and Metric are
indicated with curly brackets, while data nodes not):

    .. code-block:: text

             inputs & labels              || ------------------
                   |                      ||
                {model}                   ||
                   |                      ||
            outputs & labels              ||
                   |                      ||    tensor data
            {Metric.compute}              ||
                   |                      ||
          metric states(tensor)           ||
                   |                      ||
            {fetch as numpy}              || ------------------
                   |                      ||
          metric states(numpy)            ||    numpy data
                   |                      ||
            {Metric.update}               \/ ------------------

Examples:

    For :code:`Accuracy` metric, which takes :code:`pred` and :code:`label`
    as inputs, we can calculate the correct prediction matrix between
    :code:`pred` and :code:`label` in :code:`compute`.
    For examples, prediction results contains 10 classes, while :code:`pred`
    shape is [N, 10], :code:`label` shape is [N, 1], N is mini-batch size,
    and we only need to calculate accuracy of top-1 and top-5, we could
    calculate the correct prediction matrix of the top-5 scores of the
    prediction of each sample like follows, while the correct prediction
    matrix shape is [N, 5].

    .. code-block:: python
        :name: code-compute-example

        >>> import paddle

        >>> def compute(pred, label):
        ...     # sort prediction and slice the top-5 scores
        ...     pred = paddle.argsort(pred, descending=True)[:, :5]
        ...     # calculate whether the predictions are correct
        ...     correct = pred == label
        ...     return paddle.cast(correct, dtype='float32')
        ...

    With the :code:`compute`, we split some calculations to OPs (which
    may run on GPU devices, will be faster), and only fetch 1 tensor with
    shape as [N, 5] instead of 2 tensors with shapes as [N, 10] and [N, 1].
    :code:`update` can be define as follows:

    .. code-block:: python
        :name: code-update-example

        >>> def update(self, correct):
        ...     accs = []
        ...     for i, k in enumerate(self.topk):
        ...         num_corrects = correct[:, :k].sum()
        ...         num_samples = len(correct)
        ...         accs.append(float(num_corrects) / num_samples)
        ...         self.total[i] += num_corrects
        ...         self.count[i] += num_samples
        ...     return accs
c                    g r    selfs    r   __init__Metric.__init__   s    r   c                H    [        SU R                  R                   S35      e)
Reset states and result
z$function 'reset' not implemented in .NotImplementedError	__class____name__r    s    r   resetMetric.reset   s(    
 "24>>3J3J2K1M
 	
r   c                H    [        SU R                  R                   S35      e)a=  
Update states for metric

Inputs of :code:`update` is the outputs of :code:`Metric.compute`,
if :code:`compute` is not defined, the inputs of :code:`update`
will be flatten arguments of **output** of mode and **label** from data:
:code:`update(output1, output2, ..., label1, label2,...)`

see :code:`Metric.compute`
z%function 'update' not implemented in r&   r'   r!   argss     r   updateMetric.update   s(     "3DNN4K4K3LAN
 	
r   c                H    [        SU R                  R                   S35      e)z?
Accumulates statistics, computes and returns the metric value
z)function 'accumulate' not implemented in r&   r'   r    s    r   
accumulateMetric.accumulate   s)    
 "78O8O7PPQR
 	
r   c                H    [        SU R                  R                   S35      e)
Returns metric name
z#function 'name' not implemented in r&   r'   r    s    r   nameMetric.name   s(    
 "1$..2I2I1J!L
 	
r   c                    U$ )a  
This API is advanced usage to accelerate metric calculating, calculations
from outputs of model to the states which should be updated by Metric can
be defined here, where Paddle OPs is also supported. Outputs of this API
will be the inputs of "Metric.update".

If :code:`compute` is defined, it will be called with **outputs**
of model and **labels** from data as arguments, all outputs and labels
will be concatenated and flatten and each filed as a separate argument
as follows:
:code:`compute(output1, output2, ..., label1, label2,...)`

If :code:`compute` is not defined, default behaviour is to pass
input to output, so output format will be:
:code:`return output1, output2, ..., label1, label2,...`

see :code:`Metric.update`
r   r.   s     r   computeMetric.compute   s	    & r   r   NreturnNone)r/   r   r=   r>   )r=   r   r=   str)r/   r   r=   r   )r*   
__module____qualname____firstlineno____doc__r"   abcabstractmethodr+   r0   r3   r7   r:   __static_attributes__r   r   r   r   r   ,   s{    Pd 	
 
 	
 
 	
 
 	
 
r   r   )	metaclassc                     ^  \ rS rSr% SrS\S'   S\S'     S         SU 4S jjjrSS jrSS	 jrSS
 jr	SS jr
SS jrSS jrSrU =r$ )Accuracy   a  
Encapsulates accuracy metric logic.

Args:
    topk (list[int]|tuple[int]): Number of top elements to look at
        for computing accuracy. Default is (1,).
    name (str|None, optional): String name of the metric instance. Default
        is `acc`.

Examples:
    .. code-block:: python
        :name: code-standalone-example

        >>> import numpy as np
        >>> import paddle

        >>> x = paddle.to_tensor(np.array([
        ...     [0.1, 0.2, 0.3, 0.4],
        ...     [0.1, 0.4, 0.3, 0.2],
        ...     [0.1, 0.2, 0.4, 0.3],
        ...     [0.1, 0.2, 0.3, 0.4]]))
        >>> y = paddle.to_tensor(np.array([[0], [1], [2], [3]]))

        >>> m = paddle.metric.Accuracy()
        >>> correct = m.compute(x, y)
        >>> m.update(correct)
        >>> res = m.accumulate()
        >>> print(res)
        0.75

    .. code-block:: python
        :name: code-model-api-example

        >>> # doctest: +TIMEOUT(80)
        >>> import paddle
        >>> from paddle.static import InputSpec
        >>> import paddle.vision.transforms as T
        >>> from paddle.vision.datasets import MNIST

        >>> input = InputSpec([None, 1, 28, 28], 'float32', 'image')
        >>> label = InputSpec([None, 1], 'int64', 'label')
        >>> transform = T.Compose([T.Transpose(), T.Normalize([127.5], [127.5])])
        >>> train_dataset = MNIST(mode='train', transform=transform)

        >>> model = paddle.Model(paddle.vision.models.LeNet(), input, label)
        >>> optim = paddle.optimizer.Adam(
        ...     learning_rate=0.001, parameters=model.parameters())
        >>> model.prepare(
        ...     optim,
        ...     loss=paddle.nn.CrossEntropyLoss(),
        ...     metrics=paddle.metric.Accuracy())
        ...
        >>> model.fit(train_dataset, batch_size=64)

Sequence[int]topkintmaxkc                   > [         TU ]  " U0 UD6  Xl        [        U5      U l        U R                  U5        U R                  5         g r   )superr"   rM   maxrO   
_init_namer+   )r!   rM   r7   r/   kwargsr)   s        r   r"   Accuracy.__init__   s<     	$)&)	I	

r   c                   [         R                  " USS9n[         R                  " U[        UR                  5      S-
  /S/U R
                  /S9n[        UR                  5      S:X  d,  [        UR                  5      S:X  a+  UR                  S   S:X  a  [         R                  " US5      nO)UR                  S   S:w  a  [         R                  " USSS	9nXR                  UR                  5      :H  n[         R                  " US
S9$ )a  
Compute the top-k (maximum value in `topk`) indices.

Args:
    pred (Tensor): The predicted value is a Tensor with dtype
        float32 or float64. Shape is [batch_size, d0, ..., dN].
    label (Tensor): The ground truth value is Tensor with dtype
        int64. Shape is [batch_size, d0, ..., 1], or
        [batch_size, d0, ..., num_classes] in one hot representation.

Return:
    Tensor: Correct mask, a tensor with shape [batch_size, d0, ..., topk].
T)
descending   r   )axesstartsendsr	   )r\   rX   )axiskeepdimfloat32dtype)paddleargsortslicelenshaperO   reshapeargmaxastypera   cast)r!   predlabelr/   corrects        r   r:   Accuracy.compute  s     ~~dt4||DJJ!+,aS		{
 !!ekk"o&:
 NN5'2E[[_!MM%b$?E,,tzz22{{7)44r   c                &   [        U[        R                  5      (       a  [        R                  " U5      n[        R
                  " [        R                  " UR                  SS 5      5      n/ n[        U R                  5       Hg  u  pVUSSU24   R                  5       nUR                  [        U5      U-  5        U R                  U==   U-  ss'   U R                  U==   U-  ss'   Mi     [        U R                  5      S:X  a  US   nU$ UnU$ )a7  
Update the metrics states (correct count and total count), in order to
calculate cumulative accuracy of all instances. This function also
returns the accuracy of current step.

Args:
    correct: Correct mask, a tensor with shape [batch_size, d0, ..., topk].

Return:
    Tensor: the accuracy of current step.
Nr\   .rX   r   )r   rb   r   r   arrayprodrf   	enumeraterM   sumappendfloattotalcountre   )r!   rm   r/   num_samplesaccsiknum_correctss           r   r0   Accuracy.update+  s     gv}}--hhw'Gggbhhw}}Sb'9:;dii(DA"37+//1LKKl+k9:JJqM\)MJJqM[(M	 )
 dii.A-tAw 48r   c                |    S/[        U R                  5      -  U l        S/[        U R                  5      -  U l        g)!
Resets all of the metric state.
        r   N)re   rM   rv   rw   r    s    r   r+   Accuracy.resetC  s0     US^+
S3tyy>)
r   c                    / n[        U R                  U R                  5       H,  u  p#US:  a  [        U5      U-  OSnUR	                  U5        M.     [        U R                  5      S:X  a  US   nU$ UnU$ )z.
Computes and returns the accumulated metric.
r   r   rX   )ziprv   rw   ru   rt   re   rM   )r!   restcrs        r   r3   Accuracy.accumulateJ  so     

DJJ/DA !Aa13AJJqM 0 DII!+c!f
 25
r   c                    U=(       d    SnU R                   S:w  a'  U R                   Vs/ s H	  o! SU 3PM     snU l        g U/U l        g s  snf )NaccrX   _top)rO   rM   _name)r!   r7   r{   s      r   rS   Accuracy._init_nameU  sG    }u99>48II>IqF$qc*I>DJDJ ?s   Ac                    U R                   $ )z!
Return name of metric instance.
r   r    s    r   r7   Accuracy.name\       zzr   )r   rw   rO   rM   rv   ))rX   N)
rM   rL   r7   
str | Noner/   r   rT   r   r=   r>   )rk   r   rl   r   r/   r   r=   r   )rm   r   r/   r   r=   r   r<   )r=   zlist[float])r7   r   r=   r>   )r=   z	list[str])r*   rA   rB   rC   rD   __annotations__r"   r:   r0   r+   r3   rS   r7   rG   __classcell__r)   s   @r   rJ   rJ      s{    6p 
I #  	
  
 5>0*	  r   rJ   c                     ^  \ rS rSr% SrS\S'   S\S'    S       SU 4S jjjr      SS jrSS jrSS	 jr	SS
 jr
SrU =r$ )	Precisionic  ag  
Precision (also called positive predictive value) is the fraction of
relevant instances among the retrieved instances. Refer to
https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers

Noted that this class manages the precision score only for binary
classification task.

Args:
    name (str, optional): String name of the metric instance.
        Default is `precision`.

Examples:
    .. code-block:: python
        :name: code-standalone-example

        >>> import numpy as np
        >>> import paddle

        >>> x = np.array([0.1, 0.5, 0.6, 0.7])
        >>> y = np.array([0, 1, 1, 1])

        >>> m = paddle.metric.Precision()
        >>> m.update(x, y)
        >>> res = m.accumulate()
        >>> print(res)
        1.0

    .. code-block:: python
        :name: code-model-api-example

        >>> import numpy as np

        >>> import paddle
        >>> import paddle.nn as nn

        >>> class Data(paddle.io.Dataset): # type: ignore[type-arg]
        ...     def __init__(self):
        ...         super().__init__()
        ...         self.n = 1024
        ...         self.x = np.random.randn(self.n, 10).astype('float32')
        ...         self.y = np.random.randint(2, size=(self.n, 1)).astype('float32')
        ...
        ...     def __getitem__(self, idx):
        ...         return self.x[idx], self.y[idx]
        ...
        ...     def __len__(self):
        ...         return self.n
        ...
        >>> model = paddle.Model(nn.Sequential(
        ...     nn.Linear(10, 1),
        ...     nn.Sigmoid()
        ... ))
        >>> optim = paddle.optimizer.Adam(
        ...     learning_rate=0.001, parameters=model.parameters())
        >>> model.prepare(
        ...     optim,
        ...     loss=nn.BCELoss(),
        ...     metrics=paddle.metric.Precision())
        ...
        >>> data = Data()
        >>> model.fit(data, batch_size=16)
rN   tpfpc                N   > [         TU ]  " U0 UD6  SU l        SU l        Xl        g Nr   )rQ   r"   r   r   r   r!   r7   r/   rT   r)   s       r   r"   Precision.__init__  s*     	$)&)
r   c                \   [        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      e[        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      eUR                  S   n[        R                  " US-   5      R                  S5      n[        U5       HD  nX   nX$   nUS:X  d  M  XV:X  a  U =R                  S-  sl        M/  U =R                  S-  sl        MF     g)a  
Update the states based on the current mini-batch prediction results.

Args:
    preds (numpy.ndarray): The prediction result, usually the output
        of two-class sigmoid function. It should be a vector (column
        vector or row vector) with data type: 'float64' or 'float32'.
    labels (numpy.ndarray): The ground truth (labels),
        the shape should keep the same as preds.
        The data type is 'int32' or 'int64'.
.The 'preds' must be a numpy ndarray or Tensor./The 'labels' must be a numpy ndarray or Tensor.r   g      ?int32rX   N)r   rb   r   r   rp   r   
ValueErrorrf   floorri   ranger   r   r!   predslabels
sample_numrz   rk   rl   s          r   r0   Precision.update  s      eV]]++HHUOEE""MNNffmm,,XXf%FF##NOO\\!_
%,,W5z"A8DIEqy=GGqLGGGqLG #r   c                     SU l         SU l        gr   r   N)r   r   r    s    r   r+   Precision.reset       r   c                t    U R                   U R                  -   nUS:w  a  [        U R                   5      U-  $ S$ )zc
Calculate the final precision.

Returns:
    A scaler float: results of the calculated precision.
r   r   )r   r   ru   )r!   aps     r   r3   Precision.accumulate  s4     WWtww&(AguTWW~"636r   c                    U R                   $ r6   r   r    s    r   r7   Precision.name  r   r   )r   r   r   )	precisionr7   r@   r/   r   rT   r   r=   r>   r   z-npt.NDArray[np.float32 | np.float64] | Tensorr   z)npt.NDArray[np.int32 | np.int64] | Tensorr=   r>   r<   r=   ru   r?   )r*   rA   rB   rC   rD   r   r"   r0   r+   r3   r7   rG   r   r   s   @r   r   r   c  sz    >@ 	GG &.1=@	 $!<$! :$! 
	$!L7 r   r   c                  ~   ^  \ rS rSr% SrS\S'   S\S'   SSU 4S jjjr      SS jrSS jrSS	 jr	SS
 jr
SrU =r$ )Recalli  a  
Recall (also known as sensitivity) is the fraction of
relevant instances that have been retrieved over the
total amount of relevant instances

Refer to:
https://en.wikipedia.org/wiki/Precision_and_recall

Noted that this class manages the recall score only for
binary classification task.

Args:
    name (str, optional): String name of the metric instance.
        Default is `recall`.

Examples:
    .. code-block:: python
        :name: code-standalone-example

        >>> import numpy as np
        >>> import paddle

        >>> x = np.array([0.1, 0.5, 0.6, 0.7])
        >>> y = np.array([1, 0, 1, 1])

        >>> m = paddle.metric.Recall()
        >>> m.update(x, y)
        >>> res = m.accumulate()
        >>> print(res)
        0.6666666666666666

    .. code-block:: python
        :name: code-model-api-example

        >>> import numpy as np

        >>> import paddle
        >>> import paddle.nn as nn

        >>> class Data(paddle.io.Dataset): # type: ignore[type-arg]
        ...     def __init__(self):
        ...         super().__init__()
        ...         self.n = 1024
        ...         self.x = np.random.randn(self.n, 10).astype('float32')
        ...         self.y = np.random.randint(2, size=(self.n, 1)).astype('float32')
        ...
        ...     def __getitem__(self, idx):
        ...         return self.x[idx], self.y[idx]
        ...
        ...     def __len__(self):
        ...         return self.n
        ...
        >>> model = paddle.Model(nn.Sequential(
        ...     nn.Linear(10, 1),
        ...     nn.Sigmoid()
        ... ))
        >>> optim = paddle.optimizer.Adam(
        ...     learning_rate=0.001, parameters=model.parameters())
        >>> model.prepare(
        ...     optim,
        ...     loss=nn.BCELoss(),
        ...     metrics=[paddle.metric.Precision(), paddle.metric.Recall()])
        ...
        >>> data = Data()
        >>> model.fit(data, batch_size=16)
rN   r   fnc                N   > [         TU ]  " U0 UD6  SU l        SU l        Xl        g r   )rQ   r"   r   r   r   r   s       r   r"   Recall.__init__4  s(    $)&)
r   c                V   [        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      e[        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      eUR                  S   n[        R                  " U5      R                  S5      n[        U5       HD  nX   nX$   nUS:X  d  M  XV:X  a  U =R                  S-  sl        M/  U =R                  S-  sl        MF     g)a  
Update the states based on the current mini-batch prediction results.

Args:
    preds(numpy.array): prediction results of current mini-batch,
        the output of two-class sigmoid function.
        Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'.
    labels(numpy.array): ground truth (labels) of current mini-batch,
        the shape should keep the same as preds.
        Shape: [batch_size, 1], Dtype: 'int32' or 'int64'.
r   r   r   r   rX   N)r   rb   r   r   rp   r   r   rf   rintri   r   r   r   r   s          r   r0   Recall.update:  s      eV]]++HHUOEE""MNNffmm,,XXf%FF##NOO\\!_
%%g.z"A8DIEz=GGqLGGGqLG #r   c                t    U R                   U R                  -   nUS:w  a  [        U R                   5      U-  $ S$ )z]
Calculate the final recall.

Returns:
    A scaler float: results of the calculated Recall.
r   r   )r   r   ru   )r!   recalls     r   r3   Recall.accumulate`  s4     477"*0A+uTWW~&>3>r   c                     SU l         SU l        gr   )r   r   r    s    r   r+   Recall.resetj  r   r   c                    U R                   $ r   r   r    s    r   r7   Recall.nameq  r   r   )r   r   r   )r   r   r   r   r<   r?   )r*   rA   rB   rC   rD   r   r"   r0   r3   r+   r7   rG   r   r   s   @r   r   r     sV    AF 	GG $!<$! :$! 
	$!L? r   r   c                     ^  \ rS rSrSr   S
           SU 4S jjjr      SS jr\SS j5       rSS jr	SS jr
SS jrS	rU =r$ )Aucix  a@  
The auc metric is for binary classification.
Refer to https://en.wikipedia.org/wiki/Receiver_operating_characteristic#Area_under_the_curve.
Please notice that the auc metric is implemented with python, which may be a little bit slow.

The `auc` function creates four local variables, `true_positives`,
`true_negatives`, `false_positives` and `false_negatives` that are used to
compute the AUC. To discretize the AUC curve, a linearly spaced set of
thresholds is used to compute pairs of recall and precision values. The area
under the ROC-curve is therefore computed using the height of the recall
values by the false positive rate, while the area under the PR-curve is the
computed using the height of the precision values by the recall.

Args:
    curve (str): Specifies the mode of the curve to be computed,
        'ROC' or 'PR' for the Precision-Recall-curve. Default is 'ROC'.
    num_thresholds (int): The number of thresholds to use when
        discretizing the roc curve. Default is 4095.
    name (str, optional): String name of the metric instance. Default
        is `auc`.

"NOTE: only implement the ROC curve type via Python now."

Examples:
    .. code-block:: python
        :name: code-standalone-example

        >>> import numpy as np
        >>> import paddle

        >>> m = paddle.metric.Auc()

        >>> n = 8
        >>> class0_preds = np.random.random(size = (n, 1))
        >>> class1_preds = 1 - class0_preds

        >>> preds = np.concatenate((class0_preds, class1_preds), axis=1)
        >>> labels = np.random.randint(2, size = (n, 1))

        >>> m.update(preds=preds, labels=labels)
        >>> res = m.accumulate()

    .. code-block:: python
        :name: code-model-api-example

        >>> import numpy as np
        >>> import paddle
        >>> import paddle.nn as nn

        >>> class Data(paddle.io.Dataset): # type: ignore[type-arg]
        ...     def __init__(self):
        ...         super().__init__()
        ...         self.n = 1024
        ...         self.x = np.random.randn(self.n, 10).astype('float32')
        ...         self.y = np.random.randint(2, size=(self.n, 1)).astype('int64')
        ...
        ...     def __getitem__(self, idx):
        ...         return self.x[idx], self.y[idx]
        ...
        ...     def __len__(self):
        ...         return self.n
        ...
        >>> model = paddle.Model(nn.Sequential(
        ...     nn.Linear(10, 2), nn.Softmax())
        ... )
        >>> optim = paddle.optimizer.Adam(
        ...     learning_rate=0.001, parameters=model.parameters())
        ...
        >>> def loss(x, y):
        ...     return nn.functional.nll_loss(paddle.log(x), y)
        ...
        >>> model.prepare(
        ...     optim,
        ...     loss=loss,
        ...     metrics=paddle.metric.Auc())
        >>> data = Data()
        >>> model.fit(data, batch_size=16)
c                   > [         TU ]  " U0 UD6  Xl        X l        US-   n[        R
                  " U5      U l        [        R
                  " U5      U l        X0l        g )NrX   )	rQ   r"   _curve_num_thresholdsr   zeros	_stat_pos	_stat_negr   )r!   curvenum_thresholdsr7   r/   rT   _num_pred_bucketsr)   s          r   r"   Auc.__init__  sT     	$)&)-*Q."34"34
r   c                :   [        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      e[        U[        R                  5      (       a  [        R                  " U5      nO[        U5      (       d  [        S5      e[        U5       Hj  u  p4XS4   n[        XPR                  -  5      nX`R                  ::  d   eU(       a  U R                  U==   S-  ss'   MS  U R                  U==   S-  ss'   Ml     g)a  
Update the auc curve with the given predictions and labels.

Args:
    preds (numpy.array): An numpy array in the shape of
        (batch_size, 2), preds[i][j] denotes the probability of
        classifying the instance i into the class j.
    labels (numpy.array): an numpy array in the shape of
        (batch_size, 1), labels[i] is either o or 1,
        representing the label of the instance i.
r   r   rX   g      ?N)r   rb   r   r   rp   r   r   rr   rN   r   r   r   )r!   r   r   rz   lblvaluebin_idxs          r   r0   
Auc.update  s      ffmm,,XXf%FF##NOOeV]]++HHUOEE""MNN'FAQ$KE%"6"667G22222w'3.'w'3.' (r   c                ,    [        X-
  5      X#-   -  S-  $ )Ng       @)abs)x1x2y1y2s       r   trapezoid_areaAuc.trapezoid_area  s    27|rw'#--r   c                    SnSnSnU R                   nUS:  aG  UnUnXR                  U   -  nX R                  U   -  nX0R                  X&X5      -  nUS-  nUS:  a  MG  US:  a  US:  a  X1-  U-  $ S$ )z^
Return the area (a float score) under auc curve

Return:
    float: the area under auc curve
r   r   rX   )r   r   r   r   )r!   tot_postot_negaucidxtot_pos_prevtot_neg_prevs          r   r3   Auc.accumulate   s     ""Qh"L"L~~c**G~~c**G&&w C 1HC Qh (/}3CMG#	
LO	
r   c                    U R                   S-   n[        R                  " U5      U l        [        R                  " U5      U l        g)r%   rX   N)r   r   r   r   r   )r!   r   s     r   r+   	Auc.reset  s7     !0014"34"34r   c                    U R                   $ r   r   r    s    r   r7   Auc.name"  r   r   )r   r   r   r   r   )ROCi  r   )r   zLiteral['ROC', 'PR']r   rN   r7   r@   r/   r   rT   r   r=   r>   r   )
r   ru   r   ru   r   ru   r   ru   r=   ru   r   r<   r?   )r*   rA   rB   rC   rD   r"   r0   staticmethodr   r3   r+   r7   rG   r   r   s   @r   r   r   x  s    Mb ',"	#  	
   
 "!/<!/ :!/ 
	!/F . .
45 r   r   c                   UR                   [        R                  :X  a%  [        R                  " U[        R                  5      n[        5       (       aL  Uc	  [        SS9nUc	  [        SS9n[        R                  " XS9u  pg[        R                  " XgXU5      u  n  n	U$ [        5       (       a3  [        R                  " XS9u  pg[        R                  " XgU5      u  n  n	U$ [        S0 [        5       D6n
[        U S/ SQS5        [        R                  " XS9u  pgU
R                  SS9nUc  U
R                  SS9nUc  U
R                  SS9nU
R!                  SU/U/U/S.U/U/U/S	.S
9  U$ )aO  
accuracy layer.
Refer to the https://en.wikipedia.org/wiki/Precision_and_recall

This function computes the accuracy using the input and label.
If the correct label occurs in top k predictions, then correct will increment by one.
Note: the dtype of accuracy is determined by input. the input and label dtype can be different.

Args:
    input(Tensor): The input of accuracy layer, which is the predictions of network. A Tensor with type float32,float64.
        The shape is ``[sample_number, class_dim]`` .
    label(Tensor): The label of dataset. Tensor with type int64 or int32. The shape is ``[sample_number, 1]`` .
    k(int, optional): The top k predictions for each class will be checked. Data type is int64 or int32.
    correct(Tensor, optional): The correct predictions count. A Tensor with type int64 or int32.
    total(Tensor, optional): The total entries count. A tensor with type int64 or int32.
    name(str|None, optional): The default value is None. Normally there is no need for
        user to set this property. For more information, please refer to :ref:`api_guide_Name`

Returns:
    Tensor, the correct rate. A Tensor with type float32.

Examples:
    .. code-block:: python

        >>> import paddle

        >>> predictions = paddle.to_tensor([[0.2, 0.1, 0.4, 0.1, 0.1], [0.2, 0.3, 0.1, 0.15, 0.25]], dtype='float32')
        >>> label = paddle.to_tensor([[2], [0]], dtype="int64")
        >>> result = paddle.metric.accuracy(input=predictions, label=label, k=1)
        >>> print(result)
        Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
        0.50000000)
r   r`   )r{   accuracyinput)float16uint16r_   float64r_   )OutIndicesLabel)rJ   CorrectTotal)typeinputsoutputs)r   )ra   rb   r   rj   int64r   r   rM   r   r   r   r   r   localsr
   "create_variable_for_type_inference	append_op)r   rl   r{   rm   rv   r7   topk_outtopk_indices_acc_helperacc_outs               r   r   r   )  sp   R {{fll"E6<<0?$73G="1E!'U!8"++EE

a 	!'U!8__XUC
a0vx0FwCZ $[[4H77i7HG;;';J}999H
 z|nwO 	yW
   Nr   )rX   NNN)r   r   rl   r   r{   rN   rm   Tensor | Nonerv   r  r7   r   r=   r   )#
__future__r   rE   typingr   r   r   numpyr   rb   r   r   base.data_feederr
   base.frameworkr   r   base.layer_helperr   	frameworkr   collections.abcr   numpy.typingnptr   __all__r   ABCMetar   rJ   r   r   r   r   r   r   r   <module>r     s    # 
 . .   ( 7 8 + '( 5Ts{{ Tn]v ]@G GTHV HVn& nh !OOO O 	O
 O O Or   