v9.1.1
Menu

Binary Cross-Entropy Loss

easyFREEClassificationMachine Learning 1

Compute the binary cross-entropy loss (log loss) for a set of predictions.

Given true labels yi∈{0,1}y_i \in \{0, 1\} and predicted probabilities y^i∈(0,1)\hat{y}_i \in (0, 1):

BCE=−1n∑i=1n[yilog⁡(y^i)+(1−yi)log⁡(1−y^i)]BCE = -\frac{1}{n}\sum_{i=1}^{n}[y_i \log(\hat{y}_i) + (1 - y_i)\log(1 - \hat{y}_i)]

To avoid log⁡(0)\log(0), clip predictions to the range [ϵ,1−ϵ][\epsilon, 1-\epsilon] where ϵ=10−7\epsilon = 10^{-7}.

Return the loss rounded to 4 decimal places.

Example

Input
y_true = [1, 0, 1]
y_pred = [0.9, 0.1, 0.8]
Output
0.1446
Reasoning
  • y_true holds the actual class of each of the n=3n = 3 samples (11 = positive, 00 = negative); y_pred holds the model's probability that each sample is positive.
  • All three predictions already lie well inside [10−7,1−10−7][10^{-7}, 1 - 10^{-7}], so the clipping leaves them unchanged here; it only matters for predictions at (or within 10−710^{-7} of) 00 or 11.
  • Each sample contributes only one of the two terms: when yi=1y_i = 1 the loss is −ln⁡(y^i)-\ln(\hat{y}_i), when yi=0y_i = 0 it is −ln⁡(1−y^i)-\ln(1 - \hat{y}_i), i.e. minus the natural log (log⁡\log in the formula) of the probability given to the true class.
  • Sample 1: −ln⁡(0.9)≈0.1054-\ln(0.9) \approx 0.1054. Sample 2: true class is 00, probability given to it is 1−0.1=0.91 - 0.1 = 0.9, so again ≈0.1054\approx 0.1054. Sample 3: −ln⁡(0.8)≈0.2231-\ln(0.8) \approx 0.2231.
  • Average: 0.1054+0.1054+0.22313≈0.1446\frac{0.1054 + 0.1054 + 0.2231}{3} \approx 0.1446, the output 0.1446 (rounded to 4 decimal places).
  • Notice the least confident correct prediction (sample 3) contributes the most; a confident wrong prediction would make the loss blow up.

Constraints

  • y_true: list of 0s and 1s
  • y_pred: list of predicted probabilities (0 to 1)
  • Clip predictions to [1e-7, 1-1e-7] before computing log
  • Return a single float rounded to 4 decimal places

Learn this in

More from Machine Learning 1

solution.py

Test results

Sign in to run your code against the test cases.