
    {-jcY                         d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	m
Z
mZmZ ddlmZ ddlmZ g Zdd	Z	 	 	 	 	 ddZddZdS )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)ConstantInitializer   c                    t                      r|t          d          }|t          d          }t          |t                    r't	          j        |                              d          n|}t          j        | d|dd          \  }}t          j	        |||||          \  }}	}	|S t                      r6t          j        | |d          \  }}t          j	        |||          \  }}	}	|S t          di t                      }
t!          | d
g dd	           |
                    | j                  }|
                    d          }d| gi}t          |t                    r|g|d<   nd|i}d|d<   |
                    d|||g|gd           |
                    d          }||
                    d          }||
                    d          }|
                    d	|g|g|gd|g|g|gd           |S )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)]

    N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.11/site-packages/paddle/static/nn/metric.pyr   r   #   sz   `  ?$7333G="111E$.q($;$;BRXa[[a   !.!73He"
 "
, #+lE7E
 

a 	 !'Ua!F!F!F,_X|UCC
a00vxx00FwCCCZ   88u{8KKH<<7<KKLE7^F!X csaE(O
!
~>>	     77i7HHG;;';JJ}999HH
 z|nwOO 	yW
 
     N    ROC  c           
         t                      r|t          j        ddgdd          }t          | dddgd           t          |d	d
dgd           t          |dddgd           t          j        d|dz   gd          }t          j        d|dz   gd          }t          j        | ||||||d          \  }	}
}|	|
|fS t          di t                      }|$t          j	        
                    ddgdd          }t          | dddgd           t          |d	d
dgd           t          |dddgd           |                    d          }	|                    d          }|                    ddd|z   |dz   z  dz   g          }
|                    ddd|z   |dz   z  dz   g          }|                    ddd|dz   g          }|                    ddd|dz   g          }|
|||fD ]'}|                    |t          dd                     (|                    d| g|g|
g|gd|||d|g|
g|gd           |                    d| g|g|g|gd||dd|	g|g|gd           |	||
|||gfS )a5  
    **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.)]

    Nr   r         ?)shaper   
fill_valuer   r   aucr2   r   r   ins_tag_weight)rB   r   r   rB   r   valuer   Tpersistabler   rB           FrG   	force_cpu)Predictr$   StatPosStatNeg)curvenum_thresholdsslide_steps)AUC
StatPosOut
StatNegOutr   )rD   )r	   r-   fullr   zerosr   rD   r
   r/   tensorfill_constantr0   create_global_variableset_variable_initializerr   r1   )r   r2   rP   rQ   r.   rR   rE   stat_posstat_negauc_outbatch_stat_posbatch_stat_negr:   batch_auc_outvars                  r<   rD   rD      s   d }} 
!#[!fI#  N 	!)Y1GOOO '71CUKKK ,y).De	
 	
 	
 <q.1*<&=WMMM<q.1*<&=WMMM28*	3
 	3
/ 
 	

 ++&((++F44a&	 5 
 
 UGi-CUKKKUGgw-?GGG(9i*@%   77i7HHG==I=N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;;;	
 	
 	
 	
 wW&'&'	
 
 ,&
 
 "?)*)*
 
    ( wW z z	
 
 ,
 
 9#*#*
 
    ( 		8< r=   c                 	   |$t           j                            ddgdd          }| j        |j        k    sJ t	          d"i t                      }|                    dddg          }|                    dddg          }|                    dddg          }|                    dddg          }|                    dddg          }|                    dddg          }	|                    d	dd
g          }
|                    d	dd
g          }|                    d	dd
g          }|                    d	ddg          }|                    d	ddg          }|                    d	ddg          }|                    d	ddg          }|                    d	ddg          }|                    d	ddg          }||||||||||||	fD ]<}|                    |t           j        j	        
                    dd                     =|                    d| g|gdd|
gi           |                    dd|
gid|gi           |                    d|g|gdd|gi           |                    dd|
gid|gi           |                    d|g|gdd|gi           |                    dd| gid|gi           |                    d|g|gdd|gi           |                    dd| gid|gi           |                    dd|gid|gi           |                    dd|gid|gi           |                    d|g|gdd|gi           |                    dd|id|gid
dg|j        dd           |                    dd|gid|gi           d|i}ddgi}dg|d<   dg|d<   |                    d||d|i           |j                            d d          }|                    d!|g|gdd|gid |i           |                    d|g|	gdd|	gi           |                    d!|g|gdd|gid |i           |                    d|g|gdd|gi           ||||||	fS )#a  
    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)
    Nr   r   rA   rF   ctr_metric_bundleTrH   FrJ   rK   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)rd   )r-   rX   rY   rB   r
   r/   rZ   r[   nninitializerr   r1   r   kwargsget)r   r2   rE   r:   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_numrb   inputs_slicer"   rs   s                          r<   rd   rd   u  s~   r 44a&	 5 
 
 ;%+%%%%99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 	 
 
 	''I!55T 6  	
 	
 	
 	
 WE7++()     n%&'    
 "^<.99'     n%&'    
 "^<.99'     3.5:,:O      \55%    
 eW~)*    
 o&'	"     eW~(    
 #_M?;;(     ,
#!W^
 
	  	 	 	 hZ (     ^,LaSMEcE(OCE&M
'	     =VQ''D
#_N+;<<(tn	     #_M?;;(     Yn%566	"tn	     YgY//	"     	 r=   )r   NN)r>   r?   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   rD   rd    r=   r<   <module>r      s         ( ( ( ( ( ( ( ( < < < < < <            1 0 0 0 0 0 5 5 5 5 5 5
c c c cR 	
i i i iX| | | | | |r=   