Regression training
Train a model to predict continuous numeric targets.
Keras · Class
MeanSquaredError is a Keras regression loss that averages squared differences between targets and predictions. Its instance-level reduction controls whether those per-sample values are averaged, summed, weighted, or left unaggregated.
When called with target values and predictions, the loss squares their element-wise differences and averages across the last dimension to produce per-sample losses. The loss object then aggregates those values according to reduction; by default, it averages them over the batch.
keras.losses.MeanSquaredError(reduction="sum_over_batch_size", name="mean_squared_error", dtype=None)| Name | Type | Description |
|---|---|---|
reduction | string or None | Reduction mode for combining per-sample losses; supported values include "sum", "sum_over_batch_size", "mean", "mean_with_sample_weight", and None. |
name | string | Optional identifier for the loss instance. |
dtype | string or None | Numeric dtype used for loss computations; omitted means Keras uses its configured float type. |
A callable loss object that produces per-sample mean-squared-error values and aggregates them according to reduction.
import keras
model = keras.Sequential([
keras.layers.Input(shape=(1,)),
keras.layers.Dense(1),
])
model.compile(
optimizer="adam",
loss=keras.losses.MeanSquaredError(),
)
Creates a regression model and uses MeanSquaredError as its training loss.
Train a model to predict continuous numeric targets.
Use a loss object with Keras's model compilation API.
Inspect individual example losses for custom aggregation or diagnostics.
It computes the mean of the squared differences between labels and predictions. The per-sample calculation averages over the last dimension, and the class then applies its configured reduction.
Follow-up: How would you preserve every per-sample value? Set reduction to None, which performs no aggregation.
The default is "sum_over_batch_size". It sums per-sample losses and divides by the sample size, yielding an average over the batch.
Follow-up: What does "sum" do instead? It returns the sum of the per-sample losses without dividing by batch size.
The constructor accepts reduction, name, and dtype. dtype controls the computation type and defaults to Keras's configured floating-point type when omitted.
Follow-up: How can sample weights affect reduction? With "mean_with_sample_weight", the loss is divided by the sum of sample weights.
keras.losses.mean_squared_errorkeras.losses.MeanAbsoluteErrorkeras.losses.MeanSquaredLogarithmicErrorkeras.losses.Huber