All formulas

Machine learning building blocks

Binary cross-entropy

ml.binary-cross-entropyAlso called binary cross entropy, bce, log loss, logloss

L=−1n∑i=1n(yiln⁡pi+(1−yi)ln⁡(1−pi))\mathcal{L} = -\frac{1}{n}\sum_{i=1}^{n}\left(y_i\ln p_i + (1 - y_i)\ln\left(1 - p_i\right)\right)

Mean negative log-likelihood of binary targets under predicted probabilities p, in nats.

Notation

yy

targets in {0, 1}

y ∈ {0, 1}n

pp

predicted probabilities in (0, 1)

p ∈ ℝn, each entry ∈ (0, 1)

nn

number of entries

Size, at least 1

L\mathcal{L}

Result: the mean loss, in nats

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    y=[1,0],p=[0.5,0.5]y = [1, 0], p = [0.5, 0.5]

    Result

    L=log⁡(2)\displaystyle \mathcal{L} = \log{\left(2 \right)}

    ≈ 0.69314718056

  2. Given

    y=[1],p=[0.25]y = [1], p = [0.25]

    Result

    L=2log⁡(2)\displaystyle \mathcal{L} = 2 \log{\left(2 \right)}

    ≈ 1.38629436112

  3. Given

    y=[1,0,1],p=[0.8,0.2,0.5]y = [1, 0, 1], p = [0.8, 0.2, 0.5]

    Result

    L=2log⁡(54)3+log⁡(2)3\displaystyle \mathcal{L} = \frac{2 \log{\left(\frac{5}{4} \right)}}{3} + \frac{\log{\left(2 \right)}}{3}

    ≈ 0.379811427729

Common mistakes

  • Sums instead of averaging

    The per-example losses are summed, not averaged over the n examples.

    Fix: Divide by n, or use reduction='mean'.

  • Swaps ln p and ln(1 − p)

    Targets of 1 are scored with ln(1 − p) and targets of 0 with ln p.

    Fix: Pair y with ln p and (1 − y) with ln(1 − p).

Sources

  • Goodfellow et al. 2016, §6.2.2.2

    Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.

    deeplearningbook.org
  • Murphy 2022

    Murphy, Kevin P. Probabilistic Machine Learning: An Introduction. MIT Press, 2022.