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.
def custom_focal_loss(logits, labels, alpha, gamma, label_smoothing):