Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wessam611 focal loss kwargs (#1) #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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