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

PyTorch torch.nn.HuberLoss function

PyTorch torch.nn.HuberLoss function

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


torch.nn.HuberLoss is the Huber loss function in PyTorch.

It combines MSE and MAE, being robust to outliers and having stable gradients.

Function definition



torch.nn.HuberLoss(delta=1.0, reduction='mean')

Parameters:

Mathematical principle



L(y, ŷ) = 0.5 * (y - ŷ)², if |y - ŷ| ≤ δ

L(y, ŷ) = δ * |y - ŷ| - 0.5 * δ², if |y - ŷ| > δ


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

criterion

=

nn.

HuberLoss

(

delta

=

1.0

)

pred

=

torch.

tensor

(

[

1.0

,

2.0

,

3.0

,

10.0

]

)

target

=

torch.

tensor

(

[

1.5

,

2.5

,

3.5

,

8.0

]

)

loss

=

criterion

(

pred

,

target

)

print

(

"Huber Loss:"

,

loss.

item

(

)

)

Comparing with MSE

mse

=

nn.

MSELoss

(

)

(

pred

,

target

)

print

(

"MSE Loss:"

,

mse.

item

(

)

)

Example 2: Regression training

Example

import

torch

import

torch.

nn

as

nn

model

=

nn.

Linear

(

10

,

1

)

criterion

=

nn.

HuberLoss

(

)

optimizer

=

torch.

optim

.

Adam

(

model.

parameters

(

)

)

Training

X

=

torch.

randn

(

100

,

10

)

y

=

torch.

randn

(

100

,

1

)

model.

train

(

)

optimizer.

zero_grad

(

)

output

=

model

(

X

)

loss

=

criterion

(

output

,

y

)

loss.

backward

(

)

optimizer.

step

(

)

print

(

"Training loss:"

,

loss.

item

(

)

)


Use Cases


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