class

L1Loss

extendsModule
L1Loss(reduction: str = 'mean')
source

Mean absolute error (MAE) loss between each element of the prediction and the target.

Also known as the L1 loss, this criterion computes the element-wise absolute difference and optionally reduces it:

L(x,y)=1ni=1nxiyi\mathcal{L}(x, y) = \frac{1}{n} \sum_{i=1}^{n} |x_i - y_i|

With reduction='sum' the sum is taken instead, and with reduction='none' the full element-wise tensor is returned.

Parameters

reductionstr= 'mean'
Specifies the reduction applied to the output. 'none' — no reduction, element-wise output. 'mean' — average over all elements (default). 'sum' — sum over all elements.

Attributes

reductionstr
The reduction mode set at construction time.

Notes

  • Input x : ()(*) — any shape.
  • Target y : ()(*) — same shape as x.
  • Output : scalar when reduction is 'mean' or 'sum'; ()(*) when reduction='none'.
  • Unlike MSELoss, gradients are constant in magnitude (the subgradient is ±1), making L1 loss more robust to outliers.
  • The non-differentiability at zero can cause numerical instability near convergence for some optimisers; SmoothL1Loss provides a twice-differentiable alternative.
  • L1 loss is proportional to the negative log-likelihood under a Laplace (double-exponential) observation model.

Examples

Scalar regression:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.L1Loss()
>>> x = lucid.tensor([2.5, 0.0, 2.0, 8.0])
>>> y = lucid.tensor([3.0, -0.5, 2.0, 7.0])
>>> loss = criterion(x, y)  # scalar ≈ 0.5
Comparing element-wise residuals:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.L1Loss(reduction="none")
>>> x = lucid.tensor([[1.0, 3.0], [0.0, -1.0]])
>>> y = lucid.tensor([[2.0, 1.0], [0.0,  1.0]])
>>> loss = criterion(x, y)  # shape (2, 2): [[1., 2.], [0., 2.]]

Methods (3)

dunder

__init__

None
__init__(reduction: str = 'mean')
source

Initialise the L1Loss module. See the class docstring for parameter semantics.

fn

forward

Tensor
forward(x: Tensor, target: Tensor)
source

Compute the loss between predictions and targets.

Parameters

xTensor
Input tensor.
targetTensor
Input tensor.

Returns

Tensor

Scalar loss (or unreduced tensor depending on reduction).

fn

extra_repr

str
extra_repr()
source

Return a string representation of the layer's configuration.