
    ёicY                         S 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
JrJr  SSKJr  SSKJr  / rSS jr     SS	 jrSS
 jrg)z$
All layers just related to metric.
    N)_C_ops_legacy_C_ops)check_variable_and_dtype)Variable_create_tensorin_dygraph_modein_pir_mode)LayerHelper)ConstantInitializerc                    [        5       (       a  Uc	  [        SS9nUc	  [        SS9n[        U[        5      (       a%  [        R
                  " U5      R                  S5      OUn[        R                  " U SUSS5      u  pg[        R                  " XgXU5      u  n  n	U$ [        5       (       a4  [        R                  " XSS9u  pg[        R                  " XgU5      u  n  n	U$ [        S0 [        5       D6n
[!        U S	/ S
QS5        U
R#                  U R$                  S9nU
R#                  SS9nSU /0n[        U[        5      (       a  U/US'   OSU0nSWS'   U
R'                  SUUU/U/S.S9  U
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$ )a  

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 int32,int64. 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. Default is 1.
    correct(Tensor, optional): The correct predictions count. A Tensor with type int64 or int32. Default is None.
    total(Tensor, optional): The total entries count. A tensor with type int64 or int32. Default is None.

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

Examples:
    .. code-block:: python

        >>> import numpy as np
        >>> import paddle
        >>> import paddle.static as static
        >>> import paddle.nn.functional as F
        >>> paddle.seed(2023)
        >>> paddle.enable_static()
        >>> data = static.data(name="input", shape=[-1, 32, 32], dtype="float32")
        >>> label = static.data(name="label", shape=[-1,1], dtype="int64")
        >>> fc_out = static.nn.fc(x=data, size=10)
        >>> predict = F.softmax(x=fc_out)
        >>> result = static.accuracy(input=predict, label=label, k=5)
        >>> place = paddle.CPUPlace()
        >>> exe = static.Executor(place)
        >>> exe.run(static.default_startup_program())
        >>> np.random.seed(1107)
        >>> x = np.random.rand(3, 32, 32).astype("float32")
        >>> y = np.array([[1],[0],[1]])
        >>> output = exe.run(feed={"input": x,"label": y},
        ...                  fetch_list=[result])
        >>> print(output)
        [array(0.33333334, dtype=float32)]

int32dtyper   ksortedF)r   r   accuracyinput)float16uint16float32float64int64XKtop_k_v2)OutIndicestypeinputsattrsoutputsr   )r   r   Label)AccuracyCorrectTotalr   r    r"   )r   )r   r   
isinstancer   nparrayitemr   r   r   r	   paddletopkr   r
   localsr   "create_variable_for_type_inferencer   	append_op)r   labelr   correcttotal_ktopk_outtopk_indices_acc_helperr    r!   acc_outs                 W/var/www/html/banglarbhumi/venv/lib/python3.13/site-packages/paddle/static/nn/metric.pyr   r   #   s   ` ?$73G="1E$.q($;$;RXXa[a !.!7!73He"
 #++EE

a 	!'U!F__XUC
a0vx0FwCZ 88u{{8KH<<7<KLE7^F!XcsaE(O
!
~>	   77i7HG;;';J}999H
 z|nwO 	yW
   N    c           
      2   [        5       (       a  Uc  [        R                  " SS/SSS9n[        U SSS/S5        [        USS	S
/S5        [        USSS/S5        [        R                  " SUS-   /S
S9n[        R                  " SUS-   /S
S9n[
        R                  " U UUUUUUS5      u  pnU	U
U4$ [        S0 [        5       D6nUc!  [        R                  R                  SS/SSS9n[        U SSS/S5        [        USS	S
/S5        [        USSS/S5        UR                  SS9n	UR                  SS9nUR                  SS
SU-   US-   -  S-   /S9n
UR                  SS
SU-   US-   -  S-   /S9nUR                  SS
SUS-   /S9nUR                  SS
SUS-   /S9nXXx4 H  nUR                  U[        SSS95        M     UR                  SU /U/U
/U/S.UUUS.U/U
/U/S.S9  UR                  SU /U/U/U/S.UUSS.U	/U/U/S.S9  U	UXXx/4$ )a  
**Area Under the Curve (AUC) Layer**

This implementation computes the AUC according to forward output and label.
It is used very widely in binary classification evaluation.

Note: If input label contains values other than 0 and 1, it will be cast
to `bool`. Find the relevant definitions `here <https://en.wikipedia.org    /wiki/Receiver_operating_characteristic#Area_under_the_curve>`_.

There are two types of possible curves:

    1. ROC: Receiver operating characteristic;
    2. PR: Precision Recall

Args:
    input(Tensor): A floating-point 2D Tensor, values are in the range
                     [0, 1]. Each row is sorted in descending order. This
                     input should be the output of topk. Typically, this
                     Tensor indicates the probability of each label.
                     A Tensor with type float32,float64.
    label(Tensor): A 2D int Tensor indicating the label of the training
                     data. The height is batch size and width is always 1.
                     A Tensor with type int32,int64.
    curve(str, optional): Curve type, can be 'ROC' or 'PR'. Default 'ROC'.
    num_thresholds(int, optional): The number of thresholds to use when discretizing
                         the roc curve. Default 4095.
    topk(int, optional): only topk number of prediction output will be used for auc.
    slide_steps(int, optional): when calc batch auc, we can not only use step currently but the previous steps can be used. slide_steps=1 means use the current step, slide_steps=3 means use current step and the previous second steps, slide_steps=0 use all of the steps.
    ins_tag_weight(Tensor, optional): A 2D int Tensor indicating the data's tag weight, 1 means real data, 0 means fake data. Default None, and it will be assigned to a tensor of value 1.
                     A Tensor with type float32,float64.

Returns:
    Tensor: A tuple representing the current AUC. Data type is Tensor, supporting float32, float64.
    The return tuple is auc_out, batch_auc_out, [batch_stat_pos, batch_stat_neg, stat_pos, stat_neg ]

        auc_out: the result of the accuracy rate
        batch_auc_out: the result of the batch accuracy
        batch_stat_pos: the statistic value for label=1 at the time of batch calculation
        batch_stat_neg: the statistic value for label=0 at the time of batch calculation
        stat_pos: the statistic for label=1 at the time of calculation
        stat_neg: the statistic for label=0 at the time of calculation


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

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import numpy as np
        >>> paddle.enable_static()

        >>> paddle.seed(2023)
        >>> data = paddle.static.data(name="input", shape=[-1, 32,32], dtype="float32")
        >>> label = paddle.static.data(name="label", shape=[-1], dtype="int64")
        >>> fc_out = paddle.static.nn.fc(x=data, size=2)
        >>> predict = paddle.nn.functional.softmax(x=fc_out)
        >>> result=paddle.static.auc(input=predict, label=label)

        >>> place = paddle.CPUPlace()
        >>> exe = paddle.static.Executor(place)

        >>> exe.run(paddle.static.default_startup_program())
        >>> np.random.seed(1107)
        >>> x = np.random.rand(3,32,32).astype("float32")
        >>> y = np.array([1,0,1])
        >>> output= exe.run(feed={"input": x,"label": y},
        ...                 fetch_list=[result[0]])
        >>> print(output)
        [array(1.)]


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

        # you can learn the usage of ins_tag_weight by the following code.

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> import numpy as np
        >>> paddle.enable_static()

        >>> paddle.seed(2023)
        >>> data = paddle.static.data(name="input", shape=[-1, 32,32], dtype="float32")
        >>> label = paddle.static.data(name="label", shape=[-1], dtype="int64")
        >>> ins_tag_weight = paddle.static.data(name='ins_tag_weight', shape=[-1,16], dtype='float64')
        >>> fc_out = paddle.static.nn.fc(x=data, size=2)
        >>> predict = paddle.nn.functional.softmax(x=fc_out)
        >>> result=paddle.static.auc(input=predict, label=label, ins_tag_weight=ins_tag_weight)

        >>> place = paddle.CPUPlace()
        >>> exe = paddle.static.Executor(place)

        >>> exe.run(paddle.static.default_startup_program())
        >>> np.random.seed(1107)
        >>> x = np.random.rand(3,32,32).astype("float32")
        >>> y = np.array([1,0,1])
        >>> z = np.array([1,0,1]).astype("float64")
        >>> output= exe.run(feed={"input": x,"label": y, "ins_tag_weight":z},
        ...                 fetch_list=[result[0]])
        >>> print(output)
        [array(1.)]

   r         ?)shaper   
fill_valuer   r   aucr1   r   r   ins_tag_weight)r@   r   r   r@   r   valuer   Tpersistabler   r@           FrE   	force_cpu)Predictr#   StatPosStatNeg)curvenum_thresholdsslide_steps)AUC
StatPosOut
StatNegOutr   )rB   )r	   r,   fullr   zerosr   rB   r
   r.   tensorfill_constantr/   create_global_variableset_variable_initializerr   r0   )r   r1   rN   rO   r-   rP   rC   stat_posstat_negauc_outbatch_stat_posbatch_stat_negr9   batch_auc_outvars                  r;   rB   rB      s7   d }}!#[[!fI#N 	!)Y1GO '71CUK ,y).De	
 <<q.1*<&=WM<<q.1*<&=WM28**	3
/ 
 	

 +&(+F44a&	 5 
 UGi-CUKUGgw-?G(9i*@% 77i7HG==I=NM 22KNQ$67!;< 3 N
 22KNQ$67!;< 3 N ,,>A3E/F - H ,,>A3E/F - H C''cU;	
 D wW&'&'	
 ,&
 "?)*)*
  ( wW z z	
 ,
 9#*#*
  ( 		< r<   c                 V   Uc!  [         R                  R                  SS/SSS9nU R                  UR                  :X  d   e[	        S 0 [        5       D6nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9n	UR                  SSS/S9n
UR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUR                  SSS/S9nUUUUUUUUUUUU	4 H;  nUR                  U[         R                  R                  R                  S	SS
95        M=     UR                  SU /U/S.SU
/0S9  UR                  SSU
/0SU/0S9  UR                  SU/U/S.SU/0S9  UR                  SSU
/0SU/0S9  UR                  SU/U/S.SU/0S9  UR                  SSU /0SU/0S9  UR                  SU/U/S.SU/0S9  UR                  SSU /0SU/0S9  UR                  SSU/0SU/0S9  UR                  SSU/0SU/0S9  UR                  SU/U/S.SU/0S9  UR                  SSU0SU/0SS/UR                  SS.S9  UR                  SSU/0SU/0S9  SU0nSS/0nS/US'   S/US'   UR                  SUUSU0S9  UR                  R                  SS5      nUR                  SU/U/S.SU/0SU0S9  UR                  SU/U	/S.SU	/0S9  UR                  SU/U/S.SU/0SU0S9  UR                  SU/U/S.SU/0S9  UUUUUU	4$ )!aU
  
ctr related metric layer

This function help compute the ctr related metrics: RMSE, MAE, predicted_ctr, q_value.
To compute the final values of these metrics, we should do following computations using
total instance number:
MAE = local_abserr / instance number
RMSE = sqrt(local_sqrerr / instance number)
predicted_ctr = local_prob / instance number
q = local_q / instance number
Note that if you are doing distribute job, you should all reduce these metrics and instance
number first

Args:
    input(Tensor): A floating-point 2D Tensor, values are in the range
                     [0, 1]. Each row is sorted in descending order. This
                     input should be the output of topk. Typically, this
                     Tensor indicates the probability of each label.
    label(Tensor): A 2D int Tensor indicating the label of the training
                     data. The height is batch size and width is always 1.
    ins_tag_weight(Tensor): A 2D int Tensor indicating the ins_tag_weight of the training
                     data. 1 means real data, 0 means fake data.
                     A DenseTensor or Tensor with type float32,float64.

Returns:
    local_sqrerr(Tensor): Local sum of squared error
    local_abserr(Tensor): Local sum of abs error
    local_prob(Tensor): Local sum of predicted ctr
    local_q(Tensor): Local sum of q value
    local_pos_num (Tensor): Local number of positive examples
    local_ins_num (Tensor): Local number of instances

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

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> paddle.enable_static()
        >>> data = paddle.static.data(name="data", shape=[-1, 32], dtype="float32")
        >>> label = paddle.static.data(name="label", shape=[-1, 1], dtype="int32")
        >>> predict = paddle.nn.functional.sigmoid(paddle.static.nn.fc(x=data, size=1))
        >>> auc_out = paddle.static.ctr_metric_bundle(input=predict, label=label)

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

        >>> # doctest: +SKIP("This has diff in xdoctest env")
        >>> import paddle
        >>> paddle.enable_static()
        >>> data = paddle.static.data(name="data", shape=[-1, 32], dtype="float32")
        >>> label = paddle.static.data(name="label", shape=[-1, 1], dtype="int32")
        >>> predict = paddle.nn.functional.sigmoid(paddle.static.nn.fc(x=data, size=1))
        >>> ins_tag_weight = paddle.static.data(name='ins_tag_weight', shape=[-1, 1], dtype='int64')
        >>> auc_out = paddle.static.ctr_metric_bundle(input=predict, label=label, ins_tag_weight=ins_tag_weight)
r>   r   r?   rD   TrF   FrH   rI   elementwise_sub)r   Yr   r'   squared_l2_normr   elementwise_addl1_norm
reduce_sumsigmoidfill_constant_batch_size_likeInput)r   r    r"   r!   axesr   startsendsslicer   axiselementwise_mul)ctr_metric_bundle)r,   rV   rW   r@   r
   r.   rX   rY   nninitializerr   r0   r   kwargsget)r   r1   rC   r9   local_abserrlocal_sqrerr
local_problocal_qlocal_pos_numlocal_ins_numtmp_res_elesubtmp_res_sigmoidtmp_ones
batch_probbatch_abserrbatch_sqrerrbatch_qbatch_pos_numbatch_ins_numr`   inputs_slicer!   rp   s                          r;   rr   rr   u  sB   r 44a&	 5 
 ;;%++%%%99F00	! 1 L 00	! 1 L ..	! / J ++	! , G 11	! 2 M 11	! 2 M 222$ 3 N 332$ 4 O ,,2$ - H ..1# / J 001# 1 L 001# 1 L ++1# , G 111# 2 M 111# 2 M 	 	''II!!55T 6 	
* WE7+()   n%&'  
 "^<.9'   n%&'  
 "^<.9'   3.5:,:O    \5%  
 eW~)*  
 o&'	"   eW~(  
 #_M?;(   ,
#!W^^
	  	 hZ (   ^,LaSMEcE(OCE&M
'	   ==VQ'D
#_N+;<(tn	   #_M?;(   Yn%56	"tn	   YgY/	"   	 r<   )r>   NN)ROCi  r>   r>   N)N)__doc__numpyr)   r,   r   r   paddle.base.data_feederr   paddle.base.frameworkr   r   r   r	   paddle.base.layer_helperr
   paddle.nn.initializerr   __all__r   rB   rr    r<   r;   <module>r      sT      ( <  1 5
cR 	
iX|r<   