l2_loss

Contents

l2_loss#

class braintools.metric.l2_loss(predictions, targets=None, axis=None, reduction='none')#

Calculate the L2 loss for a set of predictions.

The L2 loss is half the squared error:

\[\text{L2 loss} = \frac{1}{2} (y - \hat{y})^2\]
Parameters:
  • predictions (Array | ndarray | bool | number | bool | int | float | complex | Quantity) – A vector of arbitrary shape [...].

  • targets (Array | ndarray | bool | number | bool | int | float | complex | Quantity | None) – A vector with the same shape as predictions (shape equality is asserted; no broadcasting). If not provided then it is assumed to be a vector of zeros.

  • axis (int | tuple[int, ...] | None) – Axis or axes along which to reduce when reduction is 'mean' or 'sum'. If None, reduction (if any) is over all elements.

  • reduction (str) –

    Reduction operation to apply:

    • 'none': return element-wise losses with the same shape as predictions (backward-compatible default),

    • 'mean': return the mean of the losses,

    • 'sum': return the sum of the losses.

Returns:

Element-wise squared differences scaled by 0.5 when reduction='none'; otherwise the reduced value.

Return type:

Array | ndarray | bool | number | bool | int | float | complex | Quantity

Notes

The 0.5 factor is standard in “Pattern Recognition and Machine Learning” [1] by Bishop, but not in “The Elements of Statistical Learning” by Tibshirani.

For brainunit.Quantity inputs the result carries squared units (e.g. mV inputs produce a mV ** 2 result), since the error is squared element-wise.

References

Examples

>>> import jax.numpy as jnp
>>> import braintools
>>> predictions = jnp.array([1.0, 2.0, 3.0])
>>> targets = jnp.array([1.5, 2.5, 2.0])
>>> braintools.metric.l2_loss(predictions, targets)
Array([0.125, 0.125, 0.5  ], dtype=float32)
>>> braintools.metric.l2_loss(predictions, targets, reduction='mean')
Array(0.25, dtype=float32)