Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Custom Loss Function in Python
00:00
5 left

Custom Loss Function in Python

HardPython

Problem

Rakuten Payment may use binary classifiers for payment-risk decisions where positive events are rare. Implement a numerically stable binary focal loss from scratch, including the gradient with respect to every logit.

Given a list of real-valued logits and binary labels, compute the mean focal loss and its gradient. Apply class weighting, focusing parameter gamma, and optional label smoothing.

For each label y, define the smoothed target as t = y * (1 - label_smoothing) + 0.5 * label_smoothing. Let p = sigmoid(logit). The per-example loss is:

-alpha * t * (1 - p)^gamma * log(p) - (1 - alpha) * (1 - t) * p^gamma * log(1 - p)

Return a dictionary with loss, the mean loss, and gradients, a list containing the derivative of the mean loss with respect to each input logit. Do not use NumPy, automatic differentiation, or machine-learning libraries.

Constraints

  • 1 <= len(logits) = len(labels) <= 100000
  • Every label is either 0 or 1
  • -1000 <= logits[i] <= 1000
  • 0 < alpha < 1
  • 0 <= gamma <= 5
  • 0 <= label_smoothing < 1
  • Use stable expressions for logarithms and sigmoid calculations

Function Signature

def custom_focal_loss(logits, labels, alpha, gamma, label_smoothing):
Interviewer

Your question is Custom Loss Function in Python. Start with the requirements in the Question tab.

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.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.