PyTorch torch.nn.L1Loss function
PyTorch torch.nn Reference Manual
torch.nn.L1Loss is the L1 loss function in PyTorch, also known as mean absolute error (MAE).
Function definition
torch.nn.L1Loss(reduction='mean')
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
criterion
=
nn.
L1Loss
(
)
pred
=
torch.
tensor
(
[
3.0
,
4.0
,
5.0
]
)
target
=
torch.
tensor
(
[
2.0
,
4.5
,
5.5
]
)
loss
=
criterion
(
pred
,
target
)
(
"L1 Loss:"
,
loss.
item
(
)
)
Manual verification
manual
=
(
pred - target
)
.
abs
(
)
.
mean
(
)
(
"Manual calculation:"
,
manual.
item
(
)
)
Example 2: Comparing with MSE
Example
import
torch
import
torch.
nn
as
nn
pred
=
torch.
tensor
(
[
10.0
,
20.0
]
)
target
=
torch.
tensor
(
[
0.0
,
0.0
]
)
(
"L1 Loss (robust to outliers):"
,
nn.
L1Loss
(
)
(
pred
,
target
)
.
item
(
)
)
(
"MSE Loss (sensitive to outliers):"
,
nn.
MSELoss
(
)
(
pred
,
target
)
.
item
(
)
)
Use Cases
- Regression tasks: when robustness is needed
- Outliers: noisy data
- L1 regularization: sparsification