computes the mean squared error between ytrue and ypred formula python loss meansquareytrue ypred args name optional string name of the metric instance dtype optional data type of the metric result example m keras metrics meansquarederror m updatestate0 1 0 0 1 1 0 0 m result 0 25 metric should be minimized during optimization computes the mean absolute error between the labels and predictions formula python loss meanabsytrue ypred args name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics meanabsoluteerror m updatestate0 1 0 0 1 1 0 0 m result 0 25 m resetstate m updatestate0 1 0 0 1 1 0 0 sampleweight1 0 m result 0 5 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics meanabsoluteerror metric should be minimized during optimization computes mean absolute percentage error between ytrue and ypred formula python loss 100 meanabsytrue ypred ytrue args name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics meanabsolutepercentageerror m updatestate0 1 0 0 1 1 0 0 m result 250000000 0 m resetstate m updatestate0 1 0 0 1 1 0 0 sampleweight1 0 m result 500000000 0 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics meanabsolutepercentageerror metric should be minimized during optimization computes mean squared logarithmic error between ytrue and ypred formula python loss meansquarelogytrue 1 logypred 1 args name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics meansquaredlogarithmicerror m updatestate0 1 0 0 1 1 0 0 m result 0 12011322 m resetstate m updatestate0 1 0 0 1 1 0 0 sampleweight1 0 m result 0 24022643 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics meansquaredlogarithmicerror metric should be minimized during optimization computes root mean squared error metric between ytrue and ypred formula python loss sqrtmeanypred ytrue 2 args name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics rootmeansquarederror m updatestate0 1 0 0 1 1 0 0 m result 0 5 m resetstate m updatestate0 1 0 0 1 1 0 0 sampleweight1 0 m result 0 70710677 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics rootmeansquarederror metric should be minimized during optimization accumulates root mean squared error statistics args ytrue the ground truth values ypred the predicted values sampleweight optional weighting of each example can be a tensor whose rank is either 0 or the same rank as ytrue and must be broadcastable to ytrue defaults to 1 returns update op computes the cosine similarity between the labels and predictions formula python loss suml2normytrue l2normypred see cosine similarityhttps en wikipedia orgwikicosinesimilarity 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 standalone usage l2normytrue 0 1 1 1 414 1 1 414 l2normypred 1 0 1 1 414 1 1 414 l2normytrue l2normypred 0 0 0 5 0 5 result meansuml2normytrue l2normypred axis1 0 0 0 5 0 5 2 m keras metrics cosinesimilarityaxis1 m updatestate0 1 1 1 1 0 1 1 m result 0 49999997 m resetstate m updatestate0 1 1 1 1 0 1 1 sampleweight0 3 0 7 m result 0 6999999 usage with compile api python model compile optimizer sgd loss mse metricskeras metrics cosinesimilarityaxis1 metric should be maximized during optimization computes the logarithm of the hyperbolic cosine of the prediction error formula python error ypred ytrue logcosh meanlogexperror experror2 axis1 args name optional string name of the metric instance dtype optional data type of the metric result examples standalone usage m keras metrics logcosherror m updatestate0 1 0 0 1 1 0 0 m result 0 10844523 m resetstate m updatestate0 1 0 0 1 1 0 0 sampleweight1 0 m result 0 21689045 usage with compile api python model compileoptimizer sgd loss mse metricskeras metrics logcosherror metric should be minimized during optimization adapted from tfaddons implementation rsquare class computes r2 score formula python sumsquaresresiduals sumytrue ypred 2 sumsquares sumytrue meanytrue 2 r2 1 sumsquaresresiduals sumsquares this is also called the coefficient of determination https en wikipedia orgwikicoefficientofdetermination it indicates how close the fitted regression line is to groundtruth 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 classaggregation 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 scikitlearn should be one of none no aggregation uniformaverage varianceweightedaverage numregressors 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 ytrue np array1 4 3 dtypenp float32 ypred np array2 4 4 dtypenp float32 metric keras metrics r2score metric updatestateytrue ypred result metric result result 0 57142854 metric should be maximized during optimization accumulates root mean squared error statistics args ytrue the ground truth values ypred the predicted values sampleweight optional weighting of each example can be a tensor whose rank is either 0 or the same rank as ytrue and must be broadcastable to ytrue defaults to 1 returns update op make sure there s a features dimension computes the cosine similarity between labels and predictions formula python loss suml2normytrue l2normypred args ytrue tensor of true targets ypred tensor of predicted targets axis axis along which to determine similarity defaults to 1 returns cosine similarity tensor example ytrue 0 1 1 1 1 1 ypred 1 0 1 1 1 1 loss keras losses cosinesimilarityytrue ypred axis1 0 0 99999994 0 99999994 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 metric should be minimized during optimization 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 standalone usage 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 metric should be minimized during optimization 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 standalone usage 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 metric should be minimized during optimization 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 standalone usage 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 metric should be minimized during optimization 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 standalone usage 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 metric should be minimized during optimization 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 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 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 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 metric should be maximized during optimization 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 standalone usage 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 metric should be minimized during optimization adapted from tf addons implementation rsquare class 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 metric should be maximized during optimization 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 make sure there s a features dimension 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
import warnings

from keras import initializers
from keras import ops
from keras.api_export import keras_export
from keras.losses.loss import squeeze_to_same_rank
from keras.losses.losses import log_cosh
from keras.losses.losses import mean_absolute_error
from keras.losses.losses import mean_absolute_percentage_error
from keras.losses.losses import mean_squared_error
from keras.losses.losses import mean_squared_logarithmic_error
from keras.metrics import reduction_metrics
from keras.utils.numerical_utils import normalize


@keras_export("keras.metrics.MeanSquaredError")
class MeanSquaredError(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="mean_squared_error", dtype=None):
        super().__init__(fn=mean_squared_error, name=name, dtype=dtype)
        
        self._direction = "down"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}


@keras_export("keras.metrics.MeanAbsoluteError")
class MeanAbsoluteError(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="mean_absolute_error", dtype=None):
        super().__init__(mean_absolute_error, name, dtype=dtype)
        
        self._direction = "down"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}


@keras_export("keras.metrics.MeanAbsolutePercentageError")
class MeanAbsolutePercentageError(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="mean_absolute_percentage_error", dtype=None):
        super().__init__(mean_absolute_percentage_error, name, dtype=dtype)
        
        self._direction = "down"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}


@keras_export("keras.metrics.MeanSquaredLogarithmicError")
class MeanSquaredLogarithmicError(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="mean_squared_logarithmic_error", dtype=None):
        super().__init__(mean_squared_logarithmic_error, name, dtype=dtype)
        
        self._direction = "down"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}


@keras_export("keras.metrics.RootMeanSquaredError")
class RootMeanSquaredError(reduction_metrics.Mean):
    

    def __init__(self, name="root_mean_squared_error", dtype=None):
        super().__init__(name, dtype=dtype)
        
        self._direction = "down"

    def update_state(self, y_true, y_pred, sample_weight=None):
        
        y_true = ops.convert_to_tensor(y_true, self._dtype)
        y_pred = ops.convert_to_tensor(y_pred, self._dtype)
        y_true, y_pred = squeeze_to_same_rank(y_true, y_pred)
        error_sq = ops.square(y_pred - y_true)
        return super().update_state(error_sq, sample_weight=sample_weight)

    def result(self):
        return ops.sqrt(super().result())


@keras_export("keras.metrics.CosineSimilarity")
class CosineSimilarity(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="cosine_similarity", dtype=None, axis=-1):
        super().__init__(cosine_similarity, name, dtype=dtype, axis=axis)
        
        self._direction = "up"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}


@keras_export("keras.metrics.LogCoshError")
class LogCoshError(reduction_metrics.MeanMetricWrapper):
    

    def __init__(self, name="logcosh", dtype=None):
        super().__init__(log_cosh, name, dtype=dtype)
        
        self._direction = "down"

    def get_config(self):
        return {"name": self.name, "dtype": self.dtype}



@keras_export("keras.metrics.R2Score")
class R2Score(reduction_metrics.Metric):
    

    def __init__(
        self,
        class_aggregation="uniform_average",
        num_regressors=0,
        name="r2_score",
        dtype=None,
    ):
        super().__init__(name=name, dtype=dtype)
        
        self._direction = "up"

        valid_class_aggregation_values = (
            None,
            "uniform_average",
            "variance_weighted_average",
        )
        if class_aggregation not in valid_class_aggregation_values:
            raise ValueError(
                "Invalid value for argument `class_aggregation`. Expected "
                f"one of {valid_class_aggregation_values}. "
                f"Received: class_aggregation={class_aggregation}"
            )
        if num_regressors < 0:
            raise ValueError(
                "Invalid value for argument `num_regressors`. "
                "Expected a value >= 0. "
                f"Received: num_regressors={num_regressors}"
            )
        self.class_aggregation = class_aggregation
        self.num_regressors = num_regressors
        self.num_samples = self.add_variable(
            shape=(),
            initializer=initializers.Zeros(),
            name="num_samples",
        )
        self._built = False

    def _build(self, y_true_shape, y_pred_shape):
        if len(y_pred_shape) != 2 or len(y_true_shape) != 2:
            raise ValueError(
                "R2Score expects 2D inputs with shape "
                "(batch_size, output_dim). Received input "
                f"shapes: y_pred.shape={y_pred_shape} and "
                f"y_true.shape={y_true_shape}."
            )
        if y_pred_shape[-1] is None or y_true_shape[-1] is None:
            raise ValueError(
                "R2Score expects 2D inputs with shape "
                "(batch_size, output_dim), with output_dim fully "
                "defined (not None). Received input "
                f"shapes: y_pred.shape={y_pred_shape} and "
                f"y_true.shape={y_true_shape}."
            )
        num_classes = y_pred_shape[-1]
        self.squared_sum = self.add_variable(
            name="squared_sum",
            shape=[num_classes],
            initializer=initializers.Zeros(),
        )
        self.sum = self.add_variable(
            name="sum",
            shape=[num_classes],
            initializer=initializers.Zeros(),
        )
        self.total_mse = self.add_variable(
            name="residual",
            shape=[num_classes],
            initializer=initializers.Zeros(),
        )
        self.count = self.add_variable(
            name="count",
            shape=[num_classes],
            initializer=initializers.Zeros(),
        )
        self._built = True

    def update_state(self, y_true, y_pred, sample_weight=None):
        
        y_true = ops.convert_to_tensor(y_true, dtype=self._dtype)
        y_pred = ops.convert_to_tensor(y_pred, dtype=self._dtype)
        y_true, y_pred = squeeze_to_same_rank(y_true, y_pred)
        if not self._built:
            self._build(y_true.shape, y_pred.shape)

        if sample_weight is None:
            sample_weight = 1

        sample_weight = ops.convert_to_tensor(sample_weight, dtype=self.dtype)

        if len(sample_weight.shape) == 1:
            
            sample_weight = ops.expand_dims(sample_weight, axis=1)

        sample_weight = ops.broadcast_to(sample_weight, ops.shape(y_true))

        weighted_y_true = y_true * ops.cast(sample_weight, y_true.dtype)
        self.sum.assign(self.sum + ops.sum(weighted_y_true, axis=0))
        self.squared_sum.assign(
            self.squared_sum + ops.sum(y_true * weighted_y_true, axis=0)
        )
        self.total_mse.assign(
            self.total_mse
            + ops.sum(
                (y_true - y_pred) ** 2 * ops.cast(sample_weight, y_true.dtype),
                axis=0,
            )
        )
        self.count.assign(self.count + ops.sum(sample_weight, axis=0))
        self.num_samples.assign(self.num_samples + ops.size(y_true))

    def result(self):
        mean = self.sum / self.count
        total = self.squared_sum - self.sum * mean
        raw_scores = 1 - (self.total_mse / total)
        raw_scores = ops.where(ops.isinf(raw_scores), 0.0, raw_scores)

        if self.class_aggregation == "uniform_average":
            r2_score = ops.mean(raw_scores)
        elif self.class_aggregation == "variance_weighted_average":
            weighted_sum = ops.sum(total * raw_scores)
            sum_of_weights = ops.sum(total)
            r2_score = weighted_sum / sum_of_weights
        else:
            r2_score = raw_scores

        if self.num_regressors != 0:
            if self.num_regressors > self.num_samples - 1:
                warnings.warn(
                    "More independent predictors than datapoints "
                    "in adjusted R2 score. Falling back to standard R2 score.",
                    stacklevel=2,
                )
            elif self.num_regressors == self.num_samples - 1:
                warnings.warn(
                    "Division by zero in Adjusted R2 score. "
                    "Falling back to standard R2 score.",
                    stacklevel=2,
                )
            else:
                n = ops.convert_to_tensor(self.num_samples, dtype="float32")
                p = ops.convert_to_tensor(self.num_regressors, dtype="float32")
                num = ops.multiply(
                    ops.subtract(1.0, r2_score), ops.subtract(n, 1.0)
                )
                den = ops.subtract(ops.subtract(n, p), 1.0)
                r2_score = ops.subtract(1.0, ops.divide(num, den))
        return r2_score

    def reset_state(self):
        for v in self.variables:
            v.assign(ops.zeros(v.shape, dtype=v.dtype))

    def get_config(self):
        config = {
            "name": self.name,
            "dtype": self.dtype,
            "class_aggregation": self.class_aggregation,
            "num_regressors": self.num_regressors,
        }
        base_config = super().get_config()
        return {**base_config, **config}


def cosine_similarity(y_true, y_pred, axis=-1):
    
    y_pred = ops.convert_to_tensor(y_pred)
    y_true = ops.convert_to_tensor(y_true, dtype=y_pred.dtype)
    y_true, y_pred = squeeze_to_same_rank(y_true, y_pred)
    y_pred = normalize(y_pred, axis=axis)
    y_true = normalize(y_true, axis=axis)
    return ops.sum(y_true * y_pred, axis=axis)