Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.L1Loss function

PyTorch torch.nn.L1Loss function

PyTorch torch.nn Reference Manual 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

)

print

(

"L1 Loss:"

,

loss.

item

(

)

)

Manual verification

manual

=

(

pred - target

)

.

abs

(

)

.

mean

(

)

print

(

"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

]

)

print

(

"L1 Loss (robust to outliers):"

,

nn.

L1Loss

(

)

(

pred

,

target

)

.

item

(

)

)

print

(

"MSE Loss (sensitive to outliers):"

,

nn.

MSELoss

(

)

(

pred

,

target

)

.

item

(

)

)


Use Cases


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual