Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Kornia Kornia Lovasz Hinge Loss

From Leeroopedia


Knowledge Sources
Domains Vision, Loss_Functions
Last Updated 2026-02-09 15:00 GMT

Overview

Lovasz Hinge Loss computes a surrogate binary intersection-over-union (IoU) loss using the Lovasz extension, providing a differentiable approximation for direct IoU optimization.

Description

The Lovasz Hinge loss is a surrogate loss for the binary intersection-over-union (IoU) metric, based on the Lovasz extension of submodular set functions (Yu and Blaschko, 2015; Berman et al., 2018). The IoU is computed as:

IoU(X,Y)=|XY||XY|

The Lovasz extension provides a tight convex surrogate that is fully differentiable, allowing direct optimization of the IoU metric during training.

The loss is computed by sorting prediction errors, computing the Lovasz gradient (the discrete derivative of the IoU w.r.t. the sorted errors), and performing a weighted sum of the rectified errors.

Note: This loss function only supports binary labels (single channel). For multi-class labels, use the Lovasz-Softmax loss.

Usage

Import this loss for binary segmentation tasks where you want to directly optimize the IoU metric. It is particularly effective when combined with cross-entropy loss and is widely used in competitions and practical segmentation systems.

Code Reference

Source Location

Signature

def lovasz_hinge_loss(
    pred: Tensor,
    target: Tensor,
) -> Tensor: ...

class LovaszHingeLoss(nn.Module):
    def __init__(self) -> None: ...
    def forward(self, pred: Tensor, target: Tensor) -> Tensor: ...

Import

from kornia.losses import LovaszHingeLoss
from kornia.losses import lovasz_hinge_loss

I/O Contract

Inputs

Name Type Required Description
pred torch.Tensor Yes Logits tensor with shape (N, 1, H, W)
target torch.Tensor Yes Labels tensor with shape (N, H, W) with binary values (0 or 1)

Outputs

Name Type Description
loss torch.Tensor Scalar loss value representing the mean Lovasz hinge loss across the batch

Usage Examples

import torch
from kornia.losses import LovaszHingeLoss

# Binary segmentation
N = 1  # single channel for binary
pred = torch.randn(1, N, 3, 5, requires_grad=True)
target = torch.empty(1, 3, 5, dtype=torch.long).random_(N)

# Using the module API
criterion = LovaszHingeLoss()
output = criterion(pred, target)
output.backward()

# Using the functional API
from kornia.losses import lovasz_hinge_loss
output = lovasz_hinge_loss(pred, target)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment