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
where
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
logits
z ∈ ℝn
targets in {0, 1}
y ∈ {0, 1}n
number of entries
Size, at least 1
Result: the mean loss, in nats
scalar
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
≈ 0.69314718056
Given
Result
≈ 0.69314718056
Given
Result
≈ 0.126928011043
Given
Result
≈ 1.68092451955
Given
Result
≈ 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.