Ë
    –\;j„V  ã                   óŠ   — 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y)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                 ó�  — t        «       r�|€t        d¬«      }|€t        d¬«      }t        |t        «      r$t	        j
                  |«      j                  d«      n|}t        j                  | d|dd«      \  }}t        j                  |||||«      \  }}	}	|S t        «       r8t        j                  | |d¬«      \  }}t        j                  |||«      \  }}	}	|S t        di t        «       ¤Ž}
t!        | d	g d
¢d«       |
j#                  | j$                  ¬«      }|
j#                  d¬«      }d| gi}t        |t        «      r|g|d<   nd|i}dd<   |
j'                  d|||g|gdœ¬«       |
j#                  d¬«      }|€|
j#                  d¬«      }|€|
j#                  d¬«      }|
j'                  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="int")
            >>> 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                 ú`G:\00. PROJECTS\API\Inventory\templateJSON\kerjaOCR\Lib\site-packages\paddle/static/nn/metric.pyr   r   "   sü  € ô` ÔØˆ?Ü$¨7Ô3ˆGØˆ=Ü"¨Ô1ˆEä$.¨q´(Ô$;ŒR�X‰X�a‹[×Ñ˜aÔ ÀˆÜ!.×!7Ñ!7Ø�3˜˜H eó"
Ñˆ�,ô #×+Ñ+Ø�l E¨7°Eó
‰
ˆˆa�ð ˆÜ	ŒÜ!'§¡¨U°aÀÔ!FÑˆ�,Ü—_‘_ X¨|¸UÓC‰
ˆˆa�ØˆäÑ0¤v£xÑ0€FÜØˆwÒCÀZôð ×8Ñ8¸u¿{¹{Ð8ÓK€HØ×<Ñ<À7Ð<ÓK€LØ�E�7ˆ^€FÜ�!”XÔØ�cˆˆsŠà�a�ˆØ€Eˆ(�OØ
×ÑØØØØ!˜
°¨~Ñ>ð	 ô ð ×7Ñ7¸iÐ7ÓH€GØ€Ø×;Ñ;À'Ð;ÓJˆØ€}Ø×9Ñ9ÀÐ9ÓHˆØ
×ÑØØ �z¨|¨nÈÀwÑOà ˜	Ø�yØ�Wñ
ð ô ð €Nó    c           	      ó
  — t        di t        «       ¤Ž}|€$t        j                  j	                  ddgdd¬«      }t        | dddgd«       t        |dd	d
gd«       t        |dddgd«       |j                  d¬«      }|j                  d¬«      }	|j                  dd
d|z   |dz   z  dz   g¬«      }
|j                  dd
d|z   |dz   z  dz   g¬«      }|j                  dd
d|dz   g¬«      }|j                  dd
d|dz   g¬«      }|
|||fD ]  }|j                  |t        dd¬«      «       Œ! |j                  d| g|g|
g|gdœ|||dœ|	g|
g|gdœ¬«       |j                  d| g|g|g|gdœ||ddœ|g|g|gdœ¬«       ||	|
|||gfS )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

            >>> 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="int")
            >>> 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.

            >>> 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="int")
            >>> ins_tag_weight = paddle.static.data(name='ins_tag_weight', shape=[-1,16], lod_level=0, 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.)]

    Úaucé   r   ç      ð?©Úshaper   Úvaluer   r   r1   r   r   Úins_tag_weightr   T©Úpersistabler   rB   ç        F©rC   Ú	force_cpu)ÚPredictr#   ÚStatPosÚStatNeg)ÚcurveÚnum_thresholdsÚslide_steps)ÚAUCÚ
StatPosOutÚ
StatNegOutr   r   )r>   )r
   r.   r,   ÚtensorÚfill_constantr   r/   Úcreate_global_variableÚset_variable_initializerr   r0   )r   r1   rM   rN   r-   rO   rD   r9   Úauc_outÚbatch_auc_outÚbatch_stat_posÚbatch_stat_negÚstat_posÚstat_negÚvars                  r;   r>   r>   ˆ   sb  € ô` Ñ+¤&£(Ñ+€FàÐÜŸ™×4Ñ4Ø�a�& 	°ð 5ó 
ˆô ˜U G¨i¸Ð-CÀUÔKÜ˜U G¨g°wÐ-?ÀÔGÜØÐ(¨9°iÐ*@À%ôð ×7Ñ7¸iÐ7ÓH€GØ×=Ñ=ÀIÐ=ÓN€Mð ×2Ñ2ØØØ�K‘ N°QÑ$6Ñ7¸!Ñ;Ð<ð 3ó €Nð
 ×2Ñ2ØØØ�K‘ N°QÑ$6Ñ7¸!Ñ;Ð<ð 3ó €Nð ×,Ñ,Ø °°>ÀAÑ3EÐ/Fð -ó €Hð ×,Ñ,Ø °°>ÀAÑ3EÐ/Fð -ó €Hð  °¸(ÓCˆØ×'Ñ'ØÜ c°UÔ;õ	
ð Dð ×ÑØà�wØ�WØ&Ð'Ø&Ð'ñ	
ð Ø,Ø&ñ
ð "�?Ø)Ð*Ø)Ð*ñ
ð ô ð( ×ÑØà�wØ�WØ �zØ �zñ	
ð Ø,Øñ
ð �9Ø#˜*Ø#˜*ñ
ð ô ð( 	ØØ	˜¨°8Ð<ðð r<   c                 ó   — |€$t         j                  j                  ddgdd¬«      }| j                  |j                  k(  sJ ‚t	        d i t        «       ¤Ž}|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }	|j                  dddg¬«      }
|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }|j                  dddg¬«      }||||||||||||	fD ]=  }|j                  |t         j                  j                  j                  d	d¬
«      «       Œ? |j                  d| g|gdœd|
gi¬«       |j                  dd|
gid|gi¬«       |j                  d|g|gdœd|gi¬«       |j                  dd|
gid|gi¬«       |j                  d|g|gdœd|gi¬«       |j                  dd| gid|gi¬«       |j                  d|g|gdœd|gi¬«       |j                  dd| gid|gi¬«       |j                  dd|gid|gi¬«       |j                  dd|gid|gi¬«       |j                  d|g|gdœd|gi¬«       |j                  dd|id|giddg|j                  ddœ¬«       |j                  dd|gid|gi¬«       d|i}ddgi}dg|d<   dg|d<   |j                  d||d|i¬«       |j                  j                  dd«      }|j                  d|g|gdœd|gid|i¬«       |j                  d|g|	gdœd|	gi¬«       |j                  d|g|gdœd|gid|i¬«       |j                  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 LoDTensor 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

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

            >>> 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

            >>> 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], lod_level=0, dtype='int64')
            >>> auc_out = paddle.static.ctr_metric_bundle(input=predict, label=label, ins_tag_weight=ins_tag_weight)
    r?   r   r@   rA   TrE   FéÿÿÿÿrG   rH   Ú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,   rS   rT   rB   r
   r.   rU   rV   ÚnnÚinitializerr   r0   r   ÚkwargsÚget)r   r1   rD   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!   rm   s                          r;   ro   ro   W  sB  € ðj ÐÜŸ™×4Ñ4Ø�a�& 	°ð 5ó 
ˆð �;‰;˜%Ÿ+™+Ò%Ð%Ð%ÜÑ9´³Ñ9€Fà×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‰I×!Ñ!×5Ñ5Ø Tð 6ó õ	
ðð* ×ÑØØ�W E 7Ñ+Ø˜Ð(Ð)ð ô ð ×ÑØØ�nÐ%Ð&Ø˜˜Ð'ð ô ð
 ×ÑØØ"�^¨<¨.Ñ9Ø˜˜Ð'ð ô ð ×ÑØØ�nÐ%Ð&Ø˜˜Ð'ð ô ð
 ×ÑØØ"�^¨<¨.Ñ9Ø˜˜Ð'ð ô ð ×ÑØ 3¨¨ .¸5À:À,Ð:Oð ô ð ×ÑØØ �\¨¨Ñ5Ø˜˜Ð%ð ô ð
 ×ÑØØ�e�Wˆ~Ø˜Ð)Ð*ð ô ð
 ×ÑØØ�oÐ&Ð'Ø˜˜	Ð"ð ô ð ×ÑØØ�e�Wˆ~Ø˜˜Ð(ð ô ð
 ×ÑØØ#�_¨M¨?Ñ;Ø˜˜Ð(ð ô ð ×ÑØ,Ø˜ÐØ˜˜
Ð#à˜!�WØ—^‘^Øñ
ð	 ô 	ð ×ÑØØ�h�ZÐ Ø˜˜Ð(ð ô ð ˜^Ð,€LØ�a�SˆM€EØ�c€Eˆ(�OØ�C€Eˆ&�MØ
×ÑØØØØ˜Ð'ð	 ô ð �=‰=×Ñ˜V QÓ'€DØ
×ÑØØ#�_¨NÐ+;Ñ<Ø˜˜Ð(Ø�tˆnð	 ô ð ×ÑØØ#�_¨M¨?Ñ;Ø˜˜Ð(ð ô ð ×ÑØØ�Y nÐ%5Ñ6Ø˜˜	Ð"Ø�tˆnð	 ô ð ×ÑØØ�Y g YÑ/Ø˜˜	Ð"ð ô ð 	ØØØØØðð 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   r>   ro   © r<   r;   Ú<module>r�      sT   ðñó ã ß (Ý <÷ó õ 1Ý 5à
€ócðR ØØ	
ØØóLô^xr<   