Skip to content
fn

mse_loss

→Tensor
mse_loss(input: Tensor, target: Tensor, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean', weight: Tensor | None = None)

Implementing kernel

C++ engine symbols that back this Python API.

Mean-squared-error (L2) loss between input and target.

The workhorse loss for regression problems. Penalises large errors quadratically, which makes it sensitive to outliers but yields a well-conditioned optimisation surface — the gradient is linear in the residual, so SGD updates scale gracefully near the optimum. Compare with l1_loss (constant gradient, robust to outliers) and huber_loss (a smooth blend of the two).

Parameters

inputTensor
Predicted values, any shape.
targetTensor
Target values that broadcast with input. A target of another shape is broadcast with a UserWarning, as the reference does; one that does not broadcast raises ValueError.
reductionstr= 'mean'
"mean" (default), "sum", or "none".
size_averagestr= 'mean'
"mean" (default), "sum", or "none".
reducestr= 'mean'
"mean" (default), "sum", or "none".
weightTensor or None= None
Optional element-wise weight tensor of the same shape as input.

Returns

Tensor

Scalar loss for "mean" / "sum", or a per-element tensor of input and target's broadcast shape for "none".

Notes

Per-element loss:

Li=(xi−yi)2L_i = (x_i - y_i)^2

With reduction:

L={1N∑iLi"mean"∑iLi"sum"Li"none"L = \begin{cases} \tfrac{1}{N}\sum_i L_i & \text{"mean"} \\ \sum_i L_i & \text{"sum"} \\ L_i & \text{"none"} \end{cases}

The gradient w.r.t. input is 2(xi−yi)/N2(x_i - y_i) / N under "mean" reduction — proportional to the error, so updates naturally shrink near the optimum.

Examples

>>> import lucid
>>> from lucid.nn.functional import mse_loss
>>> pred = lucid.tensor([1.0, 2.0, 3.0])
>>> target = lucid.tensor([1.5, 2.5, 2.5])
>>> mse_loss(pred, target)
tensor(0.25)

Used by 2