Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Focal Loss Implementation

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

Your question is Focal Loss Implementation. 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 focal loss.

Asked in the First Round Interview stage. Coding section instead of expected LeetCode style algorithmic problems.

Implement focal_loss(logits, targets, alpha, gamma). Inputs are equal-length arrays of binary classification logits and labels, where each label is 0 or 1. Use alpha for positive examples and 1 - alpha for negative examples. Return the mean binary focal loss as a float:

-alpha_t * (1 - p_t) ** gamma * log(p_t)

Compute the expression stably from logits rather than relying on probabilities that may underflow or overflow.

Constraints

  • 1 <= len(logits) == len(targets) <= 1000
  • Each target is either 0 or 1
  • 0 < alpha < 1
  • gamma >= 0
  • All logits are finite real numbers

Function Signature

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