o
    Ne                     @   s4  d Z ddlmZ ddlZddlZddlZddlZddlm	Z	 ddl
mZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZ g dZdd Zdd Zdd ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG d d! d!eZ G d"d# d#eZ!dS )$z
Fluid Metrics
    )print_functionN   )LayerHelper)Constant)unique_name)ProgramVariableprogram_guard)layers)	detection)	
MetricBaseCompositeMetric	PrecisionRecallAccuracyChunkEvaluatorEditDistanceDetectionMAPAucc                 C   s   t | tjtjfS N)
isinstancenpndarraygenericvar r   DD:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/metrics.py
_is_numpy_-   s   r   c                 C   s6   t | tpt | tjpt | tpt | tjo| jdkS )N)r   )r   intr   Zint64floatr   shaper   r   r   r   _is_number_1   s
   r"   c                 C   s   t | p	t| tjS r   )r"   r   r   r   r   r   r   r   _is_number_or_matrix_6   s   r#   c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )r   a  
    In many cases, we usually have to split the test data into mini-batches for evaluating 
    deep neural networks, therefore we need to collect the evaluation results of each 
    mini-batch and aggregate them into the final result. The paddle.fluid.metrics is 
    designed for a convenient way of deep neural network evaluation. 

    The paddle.fluid.metrics contains serval different evaluation metrics 
    like precision and recall, and most of them have the following functions:

    1. take the prediction result and the corresponding labels of a mini-batch as input, 
    then compute the evaluation result for the input mini-batch.

    2. aggregate the existing evaluation results as the overall performance.

    The class Metric is the base class for all classes in paddle.fluid.metrics, it defines
    the fundamental APIs for all metrics classes, including:

    1. update(preds, labels): given the prediction results (preds) and the labels (labels)
    of some mini-batch, compute the evaluation result of that mini-batch, and memorize the
    evaluation result.

    2. eval(): aggregate all existing evaluation result in the memory, and return the overall
    performance across different mini-batches.

    3. reset(): empty the memory.

    c                 C   s$   |dkrt || _dS | jj| _dS )am  
        The constructor of the metric class.

        Args:
            name(str): The name of metric instance. such as, "accuracy".
                  It can be used to distinguish different metric instances in a model.

        Returns:
            The constructed class instance.

        Return types:
            The MetricBase or its succeed classes

        N)str	__class____name___nameselfnamer   r   r   __init__W   s   $zMetricBase.__init__c                 C   s   | j S r   )r'   r)   r   r   r   __str__h   s   zMetricBase.__str__c                 C   s   dd t | jD }t |D ]5\}}t|tr t| |d qt|tr,t| |d qt|tjtj	fr?t| |t
| qt| |d qdS )z
        reset function empties the evaluation memory for previous mini-batches. 
        
        Args:
            None

        Returns:
            None

        Return types:
            None

        c                 S       i | ]\}}| d s||qS _
startswith.0attrvaluer   r   r   
<dictcomp>y       z$MetricBase.reset.<locals>.<dictcomp>r           N)six	iteritems__dict__r   r   setattrr    r   r   r   Z
zeros_like)r)   statesr5   r6   r   r   r   resetk   s   


zMetricBase.resetc                 C   s6   dd t | jD }i }|| jt|d |S )a'  
        Get the metric and current states.
        The states are the members who do not has "_" prefix.

        Args:
            None

        Returns:
            a python dict, which contains the inner states of the metric instance

        Return types:
            a python dict
        c                 S   r.   r/   r1   r3   r   r   r   r7      r8   z)MetricBase.get_config.<locals>.<dictcomp>)r*   r>   )r:   r;   r<   updater'   copydeepcopy)r)   r>   configr   r   r   
get_config   s   
zMetricBase.get_configc                 C      t d)ao  
        Given the prediction results (preds) and the labels (labels)
        of some mini-batch, compute the evaluation result of that mini-batch, 
        and memorize the evaluation result. Please notice that the update function only
        memorizes the evaluation result but would not return the score. If you want to 
        get the evaluation result, please call eval() function.

        Args:
            preds(numpy.array): the predictions of current minibatch
            labels(numpy.array): the labels of current minibatch.

        Returns:
            None

        Return types:
            None

        -Should not use it directly, please extend it.NotImplementedError)r)   predslabelsr   r   r   r@      s   zMetricBase.updatec                 C   rE   )ac  
        Aggregate all existing evaluation results in the memory, and return the overall
        performance across different mini-batches.

        Args:
            None

        Returns:
            The overall performance across different mini-batches.

        Return types:
            float|list(float)|numpy.array: the metrics via Python.
        rF   rG   r,   r   r   r   eval   s   zMetricBase.evalN)
r&   
__module____qualname____doc__r+   r-   r?   rD   r@   rK   r   r   r   r   r   :   s    r   c                       s:   e Zd ZdZd fdd	Zdd Zdd Zd	d
 Z  ZS )r   a  
    This op creates a container that contains the union of all the added metrics. 
    After the metrics added in, calling eval() method will compute all the contained metrics automatically.
    CAUTION: only metrics with the SAME argument list can be added in a CompositeMetric instance.

    Inherit from: `MetricBase <https://www.paddlepaddle.org.cn/documentation/docs/zh/1.5/api_cn/metrics_cn.html#paddle.fluid.metrics.MetricBase>`_ 

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python
            import paddle.fluid as fluid
            import numpy as np
            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]
            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]
            preds = np.array(preds)
            labels = np.array(labels)
            comp = fluid.metrics.CompositeMetric()
            precision = fluid.metrics.Precision()
            recall = fluid.metrics.Recall()
            comp.add_metric(precision)
            comp.add_metric(recall)
            comp.update(preds=preds, labels=labels)
            numpy_precision, numpy_recall = comp.eval()
            print("expect precision: %.2f, got %.2f" % ( 3. / 5, numpy_precision ) )
            print("expect recall: %.2f, got %.2f" % (3. / 4, numpy_recall ) )
    Nc                    s   t t| | g | _d S r   )superr   r+   _metricsr(   r%   r   r   r+      s   
zCompositeMetric.__init__c                 C   s"   t |ts	td| j| dS )z
        Add a new metric to container. Noted that the argument list 
        of the added one should be consistent with existed ones.  

        Args:
            metric(MetricBase): a instance of MetricBase
        z,SubMetric should be inherit from MetricBase.N)r   r   
ValueErrorrP   append)r)   Zmetricr   r   r   
add_metric   s   
zCompositeMetric.add_metricc                 C   s   | j D ]}||| qdS )a  
        Update the metrics of this container.

        Args:
            preds(numpy.array): predicted results of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric.
            labels(numpy.array): ground truth of current mini-batch, the shape and dtype of which should meet the requirements of the corresponded metric. 
        N)rP   r@   )r)   rI   rJ   mr   r   r   r@      s   
zCompositeMetric.updatec                 C   s"   g }| j D ]	}||  q|S )z
        Calculate the results of all metrics sequentially.

        Returns:
            list: results of all added metrics. 
            The shape and dtype of each result depend on the definition of its metric.
        )rP   rS   rK   )r)   ZansrU   r   r   r   rK     s   
zCompositeMetric.evalr   )	r&   rL   rM   rN   r+   rT   r@   rK   __classcell__r   r   rQ   r   r      s    r   c                       2   e Zd ZdZd	 fdd	Zdd Zdd Z  ZS )
r   aR  
    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): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np

            metric = fluid.metrics.Precision()

            # generate the preds and labels

            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]

            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]

            preds = np.array(preds)
            labels = np.array(labels)

            metric.update(preds=preds, labels=labels)
            numpy_precision = metric.eval()

            print("expect precision: %.2f and got %.2f" % ( 3.0 / 5.0, numpy_precision))
    Nc                        t t| | d| _d| _d S Nr   )rO   r   r+   tpfpr(   rQ   r   r   r+   4     
zPrecision.__init__c                 C   s   t |stdt |std|jd }t|d}t|D ]!}|| }|| }|dkrB||kr;|  jd7  _q!|  jd7  _q!dS )aI  
        Update the precision based on the current mini-batch prediction results .

        Args:
            preds(numpy.ndarray): prediction results of current mini-batch, 
                                the output of two-class sigmoid function. 
                                Shape: [batch_size, 1]. Dtype: 'float64' or 'float32'.
            labels(numpy.ndarray): ground truth (labels) of current mini-batch, 
                                 the shape should keep the same as preds. 
                                 Shape: [batch_size, 1], Dtype: 'int32' or 'int64'.
        $The 'preds' must be a numpy ndarray.%The 'labels' must be a numpy ndarray.r   int32r   N)	r   rR   r!   r   rintastyperangerZ   r[   r)   rI   rJ   Z
sample_numipredlabelr   r   r   r@   9     
zPrecision.updatec                 C   &   | j | j }|dkrt| j | S dS )z
        Calculate the final precision.

        Returns:
            float: Results of the calculated Precision. Scalar output with float dtype.
        r   r9   )rZ   r[   r    )r)   Zapr   r   r   rK   U     zPrecision.evalr   r&   rL   rM   rN   r+   r@   rK   rV   r   r   rQ   r   r     s
    #r   c                       rW   )
r   aX  
    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): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np

            metric = fluid.metrics.Recall()

            # generate the preds and labels

            preds = [[0.1], [0.7], [0.8], [0.9], [0.2],
                     [0.2], [0.3], [0.5], [0.8], [0.6]]

            labels = [[0], [1], [1], [1], [1],
                      [0], [0], [0], [0], [0]]

            preds = np.array(preds)
            labels = np.array(labels)

            metric.update(preds=preds, labels=labels)
            numpy_recall = metric.eval()

            print("expect recall: %.2f and got %.2f" % ( 3.0 / 4.0, numpy_recall))
    Nc                    rX   rY   )rO   r   r+   rZ   fnr(   rQ   r   r   r+     r\   zRecall.__init__c                 C   s   t |stdt |std|jd }t|d}t|D ]!}|| }|| }|dkrB||kr;|  jd7  _q!|  jd7  _q!dS )a9  
        Update the recall 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_   r   N)	r   rR   r!   r   r`   ra   rb   rZ   rk   rc   r   r   r   r@     rg   zRecall.updatec                 C   rh   )z
        Calculate the final recall.

        Returns:
            float: results of the calculated Recall. Scalar output with float dtype.
        r   r9   )rZ   rk   r    )r)   recallr   r   r   rK     ri   zRecall.evalr   rj   r   r   rQ   r   r   `  s
    &r   c                       rW   )
r   ak  
    This interface is used to calculate the mean accuracy over multiple batches.
    Accuracy object has two state: value and weight. The definition of Accuracy is available at 
    https://en.wikipedia.org/wiki/Accuracy_and_precision

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            #suppose we have batch_size = 128
            batch_size=128
            accuracy_manager = fluid.metrics.Accuracy()

            #suppose the accuracy is 0.9 for the 1st batch
            batch1_acc = 0.9
            accuracy_manager.update(value = batch1_acc, weight = batch_size)
            print("expect accuracy: %.2f, get accuracy: %.2f" % (batch1_acc, accuracy_manager.eval()))

            #suppose the accuracy is 0.8 for the 2nd batch
            batch2_acc = 0.8

            accuracy_manager.update(value = batch2_acc, weight = batch_size)
            #the joint acc for batch1 and batch2 is (batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2
            print("expect accuracy: %.2f, get accuracy: %.2f" % ((batch1_acc * batch_size + batch2_acc * batch_size) / batch_size / 2, accuracy_manager.eval()))

            #reset the accuracy_manager
            accuracy_manager.reset()
            #suppose the accuracy is 0.8 for the 3rd batch
            batch3_acc = 0.8
            accuracy_manager.update(value = batch3_acc, weight = batch_size)
            print("expect accuracy: %.2f, get accuracy: %.2f" % (batch3_acc, accuracy_manager.eval()))
    Nc                    rX   )Nr9   )rO   r   r+   r6   weightr(   rQ   r   r   r+     r\   zAccuracy.__init__c                 C   s\   t |stdt|stdt|r|dk rtd|  j|| 7  _|  j|7  _dS )a  
        This function takes the minibatch states (value, weight) as input,
        to accumulate and update the corresponding status of the Accuracy object. The update method is as follows:

        .. math::
            \\\\ \\begin{array}{l}{\\text { self. value }+=\\text { value } * \\text { weight }} \\\\ {\\text { self. weight }+=\\text { weight }}\\end{array} \\\\

        Args:
            value(float|numpy.array): accuracy of one minibatch.
            weight(int|float): minibatch size.
        z<The 'value' must be a number(int, float) or a numpy ndarray.z*The 'weight' must be a number(int, float).r   z The 'weight' can not be negativeN)r#   rR   r"   r6   rm   )r)   r6   rm   r   r   r   r@     s   zAccuracy.updatec                 C   s   | j dkr	td| j| j  S )z
        This function returns the mean accuracy (float or numpy.array) for all accumulated minibatches.

        Returns: 
            float or numpy.array: mean accuracy for all accumulated minibatches.

        r   zpThere is no data in Accuracy Metrics.                 Please check layers.accuracy output has added to Accuracy.)rm   rR   r6   r,   r   r   r   rK     s   
zAccuracy.evalr   rj   r   r   rQ   r   r     s
    $r   c                       rW   )
r   ay  
    Accumulate counter numbers output by chunk_eval from mini-batches and
    compute the precision recall and F1-score using the accumulated counter
    numbers.
    ChunkEvaluator has three states: num_infer_chunks, num_label_chunks and num_correct_chunks, 
    which correspond to the number of chunks, the number of labeled chunks, and the number of correctly identified chunks.
    For some basics of chunking, please refer to 
    `Chunking with Support Vector Machines <https://www.aclweb.org/anthology/N01-1025>`_ .
    ChunkEvalEvaluator computes the precision, recall, and F1-score of chunk detection,
    and supports IOB, IOE, IOBES and IO (also known as plain) tagging schemes.

    Args:
       name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            # init the chunk-level evaluation manager
            metric = fluid.metrics.ChunkEvaluator()

            # suppose the model predict 10 chucks, while 8 ones are correct and the ground truth has 9 chucks.
            num_infer_chunks = 10
            num_label_chunks = 9 
            num_correct_chunks = 8

            metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks)
            numpy_precision, numpy_recall, numpy_f1 = metric.eval()

            print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1))

            # the next batch, predicting 3 perfectly correct chucks.
            num_infer_chunks = 3
            num_label_chunks = 3
            num_correct_chunks = 3

            metric.update(num_infer_chunks, num_label_chunks, num_correct_chunks)
            numpy_precision, numpy_recall, numpy_f1 = metric.eval()

            print("precision: %.2f, recall: %.2f, f1: %.2f" % (numpy_precision, numpy_recall, numpy_f1))

    Nc                    s&   t t| | d| _d| _d| _d S rY   )rO   r   r+   num_infer_chunksnum_label_chunksnum_correct_chunksr(   rQ   r   r   r+   -     
zChunkEvaluator.__init__c                 C   s^   t |stdt |stdt |std|  j|7  _|  j|7  _|  j|7  _dS )a  
        This function takes (num_infer_chunks, num_label_chunks, num_correct_chunks) as input,
        to accumulate and update the corresponding status of the ChunkEvaluator object. The update method is as follows:
        
        .. math:: 
                   \\\\ \\begin{array}{l}{\\text { self. num_infer_chunks }+=\\text { num_infer_chunks }} \\\\ {\\text { self. num_Label_chunks }+=\\text { num_label_chunks }} \\\\ {\\text { self. num_correct_chunks }+=\\text { num_correct_chunks }}\\end{array} \\\\

        Args:
            num_infer_chunks(int|numpy.array): The number of chunks in Inference on the given minibatch.
            num_label_chunks(int|numpy.array): The number of chunks in Label on the given mini-batch.
            num_correct_chunks(int|float|numpy.array): The number of chunks both in Inference and Label on the
                                                  given mini-batch.
        z@The 'num_infer_chunks' must be a number(int) or a numpy ndarray.zGThe 'num_label_chunks' must be a number(int, float) or a numpy ndarray.zIThe 'num_correct_chunks' must be a number(int, float) or a numpy ndarray.N)r#   rR   rn   ro   rp   )r)   rn   ro   rp   r   r   r   r@   3  s   zChunkEvaluator.updatec                 C   s`   | j rt| j| j  nd}| jrt| j| j nd}| jr)td| | ||  nd}|||fS )z
        This function returns the mean precision, recall and f1 score for all accumulated minibatches.

        Returns: 
            float: mean precision, recall and f1 score.

        r      )rn   r    rp   ro   )r)   	precisionrl   Zf1_scorer   r   r   rK   Q  s*   


zChunkEvaluator.evalr   rj   r   r   rQ   r   r     s
    +r   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )r   a  
    This API is for the management of edit distances.
    Editing distance is a method to quantify the degree of dissimilarity 
    between two strings, such as words, by calculating the minimum editing 
    operand (add, delete or replace) required to convert one string into another. 
    Refer to https://en.wikipedia.org/wiki/Edit_distance.

    Args:
        name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np

            # suppose that batch_size is 128
            batch_size = 128

            # init the edit distance manager
            distance_evaluator = fluid.metrics.EditDistance("EditDistance")

            # generate the edit distance across 128 sequence pairs, the max distance is 10 here
            edit_distances_batch0 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch0 = batch_size

            distance_evaluator.update(edit_distances_batch0, seq_num_batch0)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch0 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))

            edit_distances_batch1 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch1 = batch_size

            distance_evaluator.update(edit_distances_batch1, seq_num_batch1)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch0 and batch1 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))

            distance_evaluator.reset()

            edit_distances_batch2 = np.random.randint(low = 0, high = 10, size = (batch_size, 1))
            seq_num_batch2 = batch_size

            distance_evaluator.update(edit_distances_batch2, seq_num_batch2)
            avg_distance, wrong_instance_ratio = distance_evaluator.eval()
            print("the average edit distance for batch2 is %.2f and the wrong instance ratio is %.2f " % (avg_distance, wrong_instance_ratio))

    c                    s&   t t| | d| _d| _d| _d S )Nr9   r   )rO   r   r+   total_distanceseq_numinstance_errorr(   rQ   r   r   r+     rq   zEditDistance.__init__c                 C   sj   t |stdt|stdt|dk}t|}|  j|7  _|  j|| 7  _|  j|7  _dS )a  
        Update the overall edit distance

        Args:
            distances(numpy.array): a (batch_size, 1) numpy.array, each element represents the edit distance between two sequences.
            seq_num(int|float): standing for the number of sequence pairs.
        z(The 'distances' must be a numpy ndarray.z+The 'seq_num' must be a number(int, float).r   N)r   rR   r"   r   sumru   rv   rt   )r)   Z	distancesru   Zseq_right_countrt   r   r   r   r@     s   
zEditDistance.updatec                 C   s6   | j dkr	td| j| j  }| jt| j  }||fS )z
        Return two floats:
        avg_distance: the average distance for all sequence pairs updated using the update function.
        avg_instance_error: the ratio of sequence pairs whose edit distance is not zero.
        r   zqThere is no data in EditDistance Metric. Please check layers.edit_distance output has been added to EditDistance.)ru   rR   rt   rv   r    )r)   Zavg_distanceZavg_instance_errorr   r   r   rK     s   
zEditDistance.evalrj   r   r   rQ   r   r   c  s
    0r   c                       s>   e Zd ZdZd fdd	Zdd Zedd	 Zd
d Z  Z	S )r   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.
    If you concern the speed, please use the fluid.layers.auc instead.

    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:
        name (str, optional): Metric name. For details, please refer to :ref:`api_guide_Name`. Default is None.
        curve (str): Specifies the name of the curve to be computed, 'ROC' [default] or 'PR' for the Precision-Recall-curve.

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

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid
            import numpy as np
            # init the auc metric
            auc_metric = fluid.metrics.Auc("ROC")

            # suppose that batch_size is 128
            batch_num = 100
            batch_size = 128

            for batch_id in range(batch_num):

                class0_preds = np.random.random(size = (batch_size, 1))
                class1_preds = 1 - class0_preds

                preds = np.concatenate((class0_preds, class1_preds), axis=1)

                labels = np.random.randint(2, size = (batch_size, 1))
                auc_metric.update(preds = preds, labels = labels)

                # shall be some score closing to 0.5 as the preds are randomly assigned
                print("auc for iteration %d is %.2f" % (batch_id, auc_metric.eval()))
    ROC  c                    sB   t t| j|d || _|| _|d }dg| | _dg| | _d S )N)r*   r   r   )rO   r   r+   Z_curve_num_thresholds	_stat_pos	_stat_neg)r)   r*   ZcurveZnum_thresholdsZ_num_pred_bucketsrQ   r   r   r+     s   zAuc.__init__c                 C   s   t |stdt |stdt|D ]-\}}||df }t|| j }|| jks,J |r8| j|  d7  < q| j|  d7  < qdS )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^   z*The 'predictions' must be a numpy ndarray.r   g      ?N)r   rR   	enumerater   rz   r{   r|   )r)   rI   rJ   rd   Zlblr6   Zbin_idxr   r   r   r@     s   z
Auc.updatec                 C   s   t | | ||  d S )Ng       @)abs)x1Zx2y1y2r   r   r   trapezoid_area	  s   zAuc.trapezoid_areac                 C   s   d}d}d}| j }|dkr1|}|}|| j| 7 }|| j| 7 }|| ||||7 }|d8 }|dks|dkr?|dkr?|| | S dS )z~
        Return the area (a float score) under auc curve

        Return:
            float: the area under auc curve
        r9   r   r   )rz   r{   r|   r   )r)   Ztot_posZtot_negZaucidxZtot_pos_prevZtot_neg_prevr   r   r   rK     s    	zAuc.eval)rx   ry   )
r&   rL   rM   rN   r+   r@   staticmethodr   rK   rV   r   r   rQ   r   r     s    .	
r   c                   @   s@   e Zd ZdZ						dddZd	d
 Zdd ZdddZdS )r   a&  
    Calculate the detection mean average precision (mAP).

    The general steps are as follows:

    1. calculate the true positive and false positive according to the input
       of detection and labels.
    2. calculate mAP value, support two versions: '11 point' and 'integral'.
       11point: the 11-point interpolated average precision.
       integral: the natural integral of the precision-recall curve.

    Please get more information from the following articles:

      https://sanchom.wordpress.com/tag/average-precision/

      https://arxiv.org/abs/1512.02325

    Args:
        input (Variable): LoDTensor, The detection results, which is a LoDTensor with shape
            [M, 6]. The layout is [label, confidence, xmin, ymin, xmax, ymax].
            The data type is float32 or float64.
        gt_label (Variable): LoDTensor, The ground truth label index, which is a LoDTensor
            with shape [N, 1].The data type is float32 or float64.
        gt_box (Variable): LoDTensor, The ground truth bounding box (bbox), which is a
            LoDTensor with shape [N, 4]. The layout is [xmin, ymin, xmax, ymax].
            The data type is float32 or float64.
        gt_difficult (Variable|None): LoDTensor, Whether this ground truth is a difficult
            bounding bbox, which can be a LoDTensor [N, 1] or not set. If None,
            it means all the ground truth labels are not difficult bbox.The
            data type is int.
        class_num (int): The class number.
        background_label (int): The index of background label, the background
            label will be ignored. If set to -1, then all categories will be
            considered, 0 by default.
        overlap_threshold (float): The threshold for deciding true/false
            positive, 0.5 by default.
        evaluate_difficult (bool): Whether to consider difficult ground truth
            for evaluation, True by default. This argument does not work when
            gt_difficult is None.
        ap_version (str): The average precision calculation ways, it must be
            'integral' or '11point'. Please check
            https://sanchom.wordpress.com/tag/average-precision/ for details.

    Examples:
        .. code-block:: python

            import paddle.fluid as fluid

            import paddle
            paddle.enable_static()

            batch_size = None # can be any size
            image_boxs_num = 10
            bounding_bboxes_num = 21

            pb = fluid.data(name='prior_box', shape=[image_boxs_num, 4],
                       dtype='float32')

            pbv = fluid.data(name='prior_box_var', shape=[image_boxs_num, 4],
                         dtype='float32')

            loc = fluid.data(name='target_box', shape=[batch_size, bounding_bboxes_num, 4],
                        dtype='float32')

            scores = fluid.data(name='scores', shape=[batch_size, bounding_bboxes_num, image_boxs_num],
                            dtype='float32')

            nmsed_outs = fluid.layers.detection_output(scores=scores,
                loc=loc, prior_box=pb, prior_box_var=pbv)

            gt_box = fluid.data(name="gt_box", shape=[batch_size, 4], dtype="float32")
            gt_label = fluid.data(name="gt_label", shape=[batch_size, 1], dtype="float32")
            difficult = fluid.data(name="difficult", shape=[batch_size, 1], dtype="float32")

            exe = fluid.Executor(fluid.CUDAPlace(0))
            map_evaluator = fluid.metrics.DetectionMAP(nmsed_outs, gt_label, gt_box, difficult, class_num = 3)

            cur_map, accum_map = map_evaluator.get_map_var()


    Nr         ?Tintegralc
                 C   s2  t d| _tj||jd}|r"tj||jd}tj|||gdd}
n	tj||gdd}
tj||
|||||	d}g }|| j	dd dd || j	d	d d
d || j	d	d dd | j	ddgdd}| jj
|ttddd || _tj||
||||| j|||	d
}tj| jjd| jj| jd || _|| _d S )NZmap_eval)xdtyper   )Zaxis)overlap_thresholdevaluate_difficult
ap_versionr_   Zaccum_pos_count)r   r!   suffixZfloat32Zaccum_true_posZaccum_false_pos	has_stater   )r6   )initializer)r   r   r   Zinput_statesZ
out_statesr   r!   r6   r   out)r   helperr
   castr   concatr   Zdetection_maprS   _create_stateZset_variable_initializerr   r   r   fill_constantr!   cur_map	accum_map)r)   inputZgt_labelZgt_boxZgt_difficultZ	class_numZbackground_labelr   r   r   rf   mapr>   r   r   r   r   r   r+   x  sr   


zDetectionMAP.__init__c                 C   s,   | j jdt| j j|gd||d}|S )z
        Create state variable.
        Args:
            suffix(str): the state suffix.
            dtype(str|core.VarDesc.VarType): the state data type
            shape(tuple|list): the shape of state
        Returns: State variable
        r0   T)r*   persistabler   r!   )r   Zcreate_variablejoinr   generater*   )r)   r   r   r!   stater   r   r   r     s   
	zDetectionMAP._create_statec                 C   s   | j | jfS )z{
        Returns: mAP variable of current mini-batch and
            accumulative mAP variable cross mini-batches.
        )r   r   r,   r   r   r   get_map_var  s   zDetectionMAP.get_map_varc                 C   st   dd }|du rt  }t|d || | j}tj|jd|j|d W d   n1 s.w   Y  || dS )a<  
        Reset metric states at the begin of each pass/user specified batch.
        Args:
            executor(Executor): a executor for executing
                the reset_program.
            reset_program(Program|None): a single Program for reset process.
                If None, will create a Program.
        c                 S   s0   t |tsJ | j|j|j|j|j|j|jdS )N)r*   r!   r   type	lod_levelr   )	r   r   Z
create_varr*   r!   r   r   r   r   )blockr   r   r   r   _clone_var_  s   z'DetectionMAP.reset.<locals>._clone_var_N)Zmain_programr   r   )	r   r	   Zcurrent_blockr   r
   r   r!   r   run)r)   executorZreset_programr   r   r   r   r   r?     s   
	zDetectionMAP.reset)NNr   r   Tr   r   )r&   rL   rM   rN   r+   r   r   r?   r   r   r   r   r   %  s    V
Cr   )"rN   
__future__r   numpyr   rA   warningsr:   Zlayer_helperr   r   r    r   Z	frameworkr   r   r	   r
   r   __all__r   r"   r#   objectr   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s4    IPSNbXj