Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Custom Loss Without Deep Libraries

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

Your question is Custom Loss Without Deep Libraries. 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

Optum Insight model evaluation pipelines may need a lightweight loss calculation when a deep learning framework is unavailable. Implement a custom weighted binary cross-entropy loss directly in Python, using raw logits and returning the gradient for every example.

Formal Specification

Write weighted_logistic_loss(logits, labels, weights), where:

  1. logits is a list of real-valued model outputs.
  2. labels is a list containing only 0 or 1.
  3. weights is a list of nonnegative example weights.
  4. All three lists have the same positive length, and the sum of weights is positive.

For each example, compute the numerically stable binary cross-entropy from the logit z:

max(z, 0) - z * y + log(1 + exp(-abs(z)))

Return a dictionary with:

  • loss: the weighted mean loss, divided by the sum of all weights.
  • gradients: a list where each value is weight / sum(weights) * (sigmoid(logit) - label).

Do not use NumPy, PyTorch, TensorFlow, or other external libraries. The implementation must remain stable for very large positive or negative logits.

Constraints

  • 1 <= len(logits) <= 10^5
  • len(logits) == len(labels) == len(weights)
  • -10^6 <= logits[i] <= 10^6
  • labels[i] is either 0 or 1
  • weights[i] >= 0
  • sum(weights) > 0

Function Signature

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