Binary Cross-Entropy Loss
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^β))
Where:
- y is the true label (0 or 1)
- y^β (y-hat) is the predicted probability
- log is natural logarithm
To avoid log(0) which is undefined, we add a small epsilon (1e-15) to predictions.
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:
y_true=1, y_pred=0.9
0.1054
L = -(1 Γ log(0.9) + 0 Γ log(0.1)) = -log(0.9) β 0.1054
Constraints:
- y_true is 0 or 1
- 0 <= y_pred <= 1
1. Background Knowledge
Binary Cross-Entropy (BCE) loss quantifies the difference between predicted probabilities y^β and true binary labels yβ{0,1} for binary classification tasks. The formula is:
L=β(yβ log(\hat{y})+(1βy)β log(1β\hat{y}))
This derives from information theory as the Kullback-Leibler divergence between true and predicted distributions, measuring prediction uncertainty. BCE penalizes confident wrong predictions heavily (e.g., y^ββ0 when y=1) and approaches 0 for perfect predictions. It's the standard loss for logistic regression and binary classification in neural networks.
Key prerequisites:
- Natural logarithm: log is base-e; Python's math.log computes this.
- Numerical stability: log(0) is undefined (ββ), so clip y^β with Ο΅=10β15: y^β=max(min(\hat{y},1β\epsilon),\epsilon).
- Single sample: No averaging over batches needed here.
2. Algorithm Approach
Direct computation using the closed-form formulaβno optimization or iteration required. Common techniques:
- Clipping for stability: Standard practice to prevent NaN/inf.
- Vectorized implementation (for batches, though not needed here): Use NumPy for efficiency.
- Alternatives in literature: Weighted BCE for imbalance, but vanilla BCE suffices for this balanced single-sample case.
The approach is O(1) arithmetic: log, multiply, add.
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
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.