Skip to content
DeepForgeby svx
All problems
MediumML Fundamentalsml-014

Binary Cross-Entropy Loss

Problem

Compute the binary cross-entropy loss: -(1/n) * sum(y_i * log(p_i) + (1 - y_i) * log(1 - p_i)).

Clip every predicted probability to [1e-15, 1 - 1e-15] before taking the log. Empty input returns 0.0.

Hint

Clamp p before logging; the loss is the negative average log-likelihood of the true labels.

Test cases

case 1
in: [[1,0,1,1],[0.9,0.1,0.8,0.7]]
expected: 0.19763488164214868
case 2
in: [[1,1,0,0],[0.5,0.5,0.5,0.5]]
expected: 0.6931471805599453
case 3
in: [[1,0],[0,1]]
expected: 34.53917619362578
case 4
in: [[1,0,1],[0.6,0.6,0.6]]
expected: 0.6459806598020454
Starter codePython
import math
def binary_cross_entropy(y_true, y_pred):
    # Your code here
    pass

4 test cases · run your code against them in the editor