#162BCE — clip the probabilities so log stays finiteEasyNeural NetworksLoss Functions
BCE — clip the probabilities so log stays finite
Background
Binary cross-entropy is
The catch: . If a model ever predicts exactly or , the naive formula returns nan/inf. Real implementations clip into first so the log stays finite.
Problem statement
Implement clipped_bce(y, y_hat, eps=1e-7) that clips the predictions to and returns the mean BCE.
Input
y— array-like of labels (0/1).y_hat— array-like of predicted probabilities in (may include exactly 0 or 1).eps—float, the clip margin (default1e-7).
Output
Returns a Python float: a finite mean BCE.
Examples
Example 1 — ordinary case
Input: y = [1, 0], y_hat = [0.9, 0.1]
Output: 0.1053605...
Explanation: .
Example 2 — exact 0/1 no longer explodes
Input: y = [1, 0], y_hat = [1.0, 0.0]
Output: ~1.2e-7 (finite, tiny)
Explanation: clipping to / keeps the log finite instead of nan.
Constraints
- Clip
y_hatto[eps, 1 - eps]before taking logs. - Average over the examples.
- Return a finite
float.
Notes
- A confident wrong prediction (e.g. when ) still produces a large loss — the clip bounds it instead of letting it become infinite.
Python
Loading...
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Example: ordinary probabilities
- •Reference: exact 0/1 stays finite and tiny
- •Sample: confident-wrong single prediction