FocalLoss#
- class FocalLoss(weight: Tensor | None = None, size_average: bool | None = None, reduce: bool | None = None, reduction: str = 'mean', gamma: float = 2, ignore_index: int = -1, loss_weight: float = 1.0, penalize_pred: bool = False)[source]#
Bases:
_WeightedLossMulti-class focal loss over per-point class logits.
Focal loss (Lin et al. 2017) for multi-class classification.
forward(pred, target)flattenspredto(N, C)(logits) andtargetto(N,)(class indices), applies the(1 - p_t) ** gammafocal modulation on top of cross-entropy, and reduces over non-ignored points. The optional classweightis indexed by the ground-truth label whenpenalize_predisTrue, otherwise by the predicted (argmax) label. Returns the loss scaled byloss_weight. Registered asFocalLoss– use in acriteria=[...]list.- Parameters:
weight (torch.Tensor | None) – Per-class rescaling weights. Defaults to
None.size_average (bool | None) – Deprecated torch reduction flag. Defaults to
None.reduce (bool | None) – Deprecated torch reduction flag. Defaults to
None.reduction (str) – Reduction mode (
"mean","sum","none"); the"mean"path divides by the count of non-ignored targets. Defaults to"mean".gamma (float) – Focusing exponent that down-weights easy examples. Defaults to
2.ignore_index (int) – Target value excluded from the loss. Defaults to
-1.loss_weight (float) – Global scale on the returned loss. Defaults to
1.0.penalize_pred (bool) – Index the class
weightby the ground-truth label instead of the predicted label. Defaults toFalse.
Example
>>> import torch >>> from pimm.models.losses.builder import build_criteria >>> crit = build_criteria([dict(type="FocalLoss", gamma=2.0, loss_weight=1.0)]) >>> pred = torch.randn(4, 3) # (N=4 points, C=3 classes) logits >>> target = torch.tensor([0, 2, 1, -1]) # -1 is ignored >>> crit(pred, target) # scalar loss tensor(0.9830)