
    6bijR                        S r SSKrSSKJs  Jr  SSKJr  SSKJ	r
  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  \" S5       " S S\R4                  5      5       r\" S5       " S S\R8                  5      5       r\" S5       " S S\R8                  5      5       r\" S5       " S S\R8                  5      5       r\" S5       " S S\R8                  5      5       r \" S5       " S S \R8                  5      5       r!\" S!5       " S" S#\R4                  5      5       r"\" S$5       " S% S&\R8                  5      5       r#\" S'5       " S( S)\RH                  5      5       r%S+S* jr&g),z%Regression metrics, e.g. MAE/MSE/etc.    N)backend)utils)logcosh)mean_absolute_error)mean_absolute_percentage_error)mean_squared_error)mean_squared_logarithmic_error)base_metric)losses_utils)metrics_utils)is_tensor_or_variable)keras_exportzkeras.metrics.MeanRelativeErrorc                   j   ^  \ rS rSrSr\R                  SU 4S jj5       rSU 4S jjrU 4S jr	Sr
U =r$ )	MeanRelativeError%   aC  Computes the mean relative error by normalizing with the given values.

This metric creates two local variables, `total` and `count` that are used
to compute the mean relative error. This is weighted by `sample_weight`, and
it is ultimately returned as `mean_relative_error`: an idempotent operation
that simply divides `total` by `count`.

If `sample_weight` is `None`, weights default to 1.
Use `sample_weight` of 0 to mask values.

Args:
  normalizer: The normalizer values with same shape as predictions.
  name: (Optional) string name of the metric instance.
  dtype: (Optional) data type of the metric result.

Standalone usage:

>>> m = tf.keras.metrics.MeanRelativeError(normalizer=[1, 3, 2, 3])
>>> m.update_state([1, 3, 2, 3], [2, 4, 6, 8])

>>> # metric = mean(|y_pred - y_true| / normalizer)
>>> #        = mean([1, 1, 4, 5] / [1, 3, 2, 3]) = mean([1, 1/3, 2, 5/3])
>>> #        = 5/4 = 1.25
>>> m.result().numpy()
1.25

Usage with `compile()` API:

```python
model.compile(
  optimizer='sgd',
  loss='mse',
  metrics=[tf.keras.metrics.MeanRelativeError(normalizer=[1, 3])])
```
c                 l   > [         TU ]  X#S9  [        R                  " XR                  5      nXl        g )Nnamedtype)super__init__tfcast_dtype
normalizer)selfr   r   r   	__class__s       a/home/james-whalen/.local/lib/python3.13/site-packages/tf_keras/src/metrics/regression_metrics.pyr   MeanRelativeError.__init__K   s*    d0WWZ5
$    c                 "  > [         R                  " XR                  5      n[         R                  " X R                  5      n[        R                  " X!/U5      u  u  nnn[
        R                  " X!5      u  p![
        R                  " X R                  5      u  o l        UR                  R                  UR                  5        [         R                  R                  [         R                  " X-
  5      U R                  5      n[        TU ]=  XCS9$ )a=  Accumulates metric 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   r   r   r   ,ragged_assert_compatible_and_get_flat_valuesr   squeeze_or_expand_dimensionsremove_squeezable_dimensionsr   shapeassert_is_compatible_withmathdivide_no_nanabsr   update_state)r   y_truey_predr#   relative_errorsr   s        r   r,   MeanRelativeError.update_stateQ   s     -- )UUm
	 	
 &BB
 #/"K"KOO#
 	..v||<''//FF6?#T__
 w# $ 
 	
r    c                   > U R                   nS[        U5      (       a  [        R                  " U5      OU0n[        TU ]  5       n[        [        UR                  5       5      [        UR                  5       5      -   5      $ )Nr   )	r   r   r   evalr   
get_configdictlistitems)r   nconfigbase_configr   s       r   r3   MeanRelativeError.get_configv   se    OO-B1-E-E',,q/1
 g(*D**,-V\\^0DDEEr    )r   )NNN)__name__
__module____qualname____firstlineno____doc__dtensor_utilsinject_meshr   r,   r3   __static_attributes____classcell__r   s   @r   r   r   %   s5    "H % %
#
JF Fr    r   zkeras.metrics.CosineSimilarityc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )CosineSimilarity   a  Computes the cosine similarity between the labels and predictions.

`cosine similarity = (a . b) / ||a|| ||b||`

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) The dimension along which the cosine
    similarity is computed. Defaults to `-1`.

Standalone usage:

>>> # 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 = tf.keras.metrics.CosineSimilarity(axis=1)
>>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]])
>>> m.result().numpy()
0.49999997

>>> m.reset_state()
>>> m.update_state([[0., 1.], [1., 1.]], [[1., 0.], [1., 1.]],
...                sample_weight=[0.3, 0.7])
>>> m.result().numpy()
0.6999999

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.CosineSimilarity(axis=1)])
```
c                 ,   > [         TU ]  [        XUS9  g )N)r   axis)r   r   cosine_similarity)r   r   r   rJ   r   s       r   r   CosineSimilarity.__init__   s    *DDIr     )rK   N
r<   r=   r>   r?   r@   rA   rB   r   rC   rD   rE   s   @r   rG   rG      s%    )V J Jr    rG   zkeras.metrics.MeanAbsoluteErrorc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )MeanAbsoluteError   ao  Computes the mean absolute error between the labels and predictions.

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

Standalone usage:

>>> m = tf.keras.metrics.MeanAbsoluteError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
0.25

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

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanAbsoluteError()])
```
c                 *   > [         TU ]  [        XS9  g Nr   )r   r   r   r   r   r   r   s      r   r   MeanAbsoluteError.__init__   s    ,d@r    rM   )r   NrO   rE   s   @r   rQ   rQ      s$    : A Ar    rQ   z)keras.metrics.MeanAbsolutePercentageErrorc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )MeanAbsolutePercentageError   a  Computes the mean absolute percentage error between `y_true` and
`y_pred`.

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

Standalone usage:

>>> m = tf.keras.metrics.MeanAbsolutePercentageError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
250000000.0

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

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanAbsolutePercentageError()])
```
c                 *   > [         TU ]  [        XS9  g rT   )r   r   r   rV   s      r   r   $MeanAbsolutePercentageError.__init__       7Kr    rM   )r   NrO   rE   s   @r   rY   rY      $    < L Lr    rY   zkeras.metrics.MeanSquaredErrorc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )MeanSquaredError   ag  Computes the mean squared error between `y_true` and `y_pred`.

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

Standalone usage:

>>> m = tf.keras.metrics.MeanSquaredError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
0.25

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

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanSquaredError()])
```
c                 *   > [         TU ]  [        XS9  g rT   )r   r   r   rV   s      r   r   MeanSquaredError.__init__  s    +T?r    rM   )r   NrO   rE   s   @r   r`   r`      s$    : @ @r    r`   z)keras.metrics.MeanSquaredLogarithmicErrorc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )MeanSquaredLogarithmicErrori  a  Computes the mean squared logarithmic error between `y_true` and
`y_pred`.

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

Standalone usage:

>>> m = tf.keras.metrics.MeanSquaredLogarithmicError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
0.12011322

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

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.MeanSquaredLogarithmicError()])
```
c                 *   > [         TU ]  [        XS9  g rT   )r   r   r	   rV   s      r   r   $MeanSquaredLogarithmicError.__init__>  r]   r    rM   )r	   NrO   rE   s   @r   re   re     r^   r    re   z"keras.metrics.RootMeanSquaredErrorc                   d   ^  \ rS rSrSr\R                  SU 4S jj5       rSU 4S jjrS r	Sr
U =r$ )	RootMeanSquaredErroriC  a  Computes root mean squared error metric between `y_true` and `y_pred`.

Standalone usage:

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

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

Usage with `compile()` API:

```python
model.compile(
    optimizer='sgd',
    loss='mse',
    metrics=[tf.keras.metrics.RootMeanSquaredError()])
```
c                     > [         TU ]  XS9  g rT   )r   r   rV   s      r   r   RootMeanSquaredError.__init__^  s    +r    c                   > [         R                  " XR                  5      n[         R                  " X R                  5      n[        R                  " X!5      u  p![         R
                  R                  X!5      n[        TU ]!  XCS9$ )aN  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.
r"   )	r   r   r   r   r%   r)   squared_differencer   r,   )r   r-   r.   r#   error_sqr   s        r   r,   !RootMeanSquaredError.update_stateb  sg     --%BB
 77--f=w#H#JJr    c                     [         R                  " [         R                  R                  U R                  U R
                  5      5      $ r;   )r   sqrtr)   r*   totalcount)r   s    r   resultRootMeanSquaredError.resultw  s*    wwrww,,TZZDEEr    rM   )root_mean_squared_errorNr;   )r<   r=   r>   r?   r@   rA   rB   r   r,   rt   rC   rD   rE   s   @r   ri   ri   C  s4    2 , ,K*F Fr    ri   zkeras.metrics.LogCoshErrorc                   N   ^  \ rS rSrSr\R                  SU 4S jj5       rSrU =r	$ )LogCoshErrori{  a  Computes the logarithm of the hyperbolic cosine of the prediction error.

`logcosh = log((exp(x) + exp(-x))/2)`, where x is the error (y_pred -
y_true)

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

Standalone usage:

>>> m = tf.keras.metrics.LogCoshError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
0.10844523

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

Usage with `compile()` API:

```python
model.compile(optimizer='sgd',
              loss='mse',
              metrics=[tf.keras.metrics.LogCoshError()])
```
c                 *   > [         TU ]  [        XS9  g rT   )r   r   r   rV   s      r   r   LogCoshError.__init__  s    $4r    rM   )r   NrO   rE   s   @r   rx   rx   {  s"    > 5 5r    rx   zkeras.metrics.R2Scorec                   ~   ^  \ rS rSrSr\R                      S
U 4S jj5       rS rSS jr	S r
S rU 4S jrS	rU =r$ )R2Scorei  a  Computes R2 score.

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 = tf.keras.metrics.R2Score()
>>> metric.update_state(y_true, y_pred)
>>> result = metric.result()
>>> result.numpy()
0.57142854
c                    > [         TU ]  X4S9  SnX;  a  [        SU SU 35      eUS:  a  [        SU 35      eXl        X l        U R                  SSS9U l        S	U l        g )
Nr   )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int32F)r   r   
ValueErrorclass_aggregationnum_regressors
add_weightr   built)r   r   r   r   r   valid_class_aggregation_valuesr   s         r   r   R2Score.__init__  s     	d0*
&
 B89 ://@.AC 
 A,,:+;= 
 "3,??W?M
r    c                 p   [        U5      S:w  d  [        U5      S:w  a  [        SU SU S35      eUS   b  US   c  [        SU SU S35      eUS   nU R                  SU/SS	9U l        U R                  S
U/SS	9U l        U R                  SU/SS	9U l        U R                  SU/SS	9U l        SU l        g )N   zcR2Score expects 2D inputs with shape (batch_size, output_dim). Received input shapes: y_pred.shape=z and y_true.shape=.rN   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zeros)r   r'   initializersumresidualrs   T)lenr   r   r   r   	total_msers   r   )r   y_true_shapey_pred_shapenum_classess       r   buildR2Score.build  s    |!S%6!%;((4~ 6  ,~Q0  #|B'7'?( )5~ 6  ,~Q	0  #2&??- + 

 ??- # 

 - ) 

 __- % 


 
r    c                    [         R                  " XR                  S9n[         R                  " X R                  S9nU R                  (       d&  U R	                  UR
                  UR
                  5        Uc  Sn[         R                  " X0R                  S9nUR
                  R                  S:X  a  [         R                  " USS9n[         R                  R                  R                  X1S9nX-  nU R                  R                  [         R                  " USS95        U R                  R                  [         R                  " X-  SS95        U R                  R                  [         R                  " X-
  S-  U-  SS95        U R                   R                  [         R                  " USS95        U R"                  R                  [         R$                  " U5      5        g )NrU      rJ   )weightsvaluesr   r   )r   convert_to_tensorr   r   r   r'   rankexpand_dims__internal__opsbroadcast_weightsr   
assign_add
reduce_sumr   r   rs   r   size)r   r-   r.   r#   weighted_y_trues        r   r,   R2Score.update_state  sa   %%fJJ?%%fJJ?zzJJv||V\\2 M,,]**M##q(NN=qAM++==! > 
 !0BMM/BC##MM&2;	
 	!!MM6?q0=@qI	
 	

bmmMBC##BGGFO4r    c                    U R                   U R                  -  nU R                  U R                   U-  -
  nSU R                  U-  -
  n[        R
                  " [        R                  R                  U5      SU5      nU R                  S:X  a  [        R                  " U5      nOEU R                  S:X  a3  [        R                  " X#-  5      n[        R                  " U5      nXV-  nOUnU R                  S:w  GaY  U R                  U R                  S-
  :  a  [        R                  " SSS9  U$ U R                  U R                  S-
  :X  a  [        R                  " S	SS9  U$ [        R                  " U R                  [        R                   S
9n[        R                  " U R                  [        R                   S
9n[        R"                  " [        R$                  " SU5      [        R$                  " US5      5      n	[        R$                  " [        R$                  " Xx5      S5      n
[        R$                  " S[        R&                  " X5      5      nU$ )Nr   g        r~   r   r   zdMore independent predictors than datapoints in adjusted R2 score. Falling back to standard R2 score.r   )
stacklevelzIDivision by zero in Adjusted R2 score. Falling back to standard R2 score.rU   g      ?)r   rs   r   r   r   wherer)   is_infr   reduce_meanr   r   r   warningswarnr   float32multiplysubtractdivide)r   meanrr   
raw_scoresr2_scoreweighted_sumsum_of_weightsr7   pnumdens              r   rt   R2Score.result1  s   xx$**$  488d?2$..501
XXbggnnZ8#zJ
!!%66~~j1H##'BB==);<L]]51N#4H!H!#""T%5%5%99O &  $$(8(81(<<9   GGD,,BJJ?GGD//rzzBkkKKX.As0C kk"++a"3S9;;sBIIc,?@r    c                     U R                    H;  nUR                  [        R                  " UR                  UR
                  S95        M=     g rT   )	variablesassignr   r   r'   r   )r   vs     r   reset_stateR2Score.reset_stateW  s/    AHHRXXaggQWW56  r    c                 ^   > U R                   U R                  S.n[        TU ]  5       n0 UEUE$ )N)r   r   )r   r   r   r3   )r   r8   r9   r   s      r   r3   R2Score.get_config[  s;    !%!7!7"11
 g(*(+(((r    )r   r   rs   r   r   r   r   r   )r~   r   r   Nr;   )r<   r=   r>   r?   r@   rA   rB   r   r   r,   rt   r   r3   rC   rD   rE   s   @r   r|   r|     sQ    (T  , >%N58$L7) )r    r|   c                     [         R                  R                  XS9n [         R                  R                  XS9n[         R                  " X-  US9$ )a  Computes the cosine similarity between labels and predictions.

Args:
  y_true: The ground truth values.
  y_pred: The prediction values.
  axis: (Optional) -1 is the dimension along which the cosine
    similarity is computed. Defaults to `-1`.

Returns:
  Cosine similarity value.
r   )r   linalgl2_normalizer   )r-   r.   rJ   s      r   rK   rK   d  sE     YY##F#6FYY##F#6F==t44r    )rN   )'r@   r   tensorflow.compat.v2compatv2r   tf_keras.srcr   tf_keras.src.dtensorr   rA   tf_keras.src.lossesr   r   r   r   r	   tf_keras.src.metricsr
   tf_keras.src.utilsr   r   tf_keras.src.utils.tf_utilsr    tensorflow.python.util.tf_exportr   Meanr   MeanMetricWrapperrG   rQ   rY   r`   re   ri   rx   Metricr|   rK   rM   r    r   <module>r      s   ,  ! !   7 ' 3 > 2 > , + , = : /0VF(( VF 1VFr ./.J{44 .J 0.Jb /0 A55  A 1 AF 9:!L+"?"? !L ;!LH ./ @{44  @ 0 @F 9:!L+"?"? !L ;!LH 234F;++ 4F 44Fn *+"5;00 "5 ,"5L %&~)k   ~) '~)B5r    