o
    7?e                    @   s  d Z ddlZddlZddlm  mZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ G dd dejZedG dd deZedG dd deZedG dd deZedG dd deZedG dd dejZedG dd dejZG dd  d ejej d!Z!ed"G d#d$ d$e!Z"ed%G d&d' d'e!Z#ed(G d)d* d*e!Z$ed+G d,d- d-e!Z%ed.G d/d0 d0ejZ&dS )1zHConfusion metrics, i.e. metrics based on True/False positives/negatives.    N)activations)backend)utils)base_metric)metrics_utils)to_list)is_tensor_or_variable)keras_exportc                       sJ   e Zd ZdZ	d fdd	ZdddZdd Zd	d
 Z fddZ  Z	S )_ConfusionMatrixConditionCountaw  Calculates the number of the given confusion matrix condition.

    Args:
      confusion_matrix_cond: One of `metrics_utils.ConfusionMatrix` conditions.
      thresholds: (Optional) A float value or a python list/tuple of float
        threshold values in [0, 1]. A threshold is compared with prediction
        values to determine the truth value of predictions
        (i.e., above the threshold is `true`, below is `false`). One metric
        value is generated for each threshold value. Defaults to `0.5`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.
    Nc                    sX   t  j||d || _|| _tj|dd| _t| j| _| j	dt
| jfdd| _d S )Nnamedtype      ?default_thresholdaccumulatorzerosshapeZinitializer)super__init___confusion_matrix_condinit_thresholdsr   parse_init_thresholds
thresholds is_evenly_distributed_thresholds_thresholds_distributed_evenly
add_weightlenr   )selfconfusion_matrix_condr   r   r   	__class__ d/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/keras/src/metrics/confusion_metrics.pyr   0   s   
z'_ConfusionMatrixConditionCount.__init__c                 C   s"   t j| j| ji||| j| j|dS )a  Accumulates the metric statistics.

        Args:
          y_true: The ground truth values.
          y_pred: The predicted values.
          sample_weight: Optional weighting of each example. Can
            be a `Tensor` whose rank is either 0, or the same rank as `y_true`,
            and must be broadcastable to `y_true`. Defaults to `1`.

        Returns:
          Update op.
        )r   thresholds_distributed_evenlysample_weight)r   !update_confusion_matrix_variablesr   r   r   r   r   y_truey_predr&   r#   r#   r$   update_state@   s   
z+_ConfusionMatrixConditionCount.update_statec                 C   s*   t | jdkr| jd }n| j}t|S N   r   )r   r   r   tfZconvert_to_tensorr   resultr#   r#   r$   r0   V   s   
z%_ConfusionMatrixConditionCount.resultc                 C   s   t dd | jD  d S )Nc                 S   s    g | ]}|t |j fqS r#   )npr   r   as_list.0vr#   r#   r$   
<listcomp>_   s     z>_ConfusionMatrixConditionCount.reset_state.<locals>.<listcomp>)r   batch_set_value	variablesr   r#   r#   r$   reset_state]   s   z*_ConfusionMatrixConditionCount.reset_statec                    0   d| j i}t  }tt| t|  S )Nr   )r   r   
get_configdictlistitemsr   configbase_configr!   r#   r$   r<   b      

z)_ConfusionMatrixConditionCount.get_configNNNN)
__name__
__module____qualname____doc__r   r+   r0   r:   r<   __classcell__r#   r#   r!   r$   r
   "   s    
r
   zkeras.metrics.FalsePositivesc                       (   e Zd ZdZejd fdd	Z  ZS )FalsePositivesa  Calculates the number of false positives.

    If `sample_weight` is given, calculates the sum of the weights of
    false positives. This metric creates one local variable, `accumulator`
    that is used to keep track of the number of false positives.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    Args:
      thresholds: (Optional) A float value, or a Python
        list/tuple of float threshold values in [0, 1]. A threshold is compared
        with prediction values to determine the truth value of predictions
        (i.e., above the threshold is `true`, below is `false`). If used with a
        loss function that sets `from_logits=True` (i.e. no sigmoid applied to
        predictions), `thresholds` should be set to 0. One metric value is
        generated for each threshold value. Defaults to `0.5`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.FalsePositives()
    >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1])
    >>> m.result().numpy()
    2.0

    >>> m.reset_state()
    >>> m.update_state([0, 1, 0, 0], [0, 0, 1, 1], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.FalsePositives()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.FalsePositives(thresholds=0)])
    ```
    Nc                       t  jtjj|||d d S N)r    r   r   r   )r   r   r   ConfusionMatrixFALSE_POSITIVESr   r   r   r   r!   r#   r$   r         
zFalsePositives.__init__rD   rF   rG   rH   rI   dtensor_utilsinject_meshr   rJ   r#   r#   r!   r$   rL   h       1rL   zkeras.metrics.FalseNegativesc                       rK   )FalseNegativesa  Calculates the number of false negatives.

    If `sample_weight` is given, calculates the sum of the weights of
    false negatives. This metric creates one local variable, `accumulator`
    that is used to keep track of the number of false negatives.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    Args:
      thresholds: (Optional) A float value, or a Python
        list/tuple of float threshold values in [0, 1]. A threshold is compared
        with prediction values to determine the truth value of predictions
        (i.e., above the threshold is `true`, below is `false`). If used with a
        loss function that sets `from_logits=True` (i.e. no sigmoid applied to
        predictions), `thresholds` should be set to 0. One metric value is
        generated for each threshold value. Defaults to `0.5`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.FalseNegatives()
    >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0])
    >>> m.result().numpy()
    2.0

    >>> m.reset_state()
    >>> m.update_state([0, 1, 1, 1], [0, 1, 0, 0], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.FalseNegatives()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.FalseNegatives(thresholds=0)])
    ```
    Nc                    rM   rN   )r   r   r   rO   FALSE_NEGATIVESrQ   r!   r#   r$   r      rR   zFalseNegatives.__init__rD   rS   r#   r#   r!   r$   rW      rV   rW   zkeras.metrics.TrueNegativesc                       rK   )TrueNegativesa  Calculates the number of true negatives.

    If `sample_weight` is given, calculates the sum of the weights of
    true negatives. This metric creates one local variable, `accumulator`
    that is used to keep track of the number of true negatives.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    Args:
      thresholds: (Optional) A float value, or a Python
        list/tuple of float threshold values in [0, 1]. A threshold is compared
        with prediction values to determine the truth value of predictions
        (i.e., above the threshold is `true`, below is `false`). If used with a
        loss function that sets `from_logits=True` (i.e. no sigmoid applied to
        predictions), `thresholds` should be set to 0. One metric value is
        generated for each threshold value. Defaults to `0.5`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.TrueNegatives()
    >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0])
    >>> m.result().numpy()
    2.0

    >>> m.reset_state()
    >>> m.update_state([0, 1, 0, 0], [1, 1, 0, 0], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.TrueNegatives()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.TrueNegatives(thresholds=0)])
    ```
    Nc                    rM   rN   )r   r   r   rO   TRUE_NEGATIVESrQ   r!   r#   r$   r     rR   zTrueNegatives.__init__rD   rS   r#   r#   r!   r$   rY      rV   rY   zkeras.metrics.TruePositivesc                       rK   )TruePositivesa  Calculates the number of true positives.

    If `sample_weight` is given, calculates the sum of the weights of
    true positives. This metric creates one local variable, `true_positives`
    that is used to keep track of the number of true positives.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    Args:
      thresholds: (Optional) A float value, or a Python
        list/tuple of float threshold values in [0, 1]. A threshold is compared
        with prediction values to determine the truth value of predictions
        (i.e., above the threshold is `true`, below is `false`). If used with a
        loss function that sets `from_logits=True` (i.e. no sigmoid applied to
        predictions), `thresholds` should be set to 0. One metric value is
        generated for each threshold value. Defaults to `0.5`.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.TruePositives()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
    >>> m.result().numpy()
    2.0

    >>> m.reset_state()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.TruePositives()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.TruePositives(thresholds=0)])
    ```
    Nc                    rM   rN   )r   r   r   rO   TRUE_POSITIVESrQ   r!   r#   r$   r   R  rR   zTruePositives.__init__rD   rS   r#   r#   r!   r$   r[     rV   r[   zkeras.metrics.Precisionc                       P   e Zd ZdZej	d fdd	ZdddZdd Zd	d
 Z	 fddZ
  ZS )	Precisiona  Computes the precision of the predictions with respect to the labels.

    The metric creates two local variables, `true_positives` and
    `false_positives` that are used to compute the precision. This value is
    ultimately returned as `precision`, an idempotent operation that simply
    divides `true_positives` by the sum of `true_positives` and
    `false_positives`.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `top_k` is set, we'll calculate precision as how often on average a class
    among the top-k classes with the highest predicted values of a batch entry
    is correct and can be found in the label for that entry.

    If `class_id` is specified, we calculate precision by considering only the
    entries in the batch for which `class_id` is above the threshold and/or in
    the top-k highest predictions, and computing the fraction of them for which
    `class_id` is indeed a correct label.

    Args:
      thresholds: (Optional) A float value, or a Python list/tuple of float
        threshold values in [0, 1]. A threshold is compared with prediction
        values to determine the truth value of predictions (i.e., above the
        threshold is `true`, below is `false`). If used with a loss function
        that sets `from_logits=True` (i.e. no sigmoid applied to predictions),
        `thresholds` should be set to 0. One metric value is generated for each
        threshold value. If neither thresholds nor top_k are set, the default is
        to calculate precision with `thresholds=0.5`.
      top_k: (Optional) Unset by default. An int value specifying the top-k
        predictions to consider when calculating precision.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.Precision()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
    >>> m.result().numpy()
    0.6666667

    >>> m.reset_state()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    >>> # With top_k=2, it will calculate precision over y_true[:2]
    >>> # and y_pred[:2]
    >>> m = tf.keras.metrics.Precision(top_k=2)
    >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
    >>> m.result().numpy()
    0.0

    >>> # With top_k=4, it will calculate precision over y_true[:4]
    >>> # and y_pred[:4]
    >>> m = tf.keras.metrics.Precision(top_k=4)
    >>> m.update_state([0, 0, 1, 1], [1, 1, 1, 1])
    >>> m.result().numpy()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.Precision()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.Precision(thresholds=0)])
    ```
    Nc                       t  j||d || _|| _|| _|d u rdntj}tj||d| _t	| j| _
| jdt| jfdd| _| jdt| jfdd| _d S )Nr   r   r   true_positivesr   r   false_positives)r   r   r   top_kclass_idr   NEG_INFr   r   r   r   r   r   r`   ra   r   r   rb   rc   r   r   r   r!   r#   r$   r     $   

zPrecision.__init__c              
   C   6   t jt jj| jt jj| ji||| j| j| j	| j
|dS )a!  Accumulates true positive and false positive statistics.

        Args:
          y_true: The ground truth values, with the same dimensions as `y_pred`.
            Will be cast to `bool`.
          y_pred: The predicted values. Each element must be in the range
            `[0, 1]`.
          sample_weight: Optional weighting of each example. Can
            be a `Tensor` whose rank is either 0, or the same rank as `y_true`,
            and must be broadcastable to `y_true`. Defaults to `1`.

        Returns:
          Update op.
        r   r%   rb   rc   r&   )r   r'   rO   r\   r`   rP   ra   r   r   rb   rc   r(   r#   r#   r$   r+        

zPrecision.update_statec                 C   8   t j| jt j| j| j}t| jdkr|d S |S r,   )r.   mathdivide_no_nanr`   addra   r   r   r/   r#   r#   r$   r0     
   zPrecision.resultc                    2   t t| j t fdd| j| jfD  d S )Nc                       g | ]
}|t  ffqS r#   r1   r   r3   num_thresholdsr#   r$   r6         z)Precision.reset_state.<locals>.<listcomp>)r   r   r   r   r7   r`   ra   r9   r#   rr   r$   r:        

zPrecision.reset_statec                    8   | j | j| jd}t  }tt| t|  S N)r   rb   rc   r   rb   rc   r   r<   r=   r>   r?   r@   r!   r#   r$   r<        
zPrecision.get_configNNNNNrE   rF   rG   rH   rI   rT   rU   r   r+   r0   r:   r<   rJ   r#   r#   r!   r$   r^   \  s    P
	r^   zkeras.metrics.Recallc                       r]   )Recallaw
  Computes the recall of the predictions with respect to the labels.

    This metric creates two local variables, `true_positives` and
    `false_negatives`, that are used to compute the recall. This value is
    ultimately returned as `recall`, an idempotent operation that simply divides
    `true_positives` by the sum of `true_positives` and `false_negatives`.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `top_k` is set, recall will be computed as how often on average a class
    among the labels of a batch entry is in the top-k predictions.

    If `class_id` is specified, we calculate recall by considering only the
    entries in the batch for which `class_id` is in the label, and computing the
    fraction of them for which `class_id` is above the threshold and/or in the
    top-k predictions.

    Args:
      thresholds: (Optional) A float value, or a Python list/tuple of float
        threshold values in [0, 1]. A threshold is compared with prediction
        values to determine the truth value of predictions (i.e., above the
        threshold is `true`, below is `false`). If used with a loss function
        that sets `from_logits=True` (i.e. no sigmoid applied to predictions),
        `thresholds` should be set to 0. One metric value is generated for each
        threshold value. If neither thresholds nor top_k are set, the default is
        to calculate recall with `thresholds=0.5`.
      top_k: (Optional) Unset by default. An int value specifying the top-k
        predictions to consider when calculating recall.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.Recall()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1])
    >>> m.result().numpy()
    0.6666667

    >>> m.reset_state()
    >>> m.update_state([0, 1, 1, 1], [1, 0, 1, 1], sample_weight=[0, 0, 1, 0])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[tf.keras.metrics.Recall()])
    ```

    Usage with a loss with `from_logits=True`:

    ```python
    model.compile(optimizer='adam',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.Recall(thresholds=0)])
    ```
    Nc                    r_   )Nr   r   r   r`   r   r   false_negatives)r   r   r   rb   rc   r   rd   r   r   r   r   r   r   r`   r}   re   r!   r#   r$   r   @  rf   zRecall.__init__c              
   C   rg   )a!  Accumulates true positive and false negative statistics.

        Args:
          y_true: The ground truth values, with the same dimensions as `y_pred`.
            Will be cast to `bool`.
          y_pred: The predicted values. Each element must be in the range
            `[0, 1]`.
          sample_weight: Optional weighting of each example. Can
            be a `Tensor` whose rank is either 0, or the same rank as `y_true`,
            and must be broadcastable to `y_true`. Defaults to `1`.

        Returns:
          Update op.
        rh   )r   r'   rO   r\   r`   rX   r}   r   r   rb   rc   r(   r#   r#   r$   r+   Y  ri   zRecall.update_statec                 C   rj   r,   )r.   rk   rl   r`   rm   r}   r   r   r/   r#   r#   r$   r0   v  rn   zRecall.resultc                    ro   )Nc                    rp   r#   rq   r3   rr   r#   r$   r6     rt   z&Recall.reset_state.<locals>.<listcomp>)r   r   r   r   r7   r`   r}   r9   r#   rr   r$   r:   }  ru   zRecall.reset_statec                    rv   rw   rx   r@   r!   r#   r$   r<     ry   zRecall.get_configrz   rE   r{   r#   r#   r!   r$   r|     s    @
	r|   c                       sJ   e Zd ZdZ	d fdd	ZdddZdd	 Z fd
dZdd Z  Z	S )SensitivitySpecificityBasezAbstract base class for computing sensitivity and specificity.

    For additional information about specificity and sensitivity, see
    [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).
       Nc                    s   t  j||d  dkrtd  || _|| _| jd fdd| _| jd fdd| _| jd fdd| _| jd	 fdd| _	 d
krNdg| _
d| _d S  fddt d D }dg| dg | _
d| _d S )Nr   r   zKArgument `num_thresholds` must be an integer > 0. Received: num_thresholds=r`   r   r   true_negativesra   r}   r-   r   Fc                        g | ]}|d  d  d   qS r-         ?r#   r4   irr   r#   r$   r6         z7SensitivitySpecificityBase.__init__.<locals>.<listcomp>           r   T)r   r   
ValueErrorvaluerc   r   r`   r   ra   r}   r   r   range)r   r   rs   rc   r   r   r   r!   rr   r$   r     s:   



z#SensitivitySpecificityBase.__init__c              	   C   sF   t jt jj| jt jj| jt jj| jt jj	| j
i||| j| j| j|dS )  Accumulates confusion matrix statistics.

        Args:
          y_true: The ground truth values.
          y_pred: The predicted values.
          sample_weight: Optional weighting of each example. Can
            be a `Tensor` whose rank is either 0, or the same rank as `y_true`,
            and must be broadcastable to `y_true`. Defaults to `1`.

        Returns:
          Update op.
        )r   r%   rc   r&   )r   r'   rO   r\   r`   rZ   r   rP   ra   rX   r}   r   r   rc   r(   r#   r#   r$   r+     s   



z'SensitivitySpecificityBase.update_statec                    s:   t | j | j| j| j| jf}t fdd|D  d S )Nc                    rp   r#   rq   r3   rr   r#   r$   r6     rt   z:SensitivitySpecificityBase.reset_state.<locals>.<listcomp>)r   r   r`   r   ra   r}   r   r7   r   Zconfusion_matrix_variablesr#   rr   r$   r:     s   

z&SensitivitySpecificityBase.reset_statec                    r;   )Nrc   )rc   r   r<   r=   r>   r?   r@   r!   r#   r$   r<     rC   z%SensitivitySpecificityBase.get_configc                 C   sD   t ||| j}t t |d}t t ||}t ||dS )a  Returns the maximum of dependent_statistic that satisfies the
        constraint.

        Args:
          constrained: Over these values the constraint
            is specified. A rank-1 tensor.
          dependent: From these values the maximum that satiesfies the
            constraint is selected. Values in this tensor and in
            `constrained` are linked by having the same threshold at each
            position, hence this tensor must have the same shape.
          predicate: A binary boolean functor to be applied to arguments
          `constrained` and `self.value`, e.g. `tf.greater`.

        Returns:
          maximal dependent value, if no value satiesfies the constraint 0.0.
        r   r   )r.   wherer   ZgreatersizeZ
reduce_maxgather)r   ZconstrainedZ	dependent	predicateZfeasibleZfeasible_existsZmax_dependentr#   r#   r$   _find_max_under_constraint  s   z5SensitivitySpecificityBase._find_max_under_constraintr   NNNrE   )
rF   rG   rH   rI   r   r+   r:   r<   r   rJ   r#   r#   r!   r$   r~     s    
$r~   )	metaclassz&keras.metrics.SensitivityAtSpecificityc                       D   e Zd ZdZej				d
 fdd	Zdd Z fdd	Z  Z	S )SensitivityAtSpecificitya  Computes best sensitivity where specificity is >= specified value.

    the sensitivity at a given specificity.

    `Sensitivity` measures the proportion of actual positives that are correctly
    identified as such (tp / (tp + fn)).
    `Specificity` measures the proportion of actual negatives that are correctly
    identified as such (tn / (tn + fp)).

    This metric creates four local variables, `true_positives`,
    `true_negatives`, `false_positives` and `false_negatives` that are used to
    compute the sensitivity at the given specificity. The threshold for the
    given specificity value is computed and used to evaluate the corresponding
    sensitivity.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `class_id` is specified, we calculate precision by considering only the
    entries in the batch for which `class_id` is above the threshold
    predictions, and computing the fraction of them for which `class_id` is
    indeed a correct label.

    For additional information about specificity and sensitivity, see
    [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).

    Args:
      specificity: A scalar value in range `[0, 1]`.
      num_thresholds: (Optional) The number of thresholds to
        use for matching the given specificity. Defaults to `200`.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.SensitivityAtSpecificity(0.5)
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
    >>> m.result().numpy()
    0.5

    >>> m.reset_state()
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
    ...                sample_weight=[1, 1, 2, 2, 1])
    >>> m.result().numpy()
    0.333333

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='binary_crossentropy',
        metrics=[tf.keras.metrics.SensitivityAtSpecificity()])
    ```
    r   Nc                    D   |dk s|dkrt d| || _|| _t j|||||d d S )Nr   r-   zJArgument `specificity` must be in the range [0, 1]. Received: specificity=rs   rc   r   r   )r   specificityrs   r   r   )r   r   rs   rc   r   r   r!   r#   r$   r   @     	
z!SensitivityAtSpecificity.__init__c                 C   L   t j| jt j| j| j}t j| jt j| j| j}| ||t j	S rE   )
r.   rk   rl   r   rm   ra   r`   r}   r   greater_equal)r   specificitiessensitivitiesr#   r#   r$   r0   X     zSensitivityAtSpecificity.resultc                    4   | j | jd}t  }tt| t|  S )N)rs   r   )rs   r   r   r<   r=   r>   r?   r@   r!   r#   r$   r<   e  
   
z#SensitivityAtSpecificity.get_configr   
rF   rG   rH   rI   rT   rU   r   r0   r<   rJ   r#   r#   r!   r$   r     s    ;r   z&keras.metrics.SpecificityAtSensitivityc                       r   )SpecificityAtSensitivitya  Computes best specificity where sensitivity is >= specified value.

    `Sensitivity` measures the proportion of actual positives that are correctly
    identified as such (tp / (tp + fn)).
    `Specificity` measures the proportion of actual negatives that are correctly
    identified as such (tn / (tn + fp)).

    This metric creates four local variables, `true_positives`,
    `true_negatives`, `false_positives` and `false_negatives` that are used to
    compute the specificity at the given sensitivity. The threshold for the
    given sensitivity value is computed and used to evaluate the corresponding
    specificity.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `class_id` is specified, we calculate precision by considering only the
    entries in the batch for which `class_id` is above the threshold
    predictions, and computing the fraction of them for which `class_id` is
    indeed a correct label.

    For additional information about specificity and sensitivity, see
    [the following](https://en.wikipedia.org/wiki/Sensitivity_and_specificity).

    Args:
      sensitivity: A scalar value in range `[0, 1]`.
      num_thresholds: (Optional) The number of thresholds to
        use for matching the given sensitivity. Defaults to `200`.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.SpecificityAtSensitivity(0.5)
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
    >>> m.result().numpy()
    0.66666667

    >>> m.reset_state()
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
    ...                sample_weight=[1, 1, 2, 2, 2])
    >>> m.result().numpy()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='binary_crossentropy',
        metrics=[tf.keras.metrics.SpecificityAtSensitivity()])
    ```
    r   Nc                    r   )Nr   r-   zJArgument `sensitivity` must be in the range [0, 1]. Received: sensitivity=r   )r   sensitivityrs   r   r   )r   r   rs   rc   r   r   r!   r#   r$   r     r   z!SpecificityAtSensitivity.__init__c                 C   r   rE   )
r.   rk   rl   r`   rm   r}   r   ra   r   r   )r   r   r   r#   r#   r$   r0     r   zSpecificityAtSensitivity.resultc                    r   )N)rs   r   )rs   r   r   r<   r=   r>   r?   r@   r!   r#   r$   r<     r   z#SpecificityAtSensitivity.get_configr   r   r#   r#   r!   r$   r   n  s    9r   zkeras.metrics.PrecisionAtRecallc                       s>   e Zd ZdZej	d
 fdd	Zdd Z fdd	Z  Z	S )PrecisionAtRecalla  Computes best precision where recall is >= specified value.

    This metric creates four local variables, `true_positives`,
    `true_negatives`, `false_positives` and `false_negatives` that are used to
    compute the precision at the given recall. The threshold for the given
    recall value is computed and used to evaluate the corresponding precision.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `class_id` is specified, we calculate precision by considering only the
    entries in the batch for which `class_id` is above the threshold
    predictions, and computing the fraction of them for which `class_id` is
    indeed a correct label.

    Args:
      recall: A scalar value in range `[0, 1]`.
      num_thresholds: (Optional) The number of thresholds to
        use for matching the given recall. Defaults to `200`.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.PrecisionAtRecall(0.5)
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8])
    >>> m.result().numpy()
    0.5

    >>> m.reset_state()
    >>> m.update_state([0, 0, 0, 1, 1], [0, 0.3, 0.8, 0.3, 0.8],
    ...                sample_weight=[2, 2, 2, 1, 1])
    >>> m.result().numpy()
    0.33333333

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='binary_crossentropy',
        metrics=[tf.keras.metrics.PrecisionAtRecall(recall=0.8)])
    ```
    r   Nc                    r   )Nr   r-   z@Argument `recall` must be in the range [0, 1]. Received: recall=r   rs   rc   r   r   )r   recallrs   r   r   )r   r   rs   rc   r   r   r!   r#   r$   r   	  s   
zPrecisionAtRecall.__init__c                 C   L   t j| jt j| j| j}t j| jt j| j| j}| ||t jS rE   )	r.   rk   rl   r`   rm   r}   ra   r   r   )r   recalls
precisionsr#   r#   r$   r0     r   zPrecisionAtRecall.resultc                    r   )N)rs   r   )rs   r   r   r<   r=   r>   r?   r@   r!   r#   r$   r<   )  s   
zPrecisionAtRecall.get_configr   r   r#   r#   r!   r$   r     s    0r   zkeras.metrics.RecallAtPrecisionc                       r   )RecallAtPrecisionar  Computes best recall where precision is >= specified value.

    For a given score-label-distribution the required precision might not
    be achievable, in this case 0.0 is returned as recall.

    This metric creates four local variables, `true_positives`,
    `true_negatives`, `false_positives` and `false_negatives` that are used to
    compute the recall at the given precision. The threshold for the given
    precision value is computed and used to evaluate the corresponding recall.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    If `class_id` is specified, we calculate precision by considering only the
    entries in the batch for which `class_id` is above the threshold
    predictions, and computing the fraction of them for which `class_id` is
    indeed a correct label.

    Args:
      precision: A scalar value in range `[0, 1]`.
      num_thresholds: (Optional) The number of thresholds to
        use for matching the given precision. Defaults to `200`.
      class_id: (Optional) Integer class ID for which we want binary metrics.
        This must be in the half-open interval `[0, num_classes)`, where
        `num_classes` is the last dimension of predictions.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.

    Standalone usage:

    >>> m = tf.keras.metrics.RecallAtPrecision(0.8)
    >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
    >>> m.result().numpy()
    0.5

    >>> m.reset_state()
    >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9],
    ...                sample_weight=[1, 0, 0, 1])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='binary_crossentropy',
        metrics=[tf.keras.metrics.RecallAtPrecision(precision=0.8)])
    ```
    r   Nc                    r   )Nr   r-   zFArgument `precision` must be in the range [0, 1]. Received: precision=r   )r   	precisionrs   r   r   )r   r   rs   rc   r   r   r!   r#   r$   r   d  r   zRecallAtPrecision.__init__c                 C   r   rE   )	r.   rk   rl   r`   rm   ra   r}   r   r   )r   r   r   r#   r#   r$   r0   |  r   zRecallAtPrecision.resultc                    r   )N)rs   r   )rs   r   r   r<   r=   r>   r?   r@   r!   r#   r$   r<     r   zRecallAtPrecision.get_configr   r   r#   r#   r!   r$   r   /  s    3r   zkeras.metrics.AUCc                       s~   e Zd ZdZej										d fdd	Zed	d
 Zdd Z	dddZ
dd Zdd Zdd Z fddZ  ZS )AUCa  Approximates the AUC (Area under the curve) of the ROC or PR curves.

    The AUC (Area under the curve) of the ROC (Receiver operating
    characteristic; default) or PR (Precision Recall) curves are quality
    measures of binary classifiers. Unlike the accuracy, and like cross-entropy
    losses, ROC-AUC and PR-AUC evaluate all the operational points of a model.

    This class approximates AUCs using a Riemann sum. During the metric
    accumulation phrase, predictions are accumulated within predefined buckets
    by value. The AUC is then computed by interpolating per-bucket averages.
    These buckets define the evaluated operational points.

    This metric 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.

    This value is ultimately returned as `auc`, an idempotent operation that
    computes the area under a discretized curve of precision versus recall
    values (computed using the aforementioned variables). The `num_thresholds`
    variable controls the degree of discretization with larger numbers of
    thresholds more closely approximating the true AUC. The quality of the
    approximation may vary dramatically depending on `num_thresholds`. The
    `thresholds` parameter can be used to manually specify thresholds which
    split the predictions more evenly.

    For a best approximation of the real AUC, `predictions` should be
    distributed approximately uniformly in the range [0, 1] (if
    `from_logits=False`). The quality of the AUC approximation may be poor if
    this is not the case. Setting `summation_method` to 'minoring' or 'majoring'
    can help quantify the error in the approximation by providing lower or upper
    bound estimate of the AUC.

    If `sample_weight` is `None`, weights default to 1.
    Use `sample_weight` of 0 to mask values.

    Args:
      num_thresholds: (Optional) The number of thresholds to
        use when discretizing the roc curve. Values must be > 1.
        Defaults to `200`.
      curve: (Optional) Specifies the name of the curve to be computed, 'ROC'
        [default] or 'PR' for the Precision-Recall-curve.
      summation_method: (Optional) Specifies the [Riemann summation method](
          https://en.wikipedia.org/wiki/Riemann_sum) used.
          'interpolation' (default) applies mid-point summation scheme for
          `ROC`.  For PR-AUC, interpolates (true/false) positives but not the
          ratio that is precision (see Davis & Goadrich 2006 for details);
          'minoring' applies left summation for increasing intervals and right
          summation for decreasing intervals; 'majoring' does the opposite.
      name: (Optional) string name of the metric instance.
      dtype: (Optional) data type of the metric result.
      thresholds: (Optional) A list of floating point values to use as the
        thresholds for discretizing the curve. If set, the `num_thresholds`
        parameter is ignored. Values should be in [0, 1]. Endpoint thresholds
        equal to {-epsilon, 1+epsilon} for a small positive epsilon value will
        be automatically included with these to correctly handle predictions
        equal to exactly 0 or 1.
      multi_label: boolean indicating whether multilabel data should be
        treated as such, wherein AUC is computed separately for each label and
        then averaged across labels, or (when False) if the data should be
        flattened into a single label before AUC computation. In the latter
        case, when multilabel data is passed to AUC, each label-prediction pair
        is treated as an individual data point. Should be set to False for
        multi-class data.
      num_labels: (Optional) The number of labels, used when `multi_label` is
        True. If `num_labels` is not specified, then state variables get created
        on the first call to `update_state`.
      label_weights: (Optional) list, array, or tensor of non-negative weights
        used to compute AUCs for multilabel data. When `multi_label` is True,
        the weights are applied to the individual label AUCs when they are
        averaged to produce the multi-label AUC. When it's False, they are used
        to weight the individual label predictions in computing the confusion
        matrix on the flattened data. Note that this is unlike class_weights in
        that class_weights weights the example depending on the value of its
        label, whereas label_weights depends only on the index of that label
        before flattening; therefore `label_weights` should not be used for
        multi-class data.
      from_logits: boolean indicating whether the predictions (`y_pred` in
        `update_state`) are probabilities or sigmoid logits. As a rule of thumb,
        when using a keras loss, the `from_logits` constructor argument of the
        loss should match the AUC `from_logits` constructor argument.

    Standalone usage:

    >>> m = tf.keras.metrics.AUC(num_thresholds=3)
    >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9])
    >>> # threshold values are [0 - 1e-7, 0.5, 1 + 1e-7]
    >>> # tp = [2, 1, 0], fp = [2, 0, 0], fn = [0, 1, 2], tn = [0, 2, 2]
    >>> # tp_rate = recall = [1, 0.5, 0], fp_rate = [1, 0, 0]
    >>> # auc = ((((1+0.5)/2)*(1-0)) + (((0.5+0)/2)*(0-0))) = 0.75
    >>> m.result().numpy()
    0.75

    >>> m.reset_state()
    >>> m.update_state([0, 0, 1, 1], [0, 0.5, 0.3, 0.9],
    ...                sample_weight=[1, 0, 0, 1])
    >>> m.result().numpy()
    1.0

    Usage with `compile()` API:

    ```python
    # Reports the AUC of a model outputting a probability.
    model.compile(optimizer='sgd',
                  loss=tf.keras.losses.BinaryCrossentropy(),
                  metrics=[tf.keras.metrics.AUC()])

    # Reports the AUC of a model outputting a logit.
    model.compile(optimizer='sgd',
                  loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
                  metrics=[tf.keras.metrics.AUC(from_logits=True)])
    ```
    r   ROCinterpolationNFc                    s  t |tjr|ttjvrtd| dttj t |tjr4|ttjvr4td| dttj |d u| _|d urXt|d | _t	|}t
tdg| dg | _n dkrctd   | _ fd	d
t d D }d| _tdt  g| dt  g | _t |tjr|| _ntj|| _t |tjr|| _ntj|| _t j||d || _|| _|	d urtj|	| jd}	tjj|	dd |	| _nd | _|
| _d| _ | jr|rt!d |g}| "| d S d S |rtd| "d  d S )Nz Invalid `curve` argument value "z". Expected one of: z+Invalid `summation_method` argument value "r   r   r   r-   zKArgument `num_thresholds` must be an integer > 1. Received: num_thresholds=c                    r   r   r#   r   rr   r#   r$   r6   =  r   z AUC.__init__.<locals>.<listcomp>Tr   )r   z3All values of `label_weights` must be non-negative.messageFz7`num_labels` is needed only when `multi_label` is True.)#
isinstancer   AUCCurver>   r   AUCSummationMethod_init_from_thresholdsr   rs   sortedr   r1   arrayr   r   r   epsilon_thresholdscurveZfrom_strsummation_methodr   r   multi_label
num_labelsr.   Zconstantr   	debuggingZassert_non_negativelabel_weights_from_logits_builtTensorShape_build)r   rs   r   r   r   r   r   r   r   r   from_logitsr   r!   rr   r$   r   	  s   


zAUC.__init__c                 C   s
   t | jS )z'The thresholds used for evaluating AUC.)r>   r   r9   r#   r#   r$   r   q  s   
zAUC.thresholdsc                 C   s   | j r"|jdkrtd|j d| |d | _t| j| jg}nt| jg}|| _| jd|dd| _	| jd|dd| _
| jd	|dd| _| jd
|dd| _| j rrt  t sctt  W d   n1 smw   Y  d| _dS )zKInitialize TP, FP, TN, and FN tensors, given the shape of the
        data.r   z>`y_pred` must have rank 2 when `multi_label=True`. Found rank z$. Full shape received for `y_pred`: r-   r`   r   r   r   ra   r}   NT)r   Zndimsr   _num_labelsr.   r   rs   Z_build_input_shaper   r`   r   ra   r}   Z
init_scopeZexecuting_eagerlyr   Z_initialize_variablesZ_get_sessionr   )r   r   Zvariable_shaper#   r#   r$   r   v  sD   




z
AUC._buildc              
   C   s   | j s| t|j | js| jdurF|dfg}| jr1|| jdf| j	df| j
df| jdfg | jdurF|| jdf tjj|dd | jrKdn| j}| jrVt|}tjtjj| jtjj| j	tjj| j
tjj| ji||| j| j|| j|dS )r   N)NL)Tr   )r   z#Number of labels is not consistent.r   )r%   r&   r   r   )r   r   r.   r   r   r   r   extendr`   r   ra   r}   appendr   Zassert_shapesr   r   Zsigmoidr   r'   rO   r\   rZ   rP   rX   r   r   )r   r)   r*   r&   Zshapesr   r#   r#   r$   r+     sD   






zAUC.update_statec           	   
   C   s  | j d| jd  | j dd  }tj| j | j}|d| jd  |dd  }tjj|t|ddd}| j dd t||dd  }t	t
|d| jd  dk|dd dktjj|d| jd  t|dd dddt|dd }tjj|||tj|   t| j dd | jdd  ddd}| jrtj|| jd dd	}| jdu rtj|| jdS tjjtt|| jt| j| jdS tj|d
dS )ak  Interpolation formula inspired by section 4 of Davis & Goadrich 2006.

        https://www.biostat.wisc.edu/~page/rocpr.pdf

        Note here we derive & use a closed formula not present in the paper
        as follows:

          Precision = TP / (TP + FP) = TP / P

        Modeling all of TP (true positive), FP (false positive) and their sum
        P = TP + FP (predicted positive) as varying linearly within each
        interval [A, B] between successive thresholds, we get

          Precision slope = dTP / dP
                          = (TP_B - TP_A) / (P_B - P_A)
                          = (TP - TP_A) / (P - P_A)
          Precision = (TP_A + slope * (P - P_A)) / P

        The area within the interval is (slope / total_pos_weight) times

          int_A^B{Precision.dP} = int_A^B{(TP_A + slope * (P - P_A)) * dP / P}
          int_A^B{Precision.dP} = int_A^B{slope * dP + intercept * dP / P}

        where intercept = TP_A - slope * P_A = TP_B - slope * P_B, resulting in

          int_A^B{Precision.dP} = TP_B - TP_A + intercept * log(P_B / P_A)

        Bringing back the factor (slope / total_pos_weight) we'd put aside, we
        get

          slope * [dTP + intercept *  log(P_B / P_A)] / total_pos_weight

        where dTP == TP_B - TP_A.

        Note that when P_A == 0 the above calculation simplifies into

          int_A^B{Precision.dTP} = int_A^B{slope * dTP} = slope * (TP_B - TP_A)

        which is really equivalent to imputing constant precision throughout the
        first bucket having >0 true positives.

        Returns:
          pr_auc: an approximation of the area under the P-R curve.
        Nr-   r   
prec_sloper   Zrecall_relative_ratiopr_auc_increment	_by_labelr   Zaxisinterpolate_pr_auc)r`   rs   r.   rk   rm   ra   rl   maximummultiplyr   logical_andZ	ones_likelogr}   r   
reduce_sumr   r   reduce_mean)	r   ZdtppZdpr   Z	interceptZsafe_p_ratior   by_label_aucr#   r#   r$   r     sL   ."(
"

zAUC.interpolate_pr_aucc           	      C   s  | j tjjkr| jtjjkr|  S tj	
| jtj	| j| j}| j tjjkr<tj	
| jtj	| j| j}|}|}ntj	
| jtj	| j| j}|}|}| jtjjkrh|d | jd  |dd   d }n*| jtjjkrt|d | jd  |dd  }nt|d | jd  |dd  }| jrt|d | jd  |dd   |}tj|| jd dd}| jd u rtj|| jdS tj	j
tt|| jt| j| jdS tjt|d | jd  |dd   || jdS )Nr-   g       @r   r   r   r   )r   r   r   ZPRr   r   ZINTERPOLATIONr   r.   rk   rl   r`   rm   r}   r   ra   r   rs   ZMINORINGminimumr   r   r   r   r   r   r   )	r   r   Zfp_ratexyr   ZheightsZriemann_termsr   r#   r#   r$   r0   9  sh   $$"

$z
AUC.resultc                    s\    j r, j j j jf} jrt fdd|D  d S t fdd|D  d S d S )Nc                    s"   g | ]}|t  j jffqS r#   )r1   r   rs   r   r3   r9   r#   r$   r6     s    z#AUC.reset_state.<locals>.<listcomp>c                    s   g | ]}|t  jffqS r#   )r1   r   rs   r3   r9   r#   r$   r6     s    )r   r`   r   ra   r}   r   r   r7   r   r#   r9   r$   r:   ~  s$   

zAUC.reset_statec                    s   t | jrt| j}n| j}| j| jj| jj| j| j	|| j
d}| jr-| jdd |d< t  }tt| t|  S )N)rs   r   r   r   r   r   r   r-   r   )r   r   r   evalrs   r   r   r   r   r   r   r   r   r   r<   r=   r>   r?   )r   r   rA   rB   r!   r#   r$   r<     s   

zAUC.get_config)
r   r   r   NNNFNNFrE   )rF   rG   rH   rI   rT   rU   r   propertyr   r   r+   r   r0   r:   r<   rJ   r#   r#   r!   r$   r     s,    ug

*>[Er   )'rI   abcnumpyr1   Ztensorflow.compat.v2compatv2r.   Z	keras.srcr   r   Zkeras.src.dtensorr   rT   Zkeras.src.metricsr   Zkeras.src.utilsr   Zkeras.src.utils.generic_utilsr   Zkeras.src.utils.tf_utilsr   Z tensorflow.python.util.tf_exportr	   ZMetricr
   rL   rW   rY   r[   r^   r|   ABCMetar~   r   r   r   r   r   r#   r#   r#   r$   <module>   sL   F<<<< " sjhWb