class
L1Loss
extends
ModuleL1Loss(reduction: str = 'mean')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:
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
reductionstrThe reduction mode set at construction time.
Notes
- Input
x: — any shape. - Target
y: — same shape asx. - Output : scalar when
reductionis'mean'or'sum'; whenreduction='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;
SmoothL1Lossprovides 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')Initialise the L1Loss module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(x: Tensor, target: Tensor)Compute the loss between predictions and targets.
Parameters
xTensorInput tensor.
targetTensorInput tensor.
Returns
TensorScalar loss (or unreduced tensor depending on reduction).
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.