v9.1.1
Menu

Binary Cross-Entropy Loss

easyPROOptimization & TrainingDeep LearningDeep Learning 1

Problem Statement

Compute the Binary Cross-Entropy (BCE) loss for a single sample.

Background

Binary Cross-Entropy measures the difference between predicted probabilities and actual binary labels:

L=−(y⋅log⁡(y^)+(1−y)⋅log⁡(1−y^))L = -(y \cdot \log(\hat{y}) + (1 - y) \cdot \log(1 - \hat{y}))

Where:

  • yy is the true label (0 or 1)
  • y^\hat{y} (y-hat) is the predicted probability
  • log⁡\log is natural logarithm

To avoid log(0), which is undefined, keep predictions within [ϵ,1−ϵ][\epsilon, 1 - \epsilon] with ϵ=10−15\epsilon = 10^{-15} before taking logs (simply adding ϵ\epsilon would break when y^=1\hat{y} = 1).

Your Task

Write a function bce_loss(y_true, y_pred) that computes the BCE loss for a single sample.

Output Format

Return a float rounded to 4 decimal places.

Example

Input
y_true=1, y_pred=0.9
Output
0.1054
Reasoning
  • Inputs: y_true = 1 is the true label (the positive class); y_pred = 0.9 is the predicted probability that the label is 1, so the model implicitly gives 1−0.9=0.11 - 0.9 = 0.1 to label 0.
  • Because y=1y = 1, the second term is weighted by 1−y=01 - y = 0 and vanishes: L=−(1⋅ln⁡0.9+0⋅ln⁡0.1)=−ln⁡0.9L = -(1 \cdot \ln 0.9 + 0 \cdot \ln 0.1) = -\ln 0.9.
  • ln⁡0.9≈−0.10536\ln 0.9 \approx -0.10536, slightly negative because 0.90.9 is just below 1. Negating gives a positive loss of 0.105360.10536, which rounds to 4 decimal places as 0.1054.
  • Only the probability placed on the correct label matters. With y=0y = 0, y^=0.1\hat{y} = 0.1 the surviving term is −ln⁡(1−0.1)-\ln(1 - 0.1), the same 0.10540.1054; a coin-flip guess y^=0.5\hat{y} = 0.5 costs −ln⁡0.5≈0.6931-\ln 0.5 \approx 0.6931.
  • Notice the loss grows without bound as the probability on the correct label shrinks (y=0y = 0, y^=0.9\hat{y} = 0.9 already costs 2.30262.3026); the ϵ\epsilon bound keeps a prediction of exactly 0 or 1 from producing ln⁡0\ln 0.

Constraints

  • y_true is 0 or 1
  • 0 <= y_pred <= 1

More from Deep Learning 1

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.