
    2Vh                         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d       Z	 ed      dd	       Z
 ed
       G d dej                               Z ed       G d dej                               Zy)    )backend)ops)keras_export)squeeze_or_expand_to_same_rank)reduction_metricsz!keras.metrics.pearson_correlationc                    t        j                  |      }t        j                  | |j                        } t        | |      \  } }| t        j                  | |d      z
  }|t        j                  ||d      z
  }|t        j
                  ||d      z  }|t        j
                  ||d      z  }t        j                  ||z  |      S )a  Computes the Pearson coefficient between labels and predictions.

    Formula:

    ```python
    loss = mean(l2norm(y_true - mean(y_true) * l2norm(y_pred - mean(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:
        Pearson Correlation Coefficient tensor.

    Example:

    >>> y_true = [[0, 1, 0.5], [1, 1, 0.2]]
    >>> y_pred = [[0.1, 0.9, 0.5], [1, 0.9, 0.2]]
    >>> loss = keras.losses.concordance_correlation(
    ...     y_true, y_pred, axis=-1
    ... ).numpy()
    [1.         0.99339927]
    dtypeTaxiskeepdimsr   )r   convert_to_tensorr
   r   meanstd)y_truey_predr   y_true_normy_pred_norms        U/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/metrics/correlation_metrics.pypearson_correlationr      s    6 ""6*F""6>F3FFCNFF388FEEK388FEEK$ NNK$ NNK88K+-D99    z%keras.metrics.concordance_correlationc                    t        j                  |      }t        j                  | |j                        } t        | |      \  } }t        j                  | |d      }t        j                  ||d      }t        j
                  | |z
  |d      }t        j
                  ||z
  |d      }| |z
  ||z
  z  }||z   t        j                  ||z
        z   }t        j                  d|z  |t        j                         z   z  |      S )a  Computes the Concordance coefficient between labels and predictions.

    Formula:

    ```python
    loss = mean(
        2 * (y_true - mean(y_true) * (y_pred - mean(y_pred)) / (
            var(y_true) + var(y_pred) + square(mean(y_true) - mean(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:
        Concordance Correlation Coefficient tensor.

    Example:

    >>> y_true = [[0, 1, 0.5], [1, 1, 0.2]]
    >>> y_pred = [[0.1, 0.9, 0.5], [1, 0.9, 0.2]]
    >>> loss = keras.losses.concordance_correlation(
    ...     y_true, y_pred, axis=-1
    ... ).numpy()
    [0.97560976 0.98765432]
    r	   Tr      r   )	r   r   r
   r   r   varsquarer   epsilon)	r   r   r   y_true_meany_pred_mean
y_true_var
y_pred_varcovarnorms	            r   concordance_correlationr$   0   s    > ""6*F""6>F3FFCNFF((6t<K((6t<K+-D4HJ+-D4HJk!f{&:;E
"SZZk0I%JJD88AI(9!9:FFr   z keras.metrics.PearsonCorrelationc                   0     e Zd ZdZ	 	 	 d fd	Zd Z xZS )PearsonCorrelationa  Calculates the Pearson Correlation Coefficient (PCC).

    PCC measures the linear relationship between the true values (`y_true`) and
    the predicted values (`y_pred`). The coefficient ranges from -1 to 1, where
    a value of 1 implies a perfect positive linear correlation, 0 indicates no
    linear correlation, and -1 indicates a perfect negative linear correlation.

    This metric is widely used in regression tasks where the strength of the
    linear relationship between predictions and true labels is an
    important evaluation criterion.

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.
        axis: (Optional) integer or tuple of integers of the axis/axes along
            which to compute the metric. Defaults to `-1`.

    Example:

    >>> pcc = keras.metrics.PearsonCorrelation(axis=-1)
    >>> y_true = [[0, 1, 0.5], [1, 1, 0.2]]
    >>> y_pred = [[0.1, 0.9, 0.5], [1, 0.9, 0.2]]
    >>> pcc.update_state(y_true, y_pred)
    >>> pcc.result()
    0.9966996338993913

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='mean_squared_error',
                  metrics=[keras.metrics.PearsonCorrelation()])
    ```
    c                 P    t         |   t        |||       || _        d| _        y N)fnnamer
   r   up)super__init__r   r   
_directionselfr*   r
   r   	__class__s       r   r-   zPearsonCorrelation.__init__   s3     	"	 	 	
 	r   c                 J    | j                   | j                  | j                  dS Nr*   r
   r   r4   r0   s    r   
get_configzPearsonCorrelation.get_config   !    IIZZII
 	
r   )r   N__name__
__module____qualname____doc__r-   r6   __classcell__r1   s   @r   r&   r&   _   s    !J #	 
r   r&   z$keras.metrics.ConcordanceCorrelationc                   0     e Zd ZdZ	 	 	 d fd	Zd Z xZS )ConcordanceCorrelationa  Calculates the Concordance Correlation Coefficient (CCC).

    CCC evaluates the agreement between true values (`y_true`) and predicted
    values (`y_pred`) by considering both precision and accuracy. The
    coefficient ranges from -1 to 1, where a value of 1 indicates perfect
    agreement.

    This metric is useful in regression tasks where it is important to assess
    how well the predictions match the true values, taking into account both
    their correlation and proximity to the 45-degree line of perfect
    concordance.

    Args:
        name: (Optional) string name of the metric instance.
        dtype: (Optional) data type of the metric result.
        axis: (Optional) integer or tuple of integers of the axis/axes along
            which to compute the metric. Defaults to `-1`.

    Example:

    >>> ccc = keras.metrics.ConcordanceCorrelation(axis=-1)
    >>> y_true = [[0, 1, 0.5], [1, 1, 0.2]]
    >>> y_pred = [[0.1, 0.9, 0.5], [1, 0.9, 0.2]]
    >>> ccc.update_state(y_true, y_pred)
    >>> ccc.result()
    0.9816320385426076

    Usage with `compile()` API:

    ```python
    model.compile(optimizer='sgd',
                  loss='mean_squared_error',
                  metrics=[keras.metrics.ConcordanceCorrelation()])
    ```
    c                 P    t         |   t        |||       || _        d| _        y r(   )r,   r-   r$   r   r.   r/   s       r   r-   zConcordanceCorrelation.__init__   s3     	&	 	 	
 	r   c                 J    | j                   | j                  | j                  dS r3   r4   r5   s    r   r6   z!ConcordanceCorrelation.get_config   r7   r   )r$   Nr8   r9   r?   s   @r   rA   rA      s    "L '	 
r   rA   N)r8   )	keras.srcr   r   keras.src.api_exportr   keras.src.losses.lossr   keras.src.metricsr   r   r$   MeanMetricWrapperr&   rA    r   r   <module>rJ      s      - @ / 12$: 3$:N 56+G 7+G\ 019
*<< 9
 29
x 45:
.@@ :
 6:
r   