
    2Vh7"                         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  ed	d
g       G d de             Zy)    )backend)dtype_policies)initializers)ops)keras_export)KerasSaveable)	auto_name)Trackerzkeras.Metriczkeras.metrics.Metricc                        e Zd ZdZddZd Zd Zd Zd Zd Z	d Z
ed	        Zd
 Z	 ddZddZed        Zd Zd Zed        Z fdZd Zd Zd Z xZS )Metrica
  Encapsulates metric logic and state.

    Args:
        name: Optional name for the metric instance.
        dtype: The dtype of the metric's computations. Defaults to `None`, which
            means using `keras.backend.floatx()`. `keras.backend.floatx()` is a
            `"float32"` unless set to different value
            (via `keras.backend.set_floatx()`). If a `keras.DTypePolicy` is
            provided, then the `compute_dtype` will be utilized.

    Example:

    ```python
    m = SomeMetric(...)
    for input in ...:
        m.update_state(input)
    print('Final result: ', m.result())
    ```

    Usage with `compile()` API:

    ```python
    model = keras.Sequential()
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dense(64, activation='relu'))
    model.add(keras.layers.Dense(10, activation='softmax'))

    model.compile(optimizer=keras.optimizers.RMSprop(0.01),
                  loss=keras.losses.CategoricalCrossentropy(),
                  metrics=[keras.metrics.CategoricalAccuracy()])

    data = np.random.random((1000, 32))
    labels = np.random.random((1000, 10))

    model.fit(data, labels, epochs=10)
    ```

    To be implemented by subclasses:

    * `__init__()`: All state variables should be created in this method by
      calling `self.add_variable()` like: `self.var = self.add_variable(...)`
    * `update_state()`: Has all updates to the state variables like:
      `self.var.assign(...)`.
    * `result()`: Computes and returns a scalar value or a dict of scalar values
      for the metric from the state variables.

    Example subclass implementation:

    ```python
    class BinaryTruePositives(Metric):

        def __init__(self, name='binary_true_positives', **kwargs):
            super().__init__(name=name, **kwargs)
            self.true_positives = self.add_variable(
                shape=(),
                initializer='zeros',
                name='true_positives'
            )

        def update_state(self, y_true, y_pred, sample_weight=None):
            y_true = ops.cast(y_true, "bool")
            y_pred = ops.cast(y_pred, "bool")

            values = ops.logical_and(
                ops.equal(y_true, True), ops.equal(y_pred, True))
            values = ops.cast(values, self.dtype)
            if sample_weight is not None:
                sample_weight = ops.cast(sample_weight, self.dtype)
                sample_weight = ops.broadcast_to(
                    sample_weight, ops.shape(values)
                )
                values = ops.multiply(values, sample_weight)
            self.true_positives.assign(self.true_positives + ops.sum(values))

        def result(self):
            return self.true_positives
    ```
    c                 `   |xs t        | j                  j                        | _        t	        j
                  |xs t        j                               | _        | j                  j                  | _
        g | _        g | _        t        d | j                  fd | j                  fd      | _        y )Nc                 6    t        | t        j                        S N)
isinstancer   Variablexs    H/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/metrics/metric.py<lambda>z!Metric.__init__.<locals>.<lambda>e   s    jG,<,<=     c                 "    t        | t              S r   )r   r   r   s    r   r   z!Metric.__init__.<locals>.<lambda>h   s    jF&; r   )	variablesmetrics)r	   	__class____name__namer   getr   floatx_dtype_policycompute_dtype_dtype_metrics
_variablesr
   _tracker)selfdtyper   s      r   __init__zMetric.__init__\   s    >Idnn&=&=>	+//0I9IJ((66 >OO <T]]K
r   c                     | j                   D ]<  }|j                  t        j                  |j                  |j
                               > y)zReset all of the metric state variables.

        This function is called between epochs/steps,
        when a metric is evaluated during training.
        )r&   N)r   assignr   zerosshaper&   )r%   vs     r   reset_statezMetric.reset_statel   s6      	8AHHSYYqwwagg67	8r   c                     t         )z%Accumulate statistics for the metric.NotImplementedErrorr%   argskwargss      r   update_statezMetric.update_stateu   s    !!r   c           
         t        |      t        | j                        k7  rEt        d| j                  j                   dt        |       dt        | j                         d      t        t        | j                  |            }t        j                  |      5 } | j                  |i | d d d        g }| j                  D ]8  }j                  |      }||j                  |       (|j                  |       : |S # 1 sw Y   TxY wNzKArgument `metric_variables` must be a list of tensors corresponding 1:1 to z(().variables. Received list with length z, but expected z variables.)state_mapping)lenr   
ValueErrorr   r   listzipr   StatelessScoper4   get_current_valueappend)r%   metric_variablesr2   r3   mappingscoper,   new_vs           r   stateless_update_statezMetric.stateless_update_statey   s    C$77((,(?(?'@ A--01A-B,C D/0=  s4>>+;<= ##': 	/eDt.v.	/  	+A++A.E  ''. ''*	+  	/ 	/s   DDc                     t         )z|Compute the current metric value.

        Returns:
            A scalar tensor, or a dictionary of scalar tensors.
        r/   r%   s    r   resultzMetric.result   s
     "!r   c           
         t        |      t        | j                        k7  rEt        d| j                  j                   dt        |       dt        | j                         d      t        t        | j                  |            }t        j                  |      5  | j                         }d d d        |S # 1 sw Y   S xY wr6   )
r8   r   r9   r   r   r:   r;   r   r<   rF   )r%   r?   r@   ress       r   stateless_resultzMetric.stateless_result   s     C$77((,(?(?'@ A--01A-B,C D/0=  s4>>+;<= ##': 	 ++-C	 
	 
s   B77Cc                 
   t        j                         5 }| j                          d d d        g }| j                  D ]8  }j	                  |      }||j                  |       (|j                  |       : |S # 1 sw Y   TxY wr   )r   r<   r-   r   r=   r>   )r%   rA   r?   r,   rB   s        r   stateless_reset_statezMetric.stateless_reset_state   s    ##% 		  	+A++A.E  ''. ''*	+  	 	s   A99Bc                     | j                   S r   )r!   rE   s    r   r&   zMetric.dtype   s    {{r   c                      y)Nr    rE   s    r   	_obj_typezMetric._obj_type   s    r   c           
      L   | j                          t        j                  | j                  j	                  dd      |       5  t        j                  |      }t        j                  |||d|d|      }d d d        | j                  j                  d       |S # 1 sw Y   'xY w)N/>)callerFon_read)initializerr+   r&   	trainableaggregationsynchronizationr   r   )
_check_super_calledr   
name_scoper   replacer   r   r   r$   add_to_store)r%   r+   rU   r&   rW   r   variables          r   add_variablezMetric.add_variable   s     	  "		 1 1#s ;DI 
	&**;7K'''' )H
	 	"";9
	 
	s   2BB#c                 ,    | j                  ||||      S )N)r+   rU   r&   r   )r^   )r%   r+   rU   r&   r   s        r   
add_weightzMetric.add_weight   s#      [D ! 
 	
r   c                     t        | j                        }| j                  D ]  }|j                  |j                          |S r   )r:   r#   r"   extendr   )r%   r   metrics      r   r   zMetric.variables   s=    )	mm 	/FV--.	/r   c                 f    | j                           | j                  |i | | j                         S r   )rY   r4   rF   r1   s      r   __call__zMetric.__call__   s/      "4*6*{{}r   c                 4    | j                   | j                  dS )z-Return the serializable config of the metric.r   r&   rg   rE   s    r   
get_configzMetric.get_config   s    		DJJ77r   c                      | di |S )NrN   rN   )clsconfigs     r   from_configzMetric.from_config   s    }V}r   c                 r    t        | d      r| j                  j                  |      }t        |   ||      S )Nr$   )hasattrr$   tracksuper__setattr__)r%   r   valuer   s      r   rq   zMetric.__setattr__   s3    4$MM''.Ew"4//r   c                 2    t        | d      st        d      y )Nr$   zNYou forgot to call `super().__init__()` in the `__init__()` method. Go add it!)rn   RuntimeErrorrE   s    r   rY   zMetric._check_super_called   s#    tZ(9  )r   c                 P    d| j                   j                   d| j                   dS )N<z name=rR   )r   r   r   rE   s    r   __repr__zMetric.__repr__   s&    4>>**+6$))A>>r   c                 "    | j                         S r   )rw   rE   s    r   __str__zMetric.__str__   s    }}r   )NN)NsumN)rN   NNN)r   
__module____qualname____doc__r'   r-   r4   rC   rF   rI   rK   propertyr&   rO   r^   r`   r   re   rh   classmethodrl   rq   rY   rw   ry   __classcell__)r   s   @r   r   r      s    M^
 8" 2"     GK&
  
8  0?r   r   N)	keras.srcr   r   r   r   keras.src.api_exportr   keras.src.saving.keras_saveabler   keras.src.utils.namingr	   keras.src.utils.trackingr
   r   rN   r   r   <module>r      sF     $ "  - 9 , , ~567r] r 8rr   