L1Loss — PyTorch 2.7 documentation (original) (raw)

class torch.nn.L1Loss(size_average=None, reduce=None, reduction='mean')[source][source]

Creates a criterion that measures the mean absolute error (MAE) between each element in the input xx and target yy.

The unreduced (i.e. with reduction set to 'none') loss can be described as:

ℓ(x,y)=L={l1,…,lN}⊤,ln=∣xn−yn∣,\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad l_n = \left| x_n - y_n \right|,

where NN is the batch size. If reduction is not 'none'(default 'mean'), then:

ℓ(x,y)={mean⁡(L),if reduction=‘mean’;sum⁡(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}

xx and yy are tensors of arbitrary shapes with a total of NN elements each.

The sum operation still operates over all the elements, and divides by NN.

The division by NN can be avoided if one sets reduction = 'sum'.

Supports real-valued and complex-valued inputs.

Parameters

Shape:

Examples:

loss = nn.L1Loss() input = torch.randn(3, 5, requires_grad=True) target = torch.randn(3, 5) output = loss(input, target) output.backward()