
    &Vfu                          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dS )    )backend)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) string name of the metric instance.
        dtype: (Optional) data type of the metric result.

    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
    ```
    Nc                     |pt          | j        j                  | _        |pt	          j                    | _        g | _        g | _        t          d | j        fd | j        fd          | _
        d S )Nc                 6    t          | t          j                  S N)
isinstancer   Variablexs    U/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/metrics/metric.py<lambda>z!Metric.__init__.<locals>.<lambda>_   s    jG,<==     c                 ,    t          | t                    S r   )r   r   r   s    r   r   z!Metric.__init__.<locals>.<lambda>b   s    jF&;&; r   )	variablesmetrics)r   	__class____name__namer   floatx_dtype_metrics
_variablesr	   _tracker)selfdtyper   s      r   __init__zMetric.__init__W   s}    >Idn&=>>	/w~// >=O <;T]K 
 
r   c                     | j         D ]5}|                    t          j        |j        |j                             6dS )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_statef   sG      	8 	8AHHSYqwag6667777	8 	8r   c                     t           )z%Accumulate statistics for the metric.NotImplementedErrorr!   argskwargss      r   update_statezMetric.update_stateo   s    !!r   c           
      (   t          |          t          | j                  k    rBt          d| j        j         dt          |           dt          | j                   d          t          t          | j        |                    }t          j        |          5 } | j	        |i | d d d            n# 1 swxY w Y   g }| j        D ]D}|
                    |          }||                    |           /|                    |           E|S 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   StatelessScoper0   get_current_valueappend)r!   metric_variablesr.   r/   mappingscoper(   new_vs           r   stateless_update_statezMetric.stateless_update_states   s     C$7$777=(,(?= =-01A-B-B= =  //= = =   s4>+;<<== #'::: 	/eDt.v...	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/ 	/  	+ 	+A++A..E  ''.... ''****s   B99B= B=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                  k    rBt          d| j        j         dt          |           dt          | j                   d          t          t          | j        |                    }t          j        |          5  | 	                                }d d d            n# 1 swxY w Y   |S r2   )
r4   r   r5   r   r   r6   r7   r   r8   rB   )r!   r;   r<   ress       r   stateless_resultzMetric.stateless_result   s     C$7$777=(,(?= =-01A-B-B= =  //= = =   s4>+;<<== #'::: 	  	 ++--C	  	  	  	  	  	  	  	  	  	  	  	  	  	  	 
s   C  CCc                     t          j                    5 }|                                  d d d            n# 1 swxY w Y   g }| j        D ]D}|                    |          }||                    |           /|                    |           E|S r   )r   r8   r)   r   r9   r:   )r!   r=   r;   r(   r>   s        r   stateless_reset_statezMetric.stateless_reset_state   s    #%% 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	  	+ 	+A++A..E  ''.... ''****s   599c                     | j         S r   )r   rA   s    r   r"   zMetric.dtype   s
    {r   c                     dS )Nr    rA   s    r   	_obj_typezMetric._obj_type   s    xr   sumc           	      N   |                                   t          j        | j                            dd          |           5  t          j        |          }t          j        |||d||          }d d d            n# 1 swxY w Y   | j        	                    d|           |S )N/>)callerF)initializerr'   r"   	trainableaggregationr   r   )
_check_super_calledr   
name_scoper   replacer   getr   r    add_to_store)r!   r'   rQ   r"   rS   r   variables          r   add_variablezMetric.add_variable   s     	  """	 1 1#s ; ;DIII 		 		&*;77K'''  H		 		 		 		 		 		 		 		 		 		 		 		 		 		 		 	"";999s   /A??BBrJ   c                 4    |                      ||||          S )N)r'   rQ   r"   r   )rZ   )r!   r'   rQ   r"   r   s        r   
add_weightzMetric.add_weight   s(      [D ! 
 
 	
r   c                 l    | j         d d          }| j        D ]}|                    |j                    |S r   )r   r   extend)r!   r   metrics      r   r   zMetric.variables   sC    OAAA&	m 	0 	0FV.////r   c                 l    |                                    | j        |i | |                                 S r   )rT   r0   rB   r-   s      r   __call__zMetric.__call__   s:      """4*6***{{}}r   c                      | j         | j        dS )z-Return the serializable config of the metric.r   r"   rc   rA   s    r   
get_configzMetric.get_config   s    	DJ777r   c                      | di |S )NrJ   rJ   )clsconfigs     r   from_configzMetric.from_config   s    s}}V}}r   c                     t          | d          r| j                            |          }t                                          ||          S )Nr    )hasattrr    tracksuper__setattr__)r!   r   valuer   s      r   rm   zMetric.__setattr__   sD    4$$ 	/M''..Eww""4///r   c                 D    t          | d          st          d          d S )Nr    zNYou forgot to call `super().__init__()` in the `__init__()` method. Go add it!)rj   RuntimeErrorrA   s    r   rT   zMetric._check_super_called   s5    tZ(( 	9  	 	r   c                 2    d| j         j         d| j         dS )N<z name=rO   )r   r   r   rA   s    r   __repr__zMetric.__repr__   s"    B4>*BBdiBBBBr   c                 *    |                                  S r   )rs   rA   s    r   __str__zMetric.__str__   s    }}r   )NN)NrL   N)rJ   NNN)r   
__module____qualname____doc__r#   r)   r0   r?   rB   rE   rG   propertyr"   rK   rZ   r\   r   ra   rd   classmethodrh   rm   rT   rs   ru   __classcell__)r   s   @r   r   r   
   s       I IV
 
 
 
8 8 8" " "     2" " "           X   GK   $
 
 
 
   X  
8 8 8   [0 0 0 0 0  C C C      r   r   N)	keras.srcr   r   r   keras.src.api_exportr   keras.src.saving.keras_saveabler   keras.src.utils.namingr   keras.src.utils.trackingr	   r   rJ   r   r   <module>r      s          " " " " " "       - - - - - - 9 9 9 9 9 9 , , , , , , , , , , , , ~5677l l l l l] l l 87l l lr   