Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Custom Loss Function in PyTorch

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

Your question is Custom Loss Function in PyTorch. 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

Write a Python function to implement a custom loss function, such as Huber loss, using PyTorch or TensorFlow.

Implement def huber_loss(predictions, targets, delta, reduction): for equal-length numeric lists. Return element-wise losses for reduction="none", or a scalar for "mean" and "sum". For error e, use 0.5 * e² when |e| <= delta, otherwise delta * (|e| - 0.5 * delta). The reference solution uses standard Python operations so its behavior can be tested without a framework; the same logic should map directly to tensor operations.

Constraints

  • 1 <= len(predictions) = len(targets) <= 1000
  • predictions and targets contain finite numbers
  • delta > 0
  • reduction is one of "none", "mean", or "sum"

Function Signature

def huber_loss(predictions, targets, delta, reduction):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output