
    2Vh,M                        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j6                               Zd&d%Zy)'    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
    c                 @    t         |   t        ||       d| _        y )N)fnnamedtypedown)super__init__r
   
_directionselfr   r   	__class__s      T/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/metrics/regression_metrics.pyr   zMeanSquaredError.__init__%   s    .TG     c                 4    | j                   | j                  dS Nr   r   r   r   s    r   
get_configzMeanSquaredError.get_config*       		DJJ77r   )r
   N__name__
__module____qualname____doc__r   r!   __classcell__r   s   @r   r   r      s    &!
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()])
    ```
    c                 @    t         |   t        ||       d| _        y Nr   r   )r   r   r   r   r   s      r   r   zMeanAbsoluteError.__init__S   s    ,d%@ r   c                 4    | j                   | j                  dS r   r   r    s    r   r!   zMeanAbsoluteError.get_configX   r"   r   )r   Nr#   r)   s   @r   r+   r+   .       !F!
8r   r+   z)keras.metrics.MeanAbsolutePercentageErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanAbsolutePercentageErrora)  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.

    Examples:
    >>> 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()])
    ```
    c                 @    t         |   t        ||       d| _        y r-   )r   r   r	   r   r   s      r   r   z$MeanAbsolutePercentageError.__init__       7UK r   c                 4    | j                   | j                  dS r   r   r    s    r   r!   z&MeanAbsolutePercentageError.get_config   r"   r   )r	   Nr#   r)   s   @r   r2   r2   \   s     D!
8r   r2   z)keras.metrics.MeanSquaredLogarithmicErrorc                   *     e Zd ZdZd fd	Zd Z xZS )MeanSquaredLogarithmicErrora,  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.

    Examples:

    >>> 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()])
    ```
    c                 @    t         |   t        ||       d| _        y r-   )r   r   r   r   r   s      r   r   z$MeanSquaredLogarithmicError.__init__   r4   r   c                 4    | j                   | j                  dS r   r   r    s    r   r!   z&MeanSquaredLogarithmicError.get_config   r"   r   )r   Nr#   r)   s   @r   r7   r7      r0   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.

    Examples:

    >>> 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()])
    ```
    c                 6    t         |   ||       d| _        y 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   rC   z!RootMeanSquaredError.update_state   sh     &&vt{{;&&vt{{;7G::fvo.w#HM#JJr   c                 F    t        j                  t        |                S N)r   sqrtr   result)r   r   s    r   rJ   zRootMeanSquaredError.result   s    xx())r   )root_mean_squared_errorNrH   )r$   r%   r&   r'   r   rC   rJ   r(   r)   s   @r   r;   r;      s    !F!
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.

    Examples:

    >>> # 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)])
    ```
    c                 B    t         |   t        |||       d| _        y )N)r   axisup)r   r   cosine_similarityr   )r   r   r   rO   r   s       r   r   zCosineSimilarity.__init__(  s!    *DDIr   c                 4    | j                   | j                  dS r   r   r    s    r   r!   zCosineSimilarity.get_config-  r"   r   )rQ   Nr#   r)   s   @r   rM   rM      s    +Z
8r   rM   zkeras.metrics.LogCoshErrorc                   *     e Zd ZdZd fd	Zd Z xZS )LogCoshErrora;  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.

    Examples:

    >>> 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()])
    ```
    c                 @    t         |   t        ||       d| _        y r-   )r   r   r   r   r   s      r   r   zLogCoshError.__init__V  s    4u5 r   c                 4    | j                   | j                  dS r   r   r    s    r   r!   zLogCoshError.get_config[  r"   r   )logcoshNr#   r)   s   @r   rU   rU   1  r0   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
    c                 
   t         |   ||       d| _        d}||vrt        d| d|       |dk  rt        d|       || _        || _        | j                  dt        j                         d	
      | _	        d| _
        y )Nr   rP   )Nuniform_average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   rc   rd   r   r   valid_class_aggregation_valuesr   s         r   r   zR2Score.__init__  s     	d%0*
&
 $BB89 ://@.AC 
 A,,:+;= 
 "3,,,$**, - 

 r   c                    t        |      dk7  st        |      dk7  rt        d| d| d      |d   |d   t        d| d| d      |d   }| j                  d|gt        j                               | _        | j                  d	|gt        j                               | _        | j                  d
|gt        j                               | _        | j                  d|gt        j                               | _        d| _	        y )N   zcR2Score expects 2D inputs with shape (batch_size, output_dim). Received input shapes: y_pred.shape=z and y_true.shape=.rS   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   r`   ra   sumresidualcountT)
lenrb   re   r   rf   rl   rm   	total_msero   rg   )r   y_true_shapey_pred_shapenum_classess       r   _buildzR2Score._build  sL   |!S%6!%;((4~ 6  ,~Q0  #|B'7'?( )5~ 6  ,~Q	0  #2&,,-$**, - 

 $$-$**, % 

 **-$**, + 

 &&-$**, ' 


 r   c           
         t        j                  || j                        }t        j                  || j                        }t        ||      \  }}| j                  s&| j                  |j                  |j                         |d}t        j                  || j                        }t        |j                        dk(  rt        j                  |d      }t        j                  |t        j                  |            }|t        j                  ||j                        z  }| j                  j                  | j                  t        j                  |d      z          | j                  j                  | j                  t        j                  ||z  d      z          | j                  j                  | j                  t        j                  ||z
  dz  t        j                  ||j                        z  d      z          | j                   j                  | j                   t        j                  |d      z          | j"                  j                  | j"                  t        j$                  |      z          y)r>   r.   N   rO   r   rj   )r   r@   rA   r   rg   ru   r`   r   rp   expand_dimsbroadcast_tocastrm   assignrl   rq   ro   r_   size)r   rD   rE   r?   weighted_y_trues        r   rC   zR2Score.update_state  s    &&vT[[A&&vT[[A7G{{KKfll3 M--m4::N}""#q(OOMBM((		&8IJ 388M6<<#HH377?#CCDswwv'?aHH	
 	NNgg&Q&-)NN	
 	

$**sww}1'EEF 0 0388F3C CDr   c                 V   | j                   | j                  z  }| j                  | j                   |z  z
  }d| j                  |z  z
  }t	        j
                  t	        j                  |      d|      }| j                  dk(  rt	        j                  |      }nD| j                  dk(  r3t	        j                   ||z        }t	        j                   |      }||z  }n|}| j                  dk7  r>| j                  | j                  dz
  kD  rt        j                  dd       |S | j                  | j                  dz
  k(  rt        j                  d	d       |S t	        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 )Nrw   g        r\   r]   r   zdMore independent predictors than datapoints in adjusted R2 score. Falling back to standard R2 score.rj   )
stacklevelzIDivision by zero in Adjusted R2 score. Falling back to standard R2 score.float32r.   g      ?)rm   ro   rl   rq   r   whereisinfrc   meanrd   r_   warningswarnr@   multiplysubtractdivide)r   r   total
raw_scoresr2_scoreweighted_sumsum_of_weightsnpnumdens              r   rJ   zR2Score.result  s   xx$**$  488d?2$..501
YYsyy4c:F
!!%66xx
+H##'BB775:#56L WWU^N#n4H!H!#""T%5%5%99O &  $$(8(81(<<9   ))$*:*:)L))$*=*=YOllLLh/a1E ll3<<1#5s;<<SZZS-ABr   c                     | j                   D ]<  }|j                  t        j                  |j                  |j
                               > y )Nr.   )	variablesr|   r   zerosr`   r   )r   vs     r   reset_statezR2Score.reset_state4  s4     	8AHHSYYqwwagg67	8r   c                     | j                   | j                  | j                  | j                  d}t        |          }i ||S )N)r   r   rc   rd   )r   r   rc   rd   r   r!   )r   configbase_configr   s      r   r!   zR2Score.get_config8  sI    IIZZ!%!7!7"11	
 g(*(+(((r   )r\   r   r   NrH   )r$   r%   r&   r'   r   ru   rC   rJ   r   r!   r(   r)   s   @r   rZ   rZ   `  s?    0h ,#J%N,E\$L8) )r   rZ   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.   rx   )r   r@   r   r   r   rm   )rD   rE   rO   s      r   rQ   rQ   C  sg    0 ""6*F""6>F3FFCNFFvD)FvD)F776F?..r   )rS   )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+   r2   r7   Meanr;   rM   rU   MetricrZ   rQ   r^   r   r   <module>r      sx    "  - @ , 7 B 6 B / 5 ./8(:: 8 08: /0*8);; *8 1*8Z 9:)8"3"E"E )8 ;)8X 9:*8"3"E"E *8 ;*8Z 23>*,11 >* 4>*B ./48(:: 48 048n *+*8$66 *8 ,*8\ %&_)&& _) '_)D/r   