Skip to content

← ML Foundations step 6 of 10

Medium Primitives

Implement Binary Cross-Entropy Loss

Binary cross-entropy measures how much probability a model assigns to the correct binary label. Here y_pred is the probability of label 1.

For label 1, the loss is -log(p). For label 0, it is -log(1 - p). Use the natural logarithm. A confident correct prediction has a small loss; a confident wrong prediction has a large loss.

For labels [1, 0] and probabilities [0.8, 0.25], the probabilities assigned to the correct labels are [0.8, 0.75]. The mean loss is (-log(0.8) - log(0.75)) / 2, approximately 0.255413.

Your task

Implement bce_loss(y_true, y_pred) for two nonempty 1D floating-point tensors of the same shape. Labels are 0 or 1. Predictions are probabilities in [0, 1], not logits (raw model scores).

First clamp each prediction to [1e-7, 1 - 1e-7]. Then return the scalar mean of -(y * log(p) + (1 - y) * log(1 - p)) using the clamped values. Clamp the probabilities; do not add epsilon to every logarithm argument.

Clamping makes the loss finite even for an input probability of 0 or 1. It also changes the loss near those endpoints. This exercise specifies its own probability-clamping rule, so do not substitute a library BCE loss with a different boundary rule. Build the result from basic tensor operations.

The plot starts with label 1 and shows the loss as its predicted probability changes. It uses the same probability-clamping rule as the exercise.

Loading visualization…