For binary classification with logit z∈R and target y∈{0,1}, evaluating −(ylog⁡σ(z)+(1−y)log⁡(1−σ(z))) naively can overflow e−z or take log⁡(0). How do you derive the numerically stable form max⁡(z,0)−zy+log⁡(1+e−∣z∣), and what value does it give at z=−2,y=1?

Deep learning, Loss functions
Level L3 Intermediate. Length Short. Nature Mat Mathematical.

What's being asked

Whether you can derive the standard binary-cross-entropy-with-logits identity and explain why every exponent stays ≤0.

Key idea

Substituting σ(z)=11+e−z and 1−σ(z)=e−z1+e−z simplifies binary cross-entropy to log⁡(1+ez)−zy. Using log⁡(1+ez)=z+log⁡(1+e−z) when z≥0 gives max⁡(z,0)−zy+log⁡(1+e−∣z∣), where −∣z∣≤0 never overflows.

Steps

  1. Substitute σ(z): log⁡σ(z)=−log⁡(1+e−z) and log⁡(1−σ(z))=−z−log⁡(1+e−z).
  2. Combine terms: L=ylog⁡(1+e−z)+(1−y)(z+log⁡(1+e−z))=(1−y)z+log⁡(1+e−z)=−zy+z+log⁡(1+e−z)=log⁡(1+ez)−zy.
  3. Split by sign of z: if z<0, use log⁡(1+ez)=0+log⁡(1+e−∣z∣); if z≥0, factor out ez to get z+log⁡(1+e−z)=z+log⁡(1+e−∣z∣). Combining both cases gives L=max⁡(z,0)−zy+log⁡(1+e−∣z∣).
  4. Evaluate at z=−2,y=1: max⁡(−2,0)−(−2)(1)+log⁡(1+e−2)=2+log⁡(1+0.1353)≈2.1269 (matching −log⁡σ(−2) without computing e+2).

Common mistakes

How long your answer should be

5–6 lines with the derivation and numerical check.

Last checked on 4 December 2026.

Read this

Previous in Deep learning: A convolutional layer outputs a tensor of shape (N,C,H,W)=(8,12,16,16) (batch size, channels, height, width). Over which axes are the mean and variance computed, how many distinct (μ,σ2) pairs are computed per batch, and how many learnable scale and shift parameters (γ,β) exist (assuming one pair per channel) for (a) batch normalisation, (b) layer normalisation, (c) instance normalisation and (d) group normalisation with G=3 groups?
Next in Deep learning: How does focal loss FL⁡(pt)=−(1−pt)γlog⁡pt modify cross-entropy for extreme class imbalance, where pt is the predicted probability for the true class and γ≥0 is the focusing parameter? What is the ratio of the loss on a hard example (pt=0.1) to an easy example (pt=0.9) for γ=0 versus γ=2, and why does this help?