
    2VhbG                     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 Z	 ed       G d d	ej                               Z ed
      d$d       Z ed       G d dej                               Z ed      d        Z ed       G d dej                               Z ed      d        Z ed       G d dej                               Z ed      d%d       Z ed       G d dej                               Z ed      	 d&d       Z ed        G d! d"ej                               Zy#)'    )backend)ops)keras_export)squeeze_or_expand_to_same_rank)reduction_metricsc                    t        j                  |      }t        j                  | |j                        } t        | |      \  } }t        j                  t        j
                  | |      t        j                               S Ndtype)r   convert_to_tensorr   r   castequalr   floatx)y_truey_preds     R/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/metrics/accuracy_metrics.pyaccuracyr      s[    ""6*F""6>F3FFCNFF88CIIff-W^^5EFF    zkeras.metrics.Accuracyc                   *     e Zd ZdZd fd	Zd Z xZS )Accuracya/  Calculates how often predictions equal labels.

    This metric creates two local variables, `total` and `count` that are used
    to compute the frequency with which `y_pred` matches `y_true`. This
    frequency is ultimately returned as `binary accuracy`: an idempotent
    operation that simply divides `total` by `count`.

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

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.

    Examples:

    >>> m = keras.metrics.Accuracy()
    >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]])
    >>> m.result()
    0.75

    >>> m.reset_state()
    >>> m.update_state([[1], [2], [3], [4]], [[0], [2], [3], [4]],
    ...                sample_weight=[1, 1, 0, 0])
    >>> m.result()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[keras.metrics.Accuracy()])
    ```
    c                 @    t         |   t        ||       d| _        y N)fnnamer   up)super__init__r   
_directionselfr   r   	__class__s      r   r   zAccuracy.__init__5   s    H4u=r   c                 4    | j                   | j                  dS Nr   r   r$   r    s    r   
get_configzAccuracy.get_config:       		DJJ77r   )r   N__name__
__module____qualname____doc__r   r&   __classcell__r!   s   @r   r   r      s    "H
8r   r   zkeras.metrics.binary_accuracyc                    t        j                  |      }t        j                  |       } t        j                  |      }t        | |      \  } }t        j                  t        j                  ||      | j
                        }t        j                  t        j                  | |      t        j                               S r	   )	r   r   r   r   greaterr   r   r   r   )r   r   	thresholds      r   binary_accuracyr2   >   s    ""6*F""6*F%%i0I3FFCNFFXXckk&)4fllCF88CIIff-W^^5EFFr   zkeras.metrics.BinaryAccuracyc                   *     e Zd ZdZd fd	Zd Z xZS )BinaryAccuracya  Calculates how often predictions match binary labels.

    This metric creates two local variables, `total` and `count` that are used
    to compute the frequency with which `y_pred` matches `y_true`. This
    frequency is ultimately returned as `binary accuracy`: an idempotent
    operation that simply divides `total` by `count`.

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

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.
        threshold: (Optional) Float representing the threshold for deciding
        whether prediction values are 1 or 0.

    Example:

    >>> m = keras.metrics.BinaryAccuracy()
    >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]])
    >>> m.result()
    0.75

    >>> m.reset_state()
    >>> m.update_state([[1], [1], [0], [0]], [[0.98], [1], [0], [0.6]],
    ...                sample_weight=[1, 0, 0, 1])
    >>> m.result()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='binary_crossentropy',
                  metrics=[keras.metrics.BinaryAccuracy()])
    ```
    c                 P    t         |   t        |||       || _        d| _        y )N)r   r   r   r1   r   )r   r   r2   r1   r   )r    r   r   r1   r!   s       r   r   zBinaryAccuracy.__init__p   s.    T) 	 	
 #r   c                 J    | j                   | j                  | j                  dS )Nr   r   r1   r7   r%   s    r   r&   zBinaryAccuracy.get_configx   s!    IIZZ
 	
r   )r2   N      ?r(   r.   s   @r   r4   r4   H   s    $L
r   r4   z"keras.metrics.categorical_accuracyc                    t        j                  | d      } d}t        j                  |      }t        j                  | |j                        } t        j                  |       }t        |j                        }t        | j                        }|E|Ct        | j                        t        |j                        k(  rt        j                  | d      } d}t        j                  |d      }|j                  | j                  ur!t        j                  || j                        }t        j                  t        j                  | |      t        j                               }|rt        j                  ||      }|S )NaxisFr
   T)r   argmaxr   r   shapelensqueezer   r   r   r   reshaper   r   reshape_matchesy_true_org_shapey_pred_ranky_true_rankmatchess          r   categorical_accuracyrH      s   ZZR(FO""6*F""6>Fyy(fll#Kfll#K 
	 $#fll"33VR(ZZR(F ||6<<'&5hhsyy0'..2BCG++g'78Nr   z!keras.metrics.CategoricalAccuracyc                   *     e Zd ZdZd fd	Zd Z xZS )CategoricalAccuracya  Calculates how often predictions match one-hot labels.

    You can provide logits of classes as `y_pred`, since argmax of
    logits and probabilities are same.

    This metric creates two local variables, `total` and `count` that are used
    to compute the frequency with which `y_pred` matches `y_true`. This
    frequency is ultimately returned as `categorical accuracy`: an idempotent
    operation that simply divides `total` by `count`.

    `y_pred` and `y_true` should be passed in as vectors of probabilities,
    rather than as labels. If necessary, use `ops.one_hot` to expand `y_true` as
    a vector.

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

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.

    Example:

    >>> m = keras.metrics.CategoricalAccuracy()
    >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
    ...                 [0.05, 0.95, 0]])
    >>> m.result()
    0.5

    >>> m.reset_state()
    >>> m.update_state([[0, 0, 1], [0, 1, 0]], [[0.1, 0.9, 0.8],
    ...                 [0.05, 0.95, 0]],
    ...                sample_weight=[0.7, 0.3])
    >>> m.result()
    0.3

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=[keras.metrics.CategoricalAccuracy()])
    ```
    c                 @    t         |   t        ||       d| _        y r   )r   r   rH   r   r   s      r   r   zCategoricalAccuracy.__init__   s    0t5Ir   c                 4    | j                   | j                  dS r#   r$   r%   s    r   r&   zCategoricalAccuracy.get_config   r'   r   )rH   Nr(   r.   s   @r   rJ   rJ      s    +Z
8r   rJ   z)keras.metrics.sparse_categorical_accuracyc                 ~   d}t        j                  |      }t        j                  | |j                        } t        j                  |       }t	        |j                        }t	        | j                        }|`|^t	        | j                        t	        |j                        k(  r3t        j                  |       d   dk(  rt        j
                  | d      } d}t        j                  |d      }|j                  | j                  ur t        j                  || j                        }t        j                  t        j                  | |      t        j                               }|rt        j                  ||      }t	        |j                        dkD  r(|j                  d   dk(  rt        j
                  |d      }|S )NFr
   r:      Tr;   )r   r   r   r>   r?   r@   r=   r   r   r   r   rA   rB   s          r   sparse_categorical_accuracyrO      sM   O""6*F""6>Fyy(fll#Kfll#K 
	 $#fll"33IIfb!Q&VR(ZZR(F ||6<<'&&,,/hhsyy0'..2BCG++g'78
7==A'--"3q"8++gr*Nr   z'keras.metrics.SparseCategoricalAccuracyc                   *     e Zd ZdZd fd	Zd Z xZS )SparseCategoricalAccuracyaC  Calculates how often predictions match integer labels.

    ```python
    acc = np.dot(sample_weight, np.equal(y_true, np.argmax(y_pred, axis=1))
    ```

    You can provide logits of classes as `y_pred`, since argmax of
    logits and probabilities are same.

    This metric creates two local variables, `total` and `count` that are used
    to compute the frequency with which `y_pred` matches `y_true`. This
    frequency is ultimately returned as `sparse categorical accuracy`: an
    idempotent operation that simply divides `total` by `count`.

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

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.

    Example:

    >>> m = keras.metrics.SparseCategoricalAccuracy()
    >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]])
    >>> m.result()
    0.5

    >>> m.reset_state()
    >>> m.update_state([[2], [1]], [[0.1, 0.6, 0.3], [0.05, 0.95, 0]],
    ...                sample_weight=[0.7, 0.3])
    >>> m.result()
    0.3

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='sparse_categorical_crossentropy',
                  metrics=[keras.metrics.SparseCategoricalAccuracy()])
    ```
    c                 @    t         |   t        ||       d| _        y r   )r   r   rO   r   r   s      r   r   z"SparseCategoricalAccuracy.__init__&  s    7d%Pr   c                 4    | j                   | j                  dS r#   r$   r%   s    r   r&   z$SparseCategoricalAccuracy.get_config+  r'   r   )rO   Nr(   r.   s   @r   rQ   rQ      s    )V
8r   rQ   z(keras.metrics.top_k_categorical_accuracyc                    d}t        j                  |      }t        j                  | |j                        } t        j                  | d      } t	        | j
                        }t	        |j
                        }t        j
                  |       }|J|H|dkD  r%t        j                  |d|j
                  d   g      }|dkD  rd}t        j                  | dg      } t        j                  t        j                  t        j                  | d      ||	      t        j                               }|rt        j                  ||      }|S )
NFr
   r:   r;      rN   Tint32k)r   r   r   r=   r?   r>   rA   r   in_top_kr   r   )r   r   rX   rC   rF   rE   rD   rG   s           r   top_k_categorical_accuracyrZ   /  s   O""6*F""6>FZZR(Ffll#Kfll#Kyy( 	k&=?[["fll2.>)?@F?"O[[".FhhSXXfg.!<nnG ++g'78Nr   z%keras.metrics.TopKCategoricalAccuracyc                   *     e Zd ZdZd fd	Zd Z xZS )TopKCategoricalAccuracya  Computes how often targets are in the top `K` predictions.

    Args:
        k: (Optional) Number of top elements to look at for computing accuracy.
            Defaults to `5`.
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.

    Example:

    >>> m = keras.metrics.TopKCategoricalAccuracy(k=1)
    >>> m.update_state([[0, 0, 1], [0, 1, 0]],
    ...                [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
    >>> m.result()
    0.5

    >>> m.reset_state()
    >>> m.update_state([[0, 0, 1], [0, 1, 0]],
    ...                [[0.1, 0.9, 0.8], [0.05, 0.95, 0]],
    ...                sample_weight=[0.7, 0.3])
    >>> m.result()
    0.3

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='categorical_crossentropy',
                  metrics=[keras.metrics.TopKCategoricalAccuracy()])
    ```
    c                 P    t         |   t        |||       || _        d| _        y )N)r   r   r   rX   r   )r   r   rZ   rX   r   )r    rX   r   r   r!   s       r   r   z TopKCategoricalAccuracy.__init__o  s1    )	 	 	
 r   c                 J    | j                   | j                  | j                  dS )Nr   r   rX   r_   r%   s    r   r&   z"TopKCategoricalAccuracy.get_configz  s    		DJJTVVDDr   )   rZ   Nr(   r.   s   @r   r\   r\   M  s    @	Er   r\   z/keras.metrics.sparse_top_k_categorical_accuracyc           	         d}t        j                  |      }|r|j                  nd}t        j                  | |      } t        | j                        }t        |j                        }t        j                  |       }|J|H|dkD  r%t        j
                  |d|j                  d   g      }|dkD  rd}t        j
                  | dg      } |rJt        j                  t        j                  t        j                  | d	      |ddd|f         d	      }	nt        j                  | ||
      }	t        j                  |	t        j                               }	|rt        j
                  |	|      }	|	S )a  Computes how often integer targets are in the top `K` predictions.

    Args:
        y_true: A tensor of shape `(batch_size)` representing indices or IDs of
            true categories.
        y_pred: If `from_sorted_ids=False`, a tensor of shape
            `(batch_size, num_categories)` containing the scores for each sample
            for all possible categories. If `from_sorted_ids=True`, a tensor of
            shape `(batch_size, N)` containing indices or IDs of the top `N`
            categories in order from highest score to lowest score.
        k: (Optional) Number of top elements to look at for computing accuracy.
            Defaults to `5`.
        from_sorted_ids: (Optional) Whether `y_pred` is sorted category IDs or
            scores for all categories (the default).

    Returns:
        A tensor with the same shape as `y_true` containing ones where `y_true`
        is in the top `k` and zeros elsewhere.
    FrV   r
   NrU   r:   rN   Tr;   rW   )r   r   r   r?   r>   rA   anyr   expand_dimsrY   r   r   r   )
r   r   rX   from_sorted_idsrC   y_true_dtyperF   rE   rD   rG   s
             r   !sparse_top_k_categorical_accuracyrf   ~  s3   . O""6*F#26<<L""6>Ffll#Kfll#Kyy( 	k&=?[["fll2.>)?@F?"O[[".F ''IIcoof15va!e}EA
 ,,vv3hhwgnn&67G ++g'78Nr   z+keras.metrics.SparseTopKCategoricalAccuracyc                   2     e Zd ZdZ	 	 	 	 d fd	Zd Z xZS )SparseTopKCategoricalAccuracya	  Computes how often integer targets are in the top `K` predictions.

    By default, the arguments expected by `update_state()` are:
    - `y_true`: a tensor of shape `(batch_size)` representing indices of true
        categories.
    - `y_pred`: a tensor of shape `(batch_size, num_categories)` containing the
        scores for each sample for all possible categories.

    With `from_sorted_ids=True`, the arguments expected by `update_state` are:
    - `y_true`: a tensor of shape `(batch_size)` representing indices or IDs of
        true categories.
    - `y_pred`: a tensor of shape `(batch_size, N)` containing the indices or
        IDs of the top `N` categories sorted in order from highest score to
        lowest score. `N` must be greater or equal to `k`.

    The `from_sorted_ids=True` option can be more efficient when the set of
    categories is very large and the model has an optimized way to retrieve the
    top ones either without scoring or without maintaining the scores for all
    the possible categories.

    Args:
        k: (Optional) Number of top elements to look at for computing accuracy.
            Defaults to `5`.
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.
        from_sorted_ids: (Optional) When `False`, the default, the tensor passed
            in `y_pred` contains the unsorted scores of all possible categories.
            When `True`, `y_pred` contains a the indices or IDs for the top
            categories.

    Example:

    >>> m = keras.metrics.SparseTopKCategoricalAccuracy(k=1)
    >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]])
    >>> m.result()
    0.5

    >>> m.reset_state()
    >>> m.update_state([2, 1], [[0.1, 0.9, 0.8], [0.05, 0.95, 0]],
    ...                sample_weight=[0.7, 0.3])
    >>> m.result()
    0.3

    >>> m = keras.metrics.SparseTopKCategoricalAccuracy(k=1,
    ...                                                from_sorted_ids=True)
    >>> m.update_state([2, 1], [[1, 0, 3], [1, 2, 3]])
    >>> m.result()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='sparse_categorical_crossentropy',
                  metrics=[keras.metrics.SparseTopKCategoricalAccuracy()])
    ```
    c                 `    t         |   t        ||||       || _        || _        d| _        y )N)r   r   r   rX   rd   r   )r   r   rf   rX   rd   r   )r    rX   r   r   rd   r!   s        r   r   z&SparseTopKCategoricalAccuracy.__init__  s>     	0+ 	 	
 .r   c                 p    | j                   | j                  | j                  d}| j                  rd|d<   |S )Nr_   Trd   )r   r   rX   rd   )r    configs     r   r&   z(SparseTopKCategoricalAccuracy.get_config  s3    ))djjtvvF(,F$%r   )r`   rf   NFr(   r.   s   @r   rh   rh     s!    8x 0&r   rh   N)r8   )r`   )r`   F)	keras.srcr   r   keras.src.api_exportr   keras.src.losses.lossr   keras.src.metricsr   r   MeanMetricWrapperr   r2   r4   rH   rJ   rO   rQ   rZ   r\   rf   rh    r   r   <module>rr      s     - @ /G &'+8 22 +8 (+8\ -.G /G ,-4
&88 4
 .4
n 23 4> 1248+== 48 348n 9: ;@ 7828 1 C C 28 928j 89 :: 56-E/AA -E 7-E` ?@).5 A5p ;<R$5$G$G R =Rr   