PyTorch torch.nn.HuberLoss function
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:
delta: transition point; beyond this value MAE is usedreduction: aggregation mode
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
)
(
"Huber Loss:"
,
loss.
item
(
)
)
Comparing with MSE
mse
=
nn.
MSELoss
(
)
(
pred
,
target
)
(
"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
(
)
(
"Training loss:"
,
loss.
item
(
)
)
Use Cases
- Regression tasks: data with outliers
- Object detection: bounding box regression
- Robust training: noisy data