o
    2h7"                     @   s   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 deZdS )    )backend)dtype_policies)initializers)ops)keras_export)KerasSaveable)	auto_name)Trackerzkeras.Metriczkeras.metrics.Metricc                       s   e Zd ZdZd+ddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
edd Zdd Z	d,ddZd-ddZedd Zdd Zdd  Zed!d" Z fd#d$Zd%d& Zd'd( Zd)d* Z  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
    ```
    Nc                 C   sd   |pt | jj| _t|pt | _| jj	| _
g | _g | _tdd | jfdd | jfd| _d S )Nc                 S   s   t | tjS N)
isinstancer   Variablex r   S/var/www/html/chatgem/venv/lib/python3.10/site-packages/keras/src/metrics/metric.py<lambda>e   s    z!Metric.__init__.<locals>.<lambda>c                 S   s
   t | tS r   )r   r
   r   r   r   r   r   h   s   
 )	variablesmetrics)r   	__class____name__namer   getr   floatx_dtype_policycompute_dtype_dtype_metrics
_variablesr	   _tracker)selfdtyper   r   r   r   __init__\   s   

zMetric.__init__c                 C   s(   | j D ]}|tj|j|jd qd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    vr   r   r   reset_statel   s   
zMetric.reset_statec                 O      t )z%Accumulate statistics for the metric.NotImplementedErrorr    argskwargsr   r   r   update_stateu   s   zMetric.update_statec                 O   s   t |t | jkrtd| jj dt | dt | j dtt| j|}tj|d}| j	|i | W d    n1 s?w   Y  g }| jD ]}|
|}|d urZ|| qI|| qI|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   StatelessScoper.   get_current_valueappend)r    metric_variablesr,   r-   mappingscoper&   new_vr   r   r   stateless_update_statey   s*   

zMetric.stateless_update_statec                 C   r(   )z|Compute the current metric value.

        Returns:
            A scalar tensor, or a dictionary of scalar tensors.
        r)   r    r   r   r   result   s   zMetric.resultc                 C   s   t |t | jkrtd| jj dt | dt | j dtt| j|}tj|d | 	 }W d    |S 1 s<w   Y  |S r/   )
r1   r   r2   r   r   r3   r4   r   r5   r>   )r    r8   r9   resr   r   r   stateless_result   s"   

zMetric.stateless_resultc                 C   sl   t  }|   W d    n1 sw   Y  g }| jD ]}||}|d ur.|| q|| q|S r   )r   r5   r'   r   r6   r7   )r    r:   r8   r&   r;   r   r   r   stateless_reset_state   s   



zMetric.stateless_reset_statec                 C   s   | j S r   )r   r=   r   r   r   r!      s   zMetric.dtypec                 C   s   dS )Nr
   r   r=   r   r   r   	_obj_type   s   zMetric._obj_typesumc              
   C   st   |    tj| jdd| d t|}tj|||d|d|d}W d    n1 s,w   Y  | j	d| |S )N/>)callerFon_read)initializerr%   r!   	trainableaggregationsynchronizationr   r   )
_check_super_calledr   
name_scoper   replacer   r   r   r   add_to_store)r    r%   rH   r!   rJ   r   variabler   r   r   add_variable   s   
zMetric.add_variabler   c                 C   s   | j ||||dS )N)r%   rH   r!   r   )rQ   )r    r%   rH   r!   r   r   r   r   
add_weight   s   zMetric.add_weightc                 C   s&   t | j}| jD ]}||j q|S r   )r3   r   r   extendr   )r    r   metricr   r   r   r      s   

zMetric.variablesc                 O   s    |    | j|i | |  S r   )rL   r.   r>   r+   r   r   r   __call__   s   zMetric.__call__c                 C   s   | j | jdS )z-Return the serializable config of the metric.r   r!   rV   r=   r   r   r   
get_config      zMetric.get_configc                 C   s   | di |S )Nr   r   )clsconfigr   r   r   from_config   rX   zMetric.from_configc                    s$   t | dr| j|}t ||S )Nr   )hasattrr   tracksuper__setattr__)r    r   valuer   r   r   r_      s   
zMetric.__setattr__c                 C   s   t | ds	tdd S )Nr   zNYou forgot to call `super().__init__()` in the `__init__()` method. Go add it!)r\   RuntimeErrorr=   r   r   r   rL      s
   
zMetric._check_super_calledc                 C   s   d| j j d| j dS )N<z name=rE   )r   r   r   r=   r   r   r   __repr__   s   zMetric.__repr__c                 C   s   |   S r   )rd   r=   r   r   r   __str__   s   zMetric.__str__)NN)NrC   N)r   NNN)r   
__module____qualname____doc__r"   r'   r.   r<   r>   r@   rA   propertyr!   rB   rQ   rR   r   rU   rW   classmethodr[   r_   rL   rd   re   __classcell__r   r   ra   r   r
      s2    
O	




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
   r   r   r   r   <module>   s    
