Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions cbloss/loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,21 @@ class FocalLoss(nn.Module):
Focal loss value.
"""

def __init__(self, num_classes, alpha=1, gamma=2, reduction="mean"):
def __init__(self, num_classes, alpha=1, gamma=2, reduction="mean", **kwargs):
super(FocalLoss, self).__init__()
self.num_classes = num_classes
self.alpha = alpha
self.gamma = gamma
self.reduction = reduction
self.kwargs = kwargs

def forward(self, outputs, targets):
if self.num_classes == 2:
# binary classification problem
ce_loss = F.binary_cross_entropy_with_logits(outputs, targets.float(), reduction="none")
ce_loss = F.binary_cross_entropy_with_logits(outputs, targets.float(), reduction="none", **self.kwargs)
elif self.num_classes > 2:
# multi-class classification problem
ce_loss = F.cross_entropy(outputs, targets, reduction="none")
ce_loss = F.cross_entropy(outputs, targets, reduction="none", **self.kwargs)
else:
raise ValueError(f"Invalid input value : {self.num_classes}. It should be equal or greater than 2.")

Expand Down