BinaryFocalLoss#

class BinaryFocalLoss(gamma=2.0, alpha=0.5, logits=True, reduce=True, loss_weight=1.0, weight=None)[source]#

Bases: Module

Binary focal loss for class-imbalanced binary targets.

Focal loss (Lin et al. 2017) for a single binary output. forward(pred, target) expects pred and target of matching shape (N,) (or broadcastable); pred is treated as logits when logits is True, else as probabilities. Returns the (optionally mean-reduced) loss scaled by loss_weight. Registered as BinaryFocalLoss – use in a criteria=[...] list.

Parameters:
  • gamma (float) – Focusing exponent that down-weights easy examples. Defaults to 2.0.

  • alpha (float) – Positive-class weight in (0, 1). Defaults to 0.5.

  • logits (bool) – Whether pred is raw logits (vs probabilities). Defaults to True.

  • reduce (bool) – Mean-reduce the per-element loss when True. Defaults to True.

  • loss_weight (float) – Global scale on the returned loss. Defaults to 1.0.

  • weight (torch.Tensor | None) – Optional per-element BCE weight. Defaults to None.

Example

>>> import torch
>>> from pimm.models.losses.builder import build_criteria
>>> crit = build_criteria([dict(type="BinaryFocalLoss", gamma=2.0, alpha=0.5)])
>>> pred = torch.zeros(4)               # logits (p=0.5 for all)
>>> target = torch.tensor([0., 1., 0., 1.])
>>> crit(pred, target)                  # scalar loss
tensor(0.0866)
BinaryFocalLoss.forward(pred, target, **kwargs)[source]#

Forward function.

Parameters:
  • pred (torch.Tensor) – The prediction with shape (N).

  • target (torch.Tensor) – The ground truth. If containing class indices, shape (N) where each value is 0 <= target[i] <= 1; if containing class probabilities, same shape as the input.

Returns:

torch.Tensor – The calculated loss.