o
    7?eIR                     @   s  d Z ddlZddlm  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 ddlmZ ddlmZ edG dd dejZedG dd dejZedG dd dejZedG dd dejZedG dd dejZ edG dd  d ejZ!ed!G d"d# d#ejZ"ed$G d%d& d&ejZ#ed'G d(d) d)ej$Z%d-d+d,Z&dS ).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                       sB   e Zd ZdZejd	 fdd	Zd
 fdd	Z fddZ  Z	S )MeanRelativeErrora  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])])
    ```
    Nc                    s(   t  j||d t|| j}|| _d S )Nnamedtype)super__init__tfcast_dtype
normalizer)selfr   r   r   	__class__ e/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/keras/src/metrics/regression_metrics.pyr   K   s   
zMeanRelativeError.__init__c                    s   t || j}t || j}t||g|\\}}}t||\}}t|| j\}| _|j	
|j	 t jt || | j}t j||dS )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   Z,ragged_assert_compatible_and_get_flat_valuesr
   squeeze_or_expand_dimensionsZremove_squeezable_dimensionsr   shapeZassert_is_compatible_withmathdivide_no_nanabsr   update_state)r   y_truey_predr   Zrelative_errorsr   r   r   r$   Q   s,   
zMeanRelativeError.update_statec                    sF   | j }dt|rt|n|i}t  }tt| t|  S )Nr   )	r   r   r   evalr   
get_configdictlistitems)r   nconfigbase_configr   r   r   r(   v   s
   
zMeanRelativeError.get_config)NNN)
__name__
__module____qualname____doc__dtensor_utilsinject_meshr   r$   r(   __classcell__r   r   r   r   r   %   s    $%r   zkeras.metrics.CosineSimilarityc                       s(   e Zd ZdZejd fdd	Z  ZS )CosineSimilaritya  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)])
    ```
    cosine_similarityNc                    s   t  jt|||d d S )N)r   axis)r   r   r8   )r   r   r   r:   r   r   r   r      s   zCosineSimilarity.__init__)r8   Nr9   r0   r1   r2   r3   r4   r5   r   r6   r   r   r   r   r7      s    +r7   zkeras.metrics.MeanAbsoluteErrorc                       (   e Zd ZdZejd fdd	Z  ZS )MeanAbsoluteErrora  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()])
    ```
    r   Nc                       t  jt||d d S Nr   )r   r   r   r   r   r   r   r   r   r         zMeanAbsoluteError.__init__)r   Nr;   r   r   r   r   r=          r=   z)keras.metrics.MeanAbsolutePercentageErrorc                       r<   )MeanAbsolutePercentageErrora  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()])
    ```
    r   Nc                    r>   r?   )r   r   r   rA   r   r   r   r      rB   z$MeanAbsolutePercentageError.__init__)r   Nr;   r   r   r   r   rD          rD   zkeras.metrics.MeanSquaredErrorc                       r<   )MeanSquaredErrora  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()])
    ```
    r   Nc                    r>   r?   )r   r   r   rA   r   r   r   r     rB   zMeanSquaredError.__init__)r   Nr;   r   r   r   r   rF      rC   rF   z)keras.metrics.MeanSquaredLogarithmicErrorc                       r<   )MeanSquaredLogarithmicErrora  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()])
    ```
    r   Nc                    r>   r?   )r   r   r   rA   r   r   r   r   >  rB   z$MeanSquaredLogarithmicError.__init__)r   Nr;   r   r   r   r   rG     rE   rG   z"keras.metrics.RootMeanSquaredErrorc                       s>   e Zd ZdZejd
 fdd	Zd fdd	Zdd	 Z  Z	S )RootMeanSquaredErroraS  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()])
    ```
    root_mean_squared_errorNc                    s   t  j||d d S r?   )r   r   rA   r   r   r   r   ^  s   zRootMeanSquaredError.__init__c                    sJ   t || j}t || j}t||\}}t j||}t j||dS )a  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!   Zsquared_differencer   r$   )r   r%   r&   r   Zerror_sqr   r   r   r$   b  s   z!RootMeanSquaredError.update_statec                 C   s   t t j| j| jS r/   )r   sqrtr!   r"   totalcount)r   r   r   r   resultw  s   zRootMeanSquaredError.result)rI   Nr/   )
r0   r1   r2   r3   r4   r5   r   r$   rM   r6   r   r   r   r   rH   C  s    rH   zkeras.metrics.LogCoshErrorc                       r<   )LogCoshErrora,  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()])
    ```
    r   Nc                    r>   r?   )r   r   r   rA   r   r   r   r     rB   zLogCoshError.__init__)r   Nr;   r   r   r   r   rN   {  s    rN   zkeras.metrics.R2Scorec                       s^   e Zd ZdZej				d fdd	Zdd	 Zdd
dZdd Z	dd Z
 fddZ  ZS )R2Scorea.  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
    uniform_averager   r2_scoreNc                    sl   t  j||d d}||vrtd| d| |dk r#td| || _|| _| jddd| _d	| _d S )
Nr   )NrP   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_samplesZint32F)r   r   
ValueErrorclass_aggregationnum_regressors
add_weightrS   built)r   rU   rV   r   r   Zvalid_class_aggregation_valuesr   r   r   r     s(   
zR2Score.__init__c                 C   s   t |dkst |dkrtd| d| d|d d u s#|d d u r.td| d| d|d }| jd|gdd	| _| jd
|gdd	| _| jd|gdd	| _| jd|gdd	| _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=.r9   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    ZinitializersumZresidualrL   T)lenrT   rW   r[   r]   	total_mserL   rX   )r   Zy_true_shapeZy_pred_shapeZnum_classesr   r   r   build  sL   
zR2Score.buildc                 C   s  t j|| jd}t j|| jd}| js| |j|j |d u r!d}t j|| jd}|jjdkr6t j|dd}t jj	j
||d}|| }| jt j|dd | jt j|| dd | jt j|| d | dd | jt j|dd | jt | d S )Nr@      r:   )weightsvaluesr   rY   )r   Zconvert_to_tensorr   rX   r`   r    ZrankZexpand_dimsZ__internal__opsZbroadcast_weightsr]   Z
assign_add
reduce_sumr[   r_   rL   rS   size)r   r%   r&   r   Zweighted_y_truer   r   r   r$     s,   zR2Score.update_statec                 C   s@  | j | j }| j| j |  }d| j|  }ttj|d|}| jdkr+t	|}n| jdkrAt
|| }t
|}|| }n|}| jdkr| j| jd krYtjddd |S | j| jd krjtjd	dd |S tj| jtjd
}tj| jtjd
}ttd|t|d}	tt||d}
tdt|	|
}|S )Nra   g        rP   rR   r   zdMore independent predictors than datapoints in adjusted R2 score. Falling back to standard R2 score.rY   )
stacklevelzIDivision by zero in Adjusted R2 score. Falling back to standard R2 score.r@   g      ?)r]   rL   r[   r_   r   wherer!   Zis_infrU   Zreduce_meanrf   rV   rS   warningswarnr   Zfloat32multiplysubtractdivide)r   meanrK   Z
raw_scoresrQ   Zweighted_sumZsum_of_weightsr,   pnumZdenr   r   r   rM   1  s@   




zR2Score.resultc                 C   s(   | j D ]}|tj|j|jd qd S r?   )	variablesZassignr   r\   r    r   )r   vr   r   r   reset_stateW  s   
zR2Score.reset_statec                    s$   | j | jd}t  }i ||S )N)rU   rV   )rU   rV   r   r(   )r   r-   r.   r   r   r   r(   [  s
   
zR2Score.get_config)rP   r   rQ   Nr/   )r0   r1   r2   r3   r4   r5   r   r`   r$   rM   rt   r(   r6   r   r   r   r   rO     s    *
'&rO   r9   c                 C   s2   t jj| |d} t jj||d}t j| | |dS )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.
    rb   )r   ZlinalgZl2_normalizerf   )r%   r&   r:   r   r   r   r8   d  s   r8   )r9   )'r3   rj   Ztensorflow.compat.v2compatv2r   Z	keras.srcr   Zkeras.src.dtensorr   r4   Zkeras.src.lossesr   r   r   r   r   Zkeras.src.metricsr	   Zkeras.src.utilsr
   r   Zkeras.src.utils.tf_utilsr   Z tensorflow.python.util.tf_exportr   ZMeanr   ZMeanMetricWrapperr7   r=   rD   rF   rG   rH   rN   ZMetricrO   r8   r   r   r   r   <module>   sF   Y1#$#$7& B