SoftmaxFocalLoss¶
Multiclass focal loss with softmax, for mutually-exclusive classification. Supports per-class alpha weighting, mean_positive reduction (RetinaNet convention), label smoothing, and arbitrary input shapes.
imbalanced_losses.focal_loss.SoftmaxFocalLoss
¶
Bases: Module
Softmax Focal Loss for mutually-exclusive multiclass classification.
Generalises focal loss from the binary sigmoid case to C classes using
softmax probabilities and standard cross-entropy as the base loss.
Supports optional DDP all-gather so that positive-count-based
normalisations (mean_positive) reflect the global batch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
alpha
|
Tensor or list[float] or None
|
Per-class weighting factors of shape (C,). Typically set to the
inverse class frequency or similar. |
None
|
gamma
|
float
|
Focusing exponent. |
2.0
|
reduction
|
str
|
'none' | 'mean' | 'mean_positive' | 'sum'. Default: 'mean'.
|
'mean'
|
label_smoothing
|
float
|
Label-smoothing epsilon forwarded to |
0.0
|
ignore_index
|
int
|
Class index to ignore (passed through to |
-100
|
background_class
|
int
|
Class index treated as background/negative for the
|
0
|
gather_distributed
|
bool or None
|
Whether to all-gather inputs and targets across DDP workers before
computing the loss. |
None
|
Notes
In DDP, mean_positive normalization is most affected by gathering: if
positives are rare and unevenly distributed across ranks, the local
positive count is noisy. Gathering ensures the denominator reflects the
true global positive count.
Source code in src/imbalanced_losses/focal_loss.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
forward(inputs, targets)
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Tensor
|
Raw logits of shape |
required |
targets
|
Tensor
|
Integer class labels of shape |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Scalar or per-sample loss depending on |
Source code in src/imbalanced_losses/focal_loss.py
Quick examples¶
Standard multiclass¶
from imbalanced_losses import SoftmaxFocalLoss
import torch
loss_fn = SoftmaxFocalLoss(gamma=2.0, reduction="mean")
logits = torch.randn(32, 10)
targets = torch.randint(0, 10, (32,))
loss = loss_fn(logits, targets)
loss.backward()
RetinaNet-style detection¶
loss_fn = SoftmaxFocalLoss(
gamma=2.0,
alpha=[0.25] * 10, # per-class weights
reduction="mean_positive", # normalize by foreground count
background_class=0,
ignore_index=-100,
)
loss = loss_fn(logits, targets)
Dense prediction (spatial inputs)¶
# [N, C, H, W] logits, [N, H, W] targets
logits = torch.randn(4, 10, 64, 64)
targets = torch.randint(0, 10, (4, 64, 64))
loss = loss_fn(logits, targets)
Parameter guidance¶
| Parameter | Default | Notes |
|---|---|---|
alpha |
None |
Per-class 1-D tensor or list; None disables class weighting |
gamma |
2.0 |
Higher = harder focus; 0 = vanilla cross-entropy |
reduction |
"mean" |
"mean_positive" normalizes by foreground count (detection tasks) |
background_class |
0 |
Class excluded from mean_positive denominator |
ignore_index |
-100 |
Padded positions — zero loss, zero gradient |
label_smoothing |
0.0 |
Forwarded to F.cross_entropy |
mean_positive reduction semantics¶
- Numerator: sum of loss over all valid (non-ignored) positions, including background
- Denominator: count of non-background, non-ignored positions only
- This matches the original RetinaNet implementation and stabilizes loss scale when positives are rare