Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Implement Binary Focal Loss Gradients

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Implement Binary Focal Loss Gradients. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Implement binary focal loss for logits and its gradient with respect to each logit. Given a list of real-valued logits logits, binary labels labels in {0,1}, focusing parameter gamma, balancing factor alpha, and reduction mode ("none", "sum", or "mean"), return both the forward loss and the backward gradient vector. Use a numerically stable sigmoid/log-sigmoid formulation.

Constraints

  • 1 <= len(logits) == len(labels) <= 10^5
  • labels[i] is either 0 or 1
  • 0 <= alpha <= 1
  • 0 <= gamma <= 5
  • reduction is one of "none", "sum", or "mean"

Function Signature

def focal_loss_with_grad(logits, labels, alpha, gamma, reduction):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output