Implementation:Kornia Kornia Charbonnier Loss
| Knowledge Sources | |
|---|---|
| Domains | Vision, Loss_Functions |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Charbonnier Loss (also known as L1-L2 loss) is a differentiable approximation of the L1 loss that provides smooth gradients near zero.
Description
The Charbonnier loss, also known as the pseudo-Huber loss or L1-L2 loss, is a smooth approximation of L1 loss that is differentiable everywhere, including at zero. It combines the properties of both L1 and L2 losses: it behaves like L2 for small residuals (providing smooth gradients) and like L1 for large residuals (providing robustness to outliers).
The mathematical formulation following Barron (2019) is:
Where is the prediction and is the target. The loss is always non-negative and provides a smooth transition between quadratic and linear behavior.
Usage
Import this loss for image restoration tasks such as super-resolution, denoising, and deblurring where you want a robust loss that provides smooth gradients. It is commonly used as an alternative to L1 loss in training deep neural networks for pixel-level regression.
Code Reference
Source Location
- Repository: Kornia
- File: kornia/losses/charbonnier.py
- Lines: 1-145
Signature
def charbonnier_loss(
img1: torch.Tensor,
img2: torch.Tensor,
reduction: str = "none",
) -> torch.Tensor: ...
class CharbonnierLoss(nn.Module):
def __init__(self, reduction: str = "none") -> None: ...
def forward(self, img1: torch.Tensor, img2: torch.Tensor) -> torch.Tensor: ...
Import
from kornia.losses import CharbonnierLoss
from kornia.losses import charbonnier_loss
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| img1 | torch.Tensor | Yes | Predicted tensor with arbitrary shape (*) |
| img2 | torch.Tensor | Yes | Target tensor with the same shape as img1 |
| reduction | str | No | Reduction mode: 'none' (default), 'mean', or 'sum' |
Outputs
| Name | Type | Description |
|---|---|---|
| loss | torch.Tensor | Computed Charbonnier loss; element-wise for 'none', scalar for 'mean'/'sum' |
Usage Examples
import torch
from kornia.losses import CharbonnierLoss
# Create sample tensors
img1 = torch.randn(2, 3, 32, 32, requires_grad=True)
img2 = torch.randn(2, 3, 32, 32)
# Using the module API
criterion = CharbonnierLoss(reduction="mean")
output = criterion(img1, img2)
output.backward()
# Using the functional API
from kornia.losses import charbonnier_loss
output = charbonnier_loss(img1, img2, reduction="sum")