All formulas

Machine learning building blocks

Binary cross-entropy from logits

ml.bce-with-logitsAlso called bce with logits, binary cross entropy with logits, sigmoid cross entropy, bcewithlogits

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

whereσ(t)=11+e−t\sigma(t) = \frac{1}{1 + e^{-t}}

Binary cross-entropy of targets y against the sigmoid of logits z, in nats. Applying the sigmoid first and then the log fails for large |z|; the per-example form max(z, 0) − zy + ln(1 + e−|z|) is exact and stable.

Notation

zz

logits

z ∈ ℝn

yy

targets in {0, 1}

y ∈ {0, 1}n

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

    z=[0],y=[1]z = [0], y = [1]

    Result

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

    ≈ 0.69314718056

  2. Given

    z=[0,0],y=[0,1]z = [0, 0], y = [0, 1]

    Result

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

    ≈ 0.69314718056

  3. Given

    z=[2],y=[1]z = [2], y = [1]

    Result

    L=log⁡(e−2+1)\displaystyle \mathcal{L} = \log{\left(e^{-2} + 1 \right)}

    ≈ 0.126928011043

  4. Given

    z=[−1,3],y=[0,0]z = [-1, 3], y = [0, 0]

    Result

    L=log⁡(e−1+1)2+log⁡(1+e3)2\displaystyle \mathcal{L} = \frac{\log{\left(e^{-1} + 1 \right)}}{2} + \frac{\log{\left(1 + e^{3} \right)}}{2}

    ≈ 1.68092451955

  5. Given

    z=[40],y=[0]z = [40], y = [0]

    Result

    L=log⁡(1+e40)\displaystyle \mathcal{L} = \log{\left(1 + e^{40} \right)}

    ≈ 40

    σ(40) rounds to 1 in float64, so taking ln(1 − σ(z)) gives infinity.

Common mistakes

  • Applies the sigmoid, then the log

    σ(z) rounds to exactly 1 for z above about 37 and to 0 for z below about −745, so ln 0 gives an infinite loss.

    Fix: Use max(z, 0) − zy + log1p(exp(−|z|)) per example, or torch.nn.functional.binary_cross_entropy_with_logits.

  • Sums instead of averaging

    The per-example losses are summed, not averaged.

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

Source

  • Goodfellow et al. 2016, §6.2.2.2

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

    deeplearningbook.org