BinaryFocalLoss#
- class BinaryFocalLoss(gamma=2.0, alpha=0.5, logits=True, reduce=True, loss_weight=1.0, weight=None)[source]#
Bases:
ModuleBinary focal loss for class-imbalanced binary targets.
Focal loss (Lin et al. 2017) for a single binary output.
forward(pred, target)expectspredandtargetof matching shape(N,)(or broadcastable);predis treated as logits whenlogitsisTrue, else as probabilities. Returns the (optionally mean-reduced) loss scaled byloss_weight. Registered asBinaryFocalLoss– use in acriteria=[...]list.- Parameters:
gamma (float) – Focusing exponent that down-weights easy examples. Defaults to
2.0.alpha (float) – Positive-class weight in
(0, 1). Defaults to0.5.logits (bool) – Whether
predis raw logits (vs probabilities). Defaults toTrue.reduce (bool) – Mean-reduce the per-element loss when
True. Defaults toTrue.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.