
    &VfjM                        d dl 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 d d
lmZ d dlmZ d dlmZ  ed           G d dej                              Z ed           G d dej                              Z ed           G d dej                              Z ed           G d dej                              Z ed           G d dej                              Z ed           G d dej                              Z ed           G d  d!ej                              Z ed"           G d# d$ej                              Zd'd&ZdS )(    N)initializers)ops)keras_export)squeeze_or_expand_to_same_rank)log_cosh)mean_absolute_error)mean_absolute_percentage_error)mean_squared_error)mean_squared_logarithmic_error)reduction_metrics)	normalizezkeras.metrics.MeanSquaredErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanSquaredErrora  Computes the mean squared error between `y_true` and `y_pred`.

    Formula:

    ```python
    loss = mean(square(y_true - y_pred))
    ```

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

    Example:

    >>> m = keras.metrics.MeanSquaredError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    0.25
    r
   Nc                 h    t                                          t          ||           d| _        d S )N)fnnamedtypedown)super__init__r
   
_directionselfr   r   	__class__s      a/var/www/html/software/conda/lib/python3.11/site-packages/keras/src/metrics/regression_metrics.pyr   zMeanSquaredError.__init__&   s.    .TGGG     c                      | j         | j        dS Nr   r   r   r   s    r   
get_configzMeanSquaredError.get_config+       	DJ777r   )r
   N__name__
__module____qualname____doc__r   r!   __classcell__r   s   @r   r   r      sV         (! ! ! ! ! !
8 8 8 8 8 8 8r   r   zkeras.metrics.MeanAbsoluteErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanAbsoluteErrora  Computes the mean absolute error between the labels and predictions.

    Formula:

    ```python
    loss = mean(abs(y_true - y_pred))
    ```

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

    Examples:

    >>> m = keras.metrics.MeanAbsoluteError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    0.25
    >>> m.reset_state()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
    ...                sample_weight=[1, 0])
    >>> m.result()
    0.5

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='mse',
        metrics=[keras.metrics.MeanAbsoluteError()])
    ```
    r   Nc                 h    t                                          t          ||           d| _        d S Nr   r   )r   r   r   r   r   s      r   r   zMeanAbsoluteError.__init__S   s.    ,d%@@@ r   c                      | j         | j        dS r   r   r    s    r   r!   zMeanAbsoluteError.get_configX   r"   r   )r   Nr#   r)   s   @r   r+   r+   /   sW           D! ! ! ! ! !
8 8 8 8 8 8 8r   r+   z)keras.metrics.MeanAbsolutePercentageErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanAbsolutePercentageErrora6  Computes mean absolute percentage error between `y_true` and `y_pred`.

    Formula:

    ```python
    loss = 100 * mean(abs((y_true - y_pred) / y_true))
    ```

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

    Example:

    Example:

    >>> m = keras.metrics.MeanAbsolutePercentageError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    250000000.0
    >>> m.reset_state()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
    ...                sample_weight=[1, 0])
    >>> m.result()
    500000000.0

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='mse',
        metrics=[keras.metrics.MeanAbsolutePercentageError()])
    ```
    r	   Nc                 h    t                                          t          ||           d| _        d S r-   )r   r   r	   r   r   s      r   r   z$MeanAbsolutePercentageError.__init__   .    7UKKK r   c                      | j         | j        dS r   r   r    s    r   r!   z&MeanAbsolutePercentageError.get_config   r"   r   )r	   Nr#   r)   s   @r   r1   r1   \   W        " "H! ! ! ! ! !
8 8 8 8 8 8 8r   r1   z)keras.metrics.MeanSquaredLogarithmicErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanSquaredLogarithmicErrora8  Computes mean squared logarithmic error between `y_true` and `y_pred`.

    Formula:

    ```python
    loss = mean(square(log(y_true + 1) - log(y_pred + 1)))
    ```

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

    Example:

    Example:

    >>> m = keras.metrics.MeanSquaredLogarithmicError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    0.12011322
    >>> m.reset_state()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
    ...                sample_weight=[1, 0])
    >>> m.result()
    0.24022643

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='mse',
        metrics=[keras.metrics.MeanSquaredLogarithmicError()])
    ```
    r   Nc                 h    t                                          t          ||           d| _        d S r-   )r   r   r   r   r   s      r   r   z$MeanSquaredLogarithmicError.__init__   r3   r   c                      | j         | j        dS r   r   r    s    r   r!   z&MeanSquaredLogarithmicError.get_config   r"   r   )r   Nr#   r)   s   @r   r7   r7      r5   r   r7   z"keras.metrics.RootMeanSquaredErrorc                   :     e Zd ZdZd fd	Zd fd	Z fdZ xZS )	RootMeanSquaredErrora  Computes root mean squared error metric between `y_true` and `y_pred`.

    Formula:

    ```python
    loss = sqrt(mean((y_pred - y_true) ** 2))
    ```

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

    Example:

    Example:

    >>> m = keras.metrics.RootMeanSquaredError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    0.5

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

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='mse',
        metrics=[keras.metrics.RootMeanSquaredError()])
    ```
    root_mean_squared_errorNc                 \    t                                          ||           d| _        d S r-   )r   r   r   r   s      r   r   zRootMeanSquaredError.__init__   s+    U+++ r   c                    t          j        || j                  }t          j        || j                  }t          ||          \  }}t          j        ||z
            }t                                          ||          S )  Accumulates root mean squared error 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.
        )sample_weight)r   convert_to_tensor_dtyper   squarer   update_state)r   y_truey_predr@   error_sqr   s        r   rD   z!RootMeanSquaredError.update_state   sp     &vt{;;&vt{;;7GG:fvo..ww##HM#JJJr   c                 h    t          j        t                                                                S N)r   sqrtr   result)r   r   s    r   rK   zRootMeanSquaredError.result   s!    x(()))r   )r<   NrI   )r$   r%   r&   r'   r   rD   rK   r(   r)   s   @r   r;   r;      s        # #J! ! ! ! ! !
K K K K K K(* * * * * * * * *r   r;   zkeras.metrics.CosineSimilarityc                   *     e Zd ZdZd fd	Zd Z xZS )CosineSimilaritya  Computes the cosine similarity between the labels and predictions.

    Formula:

    ```python
    loss = sum(l2_norm(y_true) * l2_norm(y_pred))
    ```
    See: [Cosine Similarity](https://en.wikipedia.org/wiki/Cosine_similarity).
    This metric keeps the average cosine similarity between `predictions` and
    `labels` over a stream of data.

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.
        axis: (Optional) Defaults to `-1`. The dimension along which the cosine
            similarity is computed.

    Example:

    Example:

    >>> # l2_norm(y_true) = [[0., 1.], [1./1.414, 1./1.414]]
    >>> # l2_norm(y_pred) = [[1., 0.], [1./1.414, 1./1.414]]
    >>> # l2_norm(y_true) . l2_norm(y_pred) = [[0., 0.], [0.5, 0.5]]
    >>> # result = mean(sum(l2_norm(y_true) . l2_norm(y_pred), axis=1))
    >>> #        = ((0. + 0.) +  (0.5 + 0.5)) / 2
    >>> m = keras.metrics.CosineSimilarity(axis=1)
    >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]])
    >>> m.result()
    0.49999997
    >>> m.reset_state()
    >>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]],
    ...                sample_weight=[0.3, 0.7])
    >>> m.result()
    0.6999999

    Usage with `compile()` API:

    ```python
    model.compile(
        optimizer='sgd',
        loss='mse',
        metrics=[keras.metrics.CosineSimilarity(axis=1)])
    ```
    cosine_similarityNc                 j    t                                          t          |||           d| _        d S )N)r   axisup)r   r   rN   r   )r   r   r   rQ   r   s       r   r   zCosineSimilarity.__init__.  s0    *DDIIIr   c                      | j         | j        dS r   r   r    s    r   r!   zCosineSimilarity.get_config3  r"   r   )rN   NrO   r#   r)   s   @r   rM   rM      sW        , ,\     
8 8 8 8 8 8 8r   rM   zkeras.metrics.LogCoshErrorc                   *     e Zd ZdZd fd	Zd Z xZS )LogCoshErroraG  Computes the logarithm of the hyperbolic cosine of the prediction error.

    Formula:

    ```python
    error = y_pred - y_true
    logcosh = mean(log((exp(error) + exp(-error))/2), axis=-1)
    ```

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

    Example:

    Example:

    >>> m = keras.metrics.LogCoshError()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
    >>> m.result()
    0.10844523
    >>> m.reset_state()
    >>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
    ...                sample_weight=[1, 0])
    >>> m.result()
    0.21689045

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='mse',
                  metrics=[keras.metrics.LogCoshError()])
    ```
    logcoshNc                 h    t                                          t          ||           d| _        d S r-   )r   r   r   r   r   s      r   r   zLogCoshError.__init__]  s-    4u555 r   c                      | j         | j        dS r   r   r    s    r   r!   zLogCoshError.get_configb  r"   r   )rV   Nr#   r)   s   @r   rU   rU   7  r5   r   rU   zkeras.metrics.R2Scorec                   P     e Zd ZdZ	 	 	 	 d fd	Zd ZddZd	 Zd
 Z fdZ	 xZ
S )R2Scorea  Computes R2 score.

    Formula:

    ```python
    sum_squares_residuals = sum((y_true - y_pred) ** 2)
    sum_squares = sum((y_true - mean(y_true)) ** 2)
    R2 = 1 - sum_squares_residuals / sum_squares
    ```

    This is also called the
    [coefficient of determination](
    https://en.wikipedia.org/wiki/Coefficient_of_determination).

    It indicates how close the fitted regression line
    is to ground-truth data.

    - The highest score possible is 1.0. It indicates that the predictors
        perfectly accounts for variation in the target.
    - A score of 0.0 indicates that the predictors do not
        account for variation in the target.
    - It can also be negative if the model is worse than random.

    This metric can also compute the "Adjusted R2" score.

    Args:
        class_aggregation: Specifies how to aggregate scores corresponding to
            different output classes (or target dimensions),
            i.e. different dimensions on the last axis of the predictions.
            Equivalent to `multioutput` argument in Scikit-Learn.
            Should be one of
            `None` (no aggregation), `"uniform_average"`,
            `"variance_weighted_average"`.
        num_regressors: Number of independent regressors used
            ("Adjusted R2" score). 0 is the standard R2 score.
            Defaults to `0`.
        name: Optional. string name of the metric instance.
        dtype: Optional. data type of the metric result.

    Example:

    >>> y_true = np.array([[1], [4], [3]], dtype=np.float32)
    >>> y_pred = np.array([[2], [4], [4]], dtype=np.float32)
    >>> metric = keras.metrics.R2Score()
    >>> metric.update_state(y_true, y_pred)
    >>> result = metric.result()
    >>> result
    0.57142854
    uniform_averager   r2_scoreNc                 H   t                                          ||           d| _        d}||vrt          d| d|           |dk     rt          d|           || _        || _        |                     dt          j                    d	
          | _	        d| _
        d S )Nr   rR   )Nr[   variance_weighted_averagez@Invalid value for argument `class_aggregation`. Expected one of z. Received: class_aggregation=r   z]Invalid value for argument `num_regressors`. Expected a value >= 0. Received: num_regressors= num_samples)shapeinitializerr   F)r   r   r   
ValueErrorclass_aggregationnum_regressorsadd_variabler   Zerosr`   _built)r   rd   re   r   r   valid_class_aggregation_valuesr   s         r   r   zR2Score.__init__  s     	d%000*
&
 $BBBC8C C/@C C  
 A=,:= =  
 "3,,,$*,, - 
 

 r   c                 `   t          |          dk    st          |          dk    rt          d| d| d          |d         |d         t          d| d| d          |d         }|                     d|gt          j                              | _        |                     d	|gt          j                              | _        |                     d
|gt          j                              | _        |                     d|gt          j                              | _        d| _	        d S )N   zcR2Score expects 2D inputs with shape (batch_size, output_dim). Received input shapes: y_pred.shape=z and y_true.shape=.rO   zR2Score expects 2D inputs with shape (batch_size, output_dim), with output_dim fully defined (not None). Received input shapes: y_pred.shape=squared_sum)r   ra   rb   sumresidualcountT)
lenrc   rf   r   rg   rm   rn   	total_mserp   rh   )r   y_true_shapey_pred_shapenum_classess       r   _buildzR2Score._build  s   |!!S%6%6!%;%;0(40 0 !-0 0 0   #|B'7'?0 )50 0 !-	0 0 0   #2&,,-$*,, - 
 

 $$-$*,, % 
 

 **-$*,, + 
 

 &&-$*,, ' 
 


 r   c           
      h   t          j        || j                  }t          j        || j                  }t          ||          \  }}| j        s |                     |j        |j                   |d}t          j        || j                  }t          |j                  dk    rt          j	        |d          }t          j
        |t          j        |                    }|t          j        ||j                  z  }| j                            | j        t          j        |d          z              | j                            | j        t          j        ||z  d          z              | j                            | j        t          j        ||z
  dz  t          j        ||j                  z  d          z              | j                            | j        t          j        |d          z              | j                            | j        t          j        |          z              dS )r?   r.   N   rQ   r   rk   )r   rA   rB   r   rh   rv   ra   r   rq   expand_dimsbroadcast_tocastrn   assignrm   rr   rp   r`   size)r   rE   rF   r@   weighted_y_trues        r   rD   zR2Score.update_state  s    &vT[AAA&vT[AAA7GG{ 	4KKfl333 M-m4:NNN}"##q((OMBBBM(	&8I8IJJ 38M6<#H#HH37?#C#C#CCDDDswv'?aHHHH	
 	
 	
 	Ng&Q&-)N)NN  	
 	
 	
 	
$*sw}1'E'E'EEFFF 038F3C3C CDDDDDr   c                    | j         | j        z  }| j        | j         |z  z
  }d| j        |z  z
  }t	          j        t	          j        |          d|          }| j        dk    rt	          j        |          }n>| j        dk    r1t	          j         ||z            }t	          j         |          }||z  }n|}| j	        dk    r| j	        | j
        dz
  k    rt          j        dd           n| j	        | j
        dz
  k    rt          j        d	d           nt	          j        | j
        d
          }t	          j        | j	        d
          }t	          j        t	          j        d|          t	          j        |d                    }	t	          j        t	          j        ||          d          }
t	          j        dt	          j        |	|
                    }|S )Nrx   g        r[   r^   r   zdMore independent predictors than datapoints in adjusted R2 score. Falling back to standard R2 score.rk   )
stacklevelzIDivision by zero in Adjusted R2 score. Falling back to standard R2 score.float32r.   g      ?)rn   rp   rm   rr   r   whereisinfrd   meanre   r`   warningswarnrA   multiplysubtractdivide)r   r   total
raw_scoresr\   weighted_sumsum_of_weightsnpnumdens              r   rK   zR2Score.result  s   x$*$ 48d?2$.501
Ysy44c:FF
!%666x
++HH#'BBB75:#566L WU^^N#n4HH!H!##"T%5%999O     
 $(81(<<<9      )$*:)LLL)$*=YOOOlLh//a1E1E  l3<1#5#5s;;<SZS-A-ABBr   c                     | j         D ]5}|                    t          j        |j        |j                             6d S )Nr.   )	variablesr}   r   zerosra   r   )r   vs     r   reset_statezR2Score.reset_state;  sE     	8 	8AHHSYqwag6667777	8 	8r   c                     | j         | j        | j        | j        d}t	                                                      }i ||S )N)r   r   rd   re   )r   r   rd   re   r   r!   )r   configbase_configr   s      r   r!   zR2Score.get_config?  sL    IZ!%!7"1	
 
 gg((**(+(((r   )r[   r   r\   NrI   )r$   r%   r&   r'   r   rv   rD   rK   r   r!   r(   r)   s   @r   rZ   rZ   g  s        0 0h ,# # # # # #J% % %N,E ,E ,E ,E\$ $ $L8 8 8) ) ) ) ) ) ) ) )r   rZ   rO   c                     t          j        |          }t          j        | |j                  } t          | |          \  } }t	          ||          }t	          | |          } t          j        | |z  |          S )aN  Computes the cosine similarity between labels and predictions.

    Formula:

    ```python
    loss = sum(l2_norm(y_true) * l2_norm(y_pred))
    ```

    Args:
        y_true: Tensor of true targets.
        y_pred: Tensor of predicted targets.
        axis: Axis along which to determine similarity. Defaults to `-1`.

    Returns:
        Cosine similarity tensor.

    Example:

    >>> y_true = [[0., 1.], [1., 1.], [1., 1.]]
    >>> y_pred = [[1., 0.], [1., 1.], [-1., -1.]]
    >>> loss = keras.losses.cosine_similarity(y_true, y_pred, axis=-1)
    [0., 0.99999994, -0.99999994]
    r.   ry   )r   rA   r   r   r   rn   )rE   rF   rQ   s      r   rN   rN   J  s{    0 "6**F"6>>>F3FFCCNFFvD)))FvD)))F76F?....r   )rO   )r   	keras.srcr   r   keras.src.api_exportr   keras.src.losses.lossr   keras.src.losses.lossesr   r   r	   r
   r   keras.src.metricsr   keras.src.utils.numerical_utilsr   MeanMetricWrapperr   r+   r1   r7   Meanr;   rM   rU   MetricrZ   rN   r_   r   r   <module>r      s9    " " " " " "       - - - - - - @ @ @ @ @ @ , , , , , , 7 7 7 7 7 7 B B B B B B 6 6 6 6 6 6 B B B B B B / / / / / / 5 5 5 5 5 5 .//8 8 8 8 8(: 8 8 0/8< /00)8 )8 )8 )8 )8); )8 )8 10)8X 9::+8 +8 +8 +8 +8"3"E +8 +8 ;:+8\ 9::+8 +8 +8 +8 +8"3"E +8 +8 ;:+8\ 233@* @* @* @* @*,1 @* @* 43@*F .//58 58 58 58 58(: 58 58 0/58p *+++8 +8 +8 +8 +8$6 +8 +8 ,++8^ %&&_) _) _) _) _)& _) _) '&_)D/ / / / / /r   