|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | +import torch.nn.functional as F |
| 4 | + |
| 5 | + |
| 6 | +# from https://github.com/itakurah/Focal-loss-PyTorch |
| 7 | + |
| 8 | + |
| 9 | +class FocalLoss(nn.Module): |
| 10 | + def __init__( |
| 11 | + self, |
| 12 | + gamma=2, |
| 13 | + alpha=None, |
| 14 | + reduction="mean", |
| 15 | + task_type="binary", |
| 16 | + num_classes=None, |
| 17 | + ): |
| 18 | + """ |
| 19 | + Unified Focal Loss class for binary, multi-class, and multi-label classification tasks. |
| 20 | + :param gamma: Focusing parameter, controls the strength of the modulating factor (1 - p_t)^gamma |
| 21 | + :param alpha: Balancing factor, can be a scalar or a tensor for class-wise weights. If None, no class balancing is used. |
| 22 | + :param reduction: Specifies the reduction method: 'none' | 'mean' | 'sum' |
| 23 | + :param task_type: Specifies the type of task: 'binary', 'multi-class', or 'multi-label' |
| 24 | + :param num_classes: Number of classes (only required for multi-class classification) |
| 25 | + """ |
| 26 | + super(FocalLoss, self).__init__() |
| 27 | + self.gamma = gamma |
| 28 | + self.alpha = alpha |
| 29 | + self.reduction = reduction |
| 30 | + self.task_type = task_type |
| 31 | + self.num_classes = num_classes |
| 32 | + |
| 33 | + # Handle alpha for class balancing in multi-class tasks |
| 34 | + if ( |
| 35 | + task_type == "multi-class" |
| 36 | + and alpha is not None |
| 37 | + and isinstance(alpha, (list, torch.Tensor)) |
| 38 | + ): |
| 39 | + assert ( |
| 40 | + num_classes is not None |
| 41 | + ), "num_classes must be specified for multi-class classification" |
| 42 | + if isinstance(alpha, list): |
| 43 | + self.alpha = torch.Tensor(alpha) |
| 44 | + else: |
| 45 | + self.alpha = alpha |
| 46 | + |
| 47 | + def forward(self, inputs, targets): |
| 48 | + """ |
| 49 | + Forward pass to compute the Focal Loss based on the specified task type. |
| 50 | + :param inputs: Predictions (logits) from the model. |
| 51 | + Shape: |
| 52 | + - binary/multi-label: (batch_size, num_classes) |
| 53 | + - multi-class: (batch_size, num_classes) |
| 54 | + :param targets: Ground truth labels. |
| 55 | + Shape: |
| 56 | + - binary: (batch_size,) |
| 57 | + - multi-label: (batch_size, num_classes) |
| 58 | + - multi-class: (batch_size,) |
| 59 | + """ |
| 60 | + if self.task_type == "binary": |
| 61 | + return self.binary_focal_loss(inputs, targets) |
| 62 | + elif self.task_type == "multi-class": |
| 63 | + return self.multi_class_focal_loss(inputs, targets) |
| 64 | + elif self.task_type == "multi-label": |
| 65 | + return self.multi_label_focal_loss(inputs, targets) |
| 66 | + else: |
| 67 | + raise ValueError( |
| 68 | + f"Unsupported task_type '{self.task_type}'. Use 'binary', 'multi-class', or 'multi-label'." |
| 69 | + ) |
| 70 | + |
| 71 | + def binary_focal_loss(self, inputs, targets): |
| 72 | + """Focal loss for binary classification.""" |
| 73 | + probs = torch.sigmoid(inputs) |
| 74 | + targets = targets.float() |
| 75 | + |
| 76 | + # Compute binary cross entropy |
| 77 | + bce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") |
| 78 | + |
| 79 | + # Compute focal weight |
| 80 | + p_t = probs * targets + (1 - probs) * (1 - targets) |
| 81 | + focal_weight = (1 - p_t) ** self.gamma |
| 82 | + |
| 83 | + # Apply alpha if provided |
| 84 | + if self.alpha is not None: |
| 85 | + alpha_t = self.alpha * targets + (1 - self.alpha) * (1 - targets) |
| 86 | + bce_loss = alpha_t * bce_loss |
| 87 | + |
| 88 | + # Apply focal loss weighting |
| 89 | + loss = focal_weight * bce_loss |
| 90 | + |
| 91 | + if self.reduction == "mean": |
| 92 | + return loss.mean() |
| 93 | + elif self.reduction == "sum": |
| 94 | + return loss.sum() |
| 95 | + return loss |
| 96 | + |
| 97 | + def multi_class_focal_loss(self, inputs, targets): |
| 98 | + """Focal loss for multi-class classification.""" |
| 99 | + if self.alpha is not None: |
| 100 | + alpha = self.alpha.to(inputs.device) |
| 101 | + |
| 102 | + # Convert logits to probabilities with softmax |
| 103 | + probs = F.softmax(inputs, dim=1) |
| 104 | + |
| 105 | + # One-hot encode the targets |
| 106 | + targets_one_hot = F.one_hot(targets, num_classes=self.num_classes).float() |
| 107 | + |
| 108 | + # Compute cross-entropy for each class |
| 109 | + ce_loss = -targets_one_hot * torch.log(probs) |
| 110 | + |
| 111 | + # Compute focal weight |
| 112 | + p_t = torch.sum(probs * targets_one_hot, dim=1) # p_t for each sample |
| 113 | + focal_weight = (1 - p_t) ** self.gamma |
| 114 | + |
| 115 | + # Apply alpha if provided (per-class weighting) |
| 116 | + if self.alpha is not None: |
| 117 | + alpha_t = alpha.gather(0, targets) |
| 118 | + ce_loss = alpha_t.unsqueeze(1) * ce_loss |
| 119 | + |
| 120 | + # Apply focal loss weight |
| 121 | + loss = focal_weight.unsqueeze(1) * ce_loss |
| 122 | + |
| 123 | + if self.reduction == "mean": |
| 124 | + return loss.mean() |
| 125 | + elif self.reduction == "sum": |
| 126 | + return loss.sum() |
| 127 | + return loss |
| 128 | + |
| 129 | + def multi_label_focal_loss(self, inputs, targets): |
| 130 | + """Focal loss for multi-label classification.""" |
| 131 | + probs = torch.sigmoid(inputs) |
| 132 | + |
| 133 | + # Compute binary cross entropy |
| 134 | + bce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none") |
| 135 | + |
| 136 | + # Compute focal weight |
| 137 | + p_t = probs * targets + (1 - probs) * (1 - targets) |
| 138 | + focal_weight = (1 - p_t) ** self.gamma |
| 139 | + |
| 140 | + # Apply alpha if provided |
| 141 | + if self.alpha is not None: |
| 142 | + alpha_t = self.alpha * targets + (1 - self.alpha) * (1 - targets) |
| 143 | + bce_loss = alpha_t * bce_loss |
| 144 | + |
| 145 | + # Apply focal loss weight |
| 146 | + loss = focal_weight * bce_loss |
| 147 | + |
| 148 | + if self.reduction == "mean": |
| 149 | + return loss.mean() |
| 150 | + elif self.reduction == "sum": |
| 151 | + return loss.sum() |
| 152 | + return loss |
0 commit comments