Optimize continuous predictions with a squared-error objective.
Regression training
TensorFlow · Class
Computes the average squared difference between labels and predictions. It is a configurable Keras Loss object with selectable reduction behavior.
The loss compares corresponding values in the labels and predictions, squares their differences, and averages the resulting errors. Calling the object invokes the inherited loss interface; the configured reduction controls how per-example losses are aggregated.
tf.keras.losses.MeanSquaredError(
reduction='sum_over_batch_size',
name='mean_squared_error'
)| Name | Type | Description |
|---|---|---|
reduction | str or None | Type of reduction to apply to the loss. Supported values are "sum", "sum_over_batch_size", or None. |
name | str | Optional name for the loss instance. |
A loss value computed from the labels and predictions; its aggregation is controlled by reduction.
Loss, the class fits Keras loss APIs and can be configured as a model objective.mean_squared_error.call method.import tensorflow as tf
loss_fn = tf.keras.losses.MeanSquaredError()
y_true = tf.constant([[1.0, 2.0], [3.0, 4.0]])
y_pred = tf.constant([[1.5, 1.0], [2.0, 5.0]])
loss = loss_fn(y_true, y_pred)
print(float(loss))Creates the loss object and computes one scalar loss for two samples.
Regression training
Custom training loops
Loss serialization
It computes the mean of the squared differences between y_true and y_pred: mean(square(y_true - y_pred)). The class is a Loss, so it can be passed directly as a Keras model loss.
Follow-up: How would you change aggregation? Instantiate it with reduction='sum' or reduction=None, choosing deliberately because the reduction changes the returned loss structure and scale.
The constructor accepts reduction, which specifies the type of loss aggregation, and name, which identifies the loss instance. The documented default reduction is 'sum_over_batch_size'.
Follow-up: When might reduction=None be useful? It can preserve individual loss values instead of aggregating them, which is useful when later code needs per-example weighting or custom aggregation.
The callable interface accepts y_true, y_pred, and optional sample_weight. Calling the object computes the loss using the configured reduction, while get_config() exposes its serializable configuration.
Follow-up: Why use the callable object rather than only a standalone function? The object packages configuration such as reduction and name and integrates with Keras loss serialization and training APIs.
tf.keras.losses.Losstf.keras.losses.MeanAbsoluteErrortf.keras.losses.MeanSquaredLogarithmicErrortf.keras.losses.MSE