Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Paying for surprise
A classifier that outputs a probability p that the answer is “yes” should pay little when it is confident and right, and a lot when it is confident and wrong. Binary cross-entropy does exactly that: it charges −log of the probability given to what actually happened. Saying 0.9 when the answer is yes costs 0.105; saying 0.01 costs 4.6; saying 0 costs infinity.
Binary decisions are everywhere: is this pixel a crack, is this telemetry window anomalous, is there a person in this zone, should this sensor be trusted. Multi-label tasks (several independent yes/no labels per input) use one BCE term per label. The way BCE is computed (from logits, with class weights or not) decides whether training is stable and whether rare events are detected.
- 1. BCE for p = 0.9 when y = 1 is about…
- 2. BCE punishes most…
- 3. Multi-label classification uses…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.By hand
- Definition: BCE(p, y) = −[y log p + (1 − y) log(1 − p)], averaged over examples. For p = (0.8, 0.3) and y = (1, 0): (−log 0.8 − log 0.7)/2 ≈ (0.223 + 0.357)/2 = 0.290.
- From a logit z, with p = σ(z): BCE = y·softplus(−z) + (1 − y)·softplus(z) = max(z, 0) − yz + log(1 + e^(−|z|)). This form never overflows.
- Gradient with respect to the logit: ∂BCE/∂z = p − y. With z = 0 and y = 1, it is −0.5.
- Positive weighting: weight the y = 1 term by w, usually #negatives/#positives, to counter class imbalance. pos_weight = 4 for 1 positive among 5.
- Label smoothing: replace the targets 0 and 1 by ε/2 and 1 − ε/2, for example 0.05 and 0.95 with ε = 0.1.
- Soft targets: BCE(p, y) = H(y) + KL(y ‖ p), so for a fixed target it is minimised exactly at p = y.
- 1. ∂BCE/∂z with z = 0, y = 0 is…
- 2. For 1 positive in 10 examples, the usual pos_weight is…
- 3. With a soft target y, BCE is minimised at…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.Computing it safely
Exercise 1.
- From probabilities, BCE needs clipping: log(0) = −∞. With ε = 10⁻⁷, a probability of exactly 0 for a positive costs about 16 instead of infinity.
- From logits, it is finite for any input: logit −800 for a positive gives exactly 800.
- The logit gradient (p − y)/n matches finite differences.
- pos_weight multiplies the positive term.
- H(y) + KL(y ‖ p) equals the BCE for a soft target.
Rules.
- Give the loss logits, not sigmoid outputs:
BCEWithLogitsLoss. It is stable, and its gradient is exactly p − y. - Use pos_weight (or resampling) for rare positives, then choose the decision threshold on validation data; 0.5 is not sacred.
- Label smoothing reduces overconfidence but biases predicted probabilities toward 0.5, so re-check calibration.
nn.BCEWithLogitsLoss(pos_weight=torch.tensor([9.0])) # stable, weighted
nn.BCELoss()(torch.sigmoid(z), y) # works, but less stable- 1. The stable way to compute BCE is…
- 2. After training with pos_weight, the decision threshold should be…
- 3. Label smoothing pulls predicted probabilities…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.Theory
Likelihood. For a label y that is 0 or 1, with P(y = 1) = p, the Bernoulli log-likelihood is y log p + (1 − y) log(1 − p). BCE is its negative, so minimising BCE is maximum likelihood, and logistic regression is exactly BCE with a linear logit.
Proper scoring rule. The expected BCE under the true probability q, −[q log p + (1 − q) log(1 − p)], is uniquely minimised at p = q. Honest probabilities are optimal, which is why BCE-trained models can be calibrated. The Brier score (squared error on probabilities) is also proper.
Why not squared error on σ(z)? Its gradient with respect to z is 2(p − y)·p(1 − p). When the model is confidently wrong (p near 0 for y = 1), the factor p(1 − p) is nearly 0, so the model barely learns from its worst mistakes. BCE’s gradient p − y is largest exactly then, because the log cancels the sigmoid’s saturation. Exercise 2 measures the consequence.
Information theory.
- BCE is the cross-entropy between the label distribution (y, 1 − y) and the prediction (p, 1 − p): H(y) + KL(y ‖ p).
- With hard labels H(y) = 0, so BCE is the KL divergence itself.
- In bits (log base 2) it is the average code length needed to encode the labels with the model’s probabilities.
- 1. Logistic regression minimises…
- 2. A proper scoring rule is minimised in expectation by…
- 3. Squared error on σ(z) learns slowly from confident mistakes because of the factor…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.Recovering from confident mistakes
History.
- Cross-entropy comes from C. Shannon’s information theory (1948) and S. Kullback and R. Leibler’s divergence (1951).
- Logistic regression (D. Cox, 1958) is maximum likelihood with BCE.
- In neural networks, J. Hopfield (1987) and E. Baum and F. Wilczek (1988) argued for cross-entropy over squared error.
- P. Golik, P. Doetsch and H. Ney (2013) compared the two for training deep networks.
Exercise 2. Logistic regression on two Gaussian classes (400 points), trained by gradient descent at learning rate 0.5. The weights start pointing the wrong way with norm 0 to 20, so the model is confidently wrong. The table counts steps until training accuracy reaches 90%.
| initial wrong-way weight norm | BCE | squared error on σ(z) |
|---|---|---|
| 0 | 1 | 1 |
| 2 | 4 | 21 |
| 5 | 9 | 273 |
| 10 | 17 | never (3000+) |
| 20 | 33 | never (3000+) |
- BCE’s recovery time grew linearly with the initial confidence, about 1.6 steps per unit of weight norm. Its gradient p − y stays near ±1 for confidently wrong examples.
- Squared error on the sigmoid slowed exponentially. Its gradient carries the factor p(1 − p) ≈ e^(−|z|), which vanishes for confidently wrong examples. From norm 10 it did not recover in 3000 steps.
- This is why classifiers use cross-entropy. Saturated, confidently wrong states occur in practice after a bad initialisation, a distribution shift, or a large learning-rate step, and only cross-entropy reliably escapes them.
BCE in AI, robotics and aerospace
- Segmentation and inspection: per-pixel crack, corrosion or landing-zone masks are trained with BCE, often combined with Dice loss (E2-9) and weighted for rare defects.
- Anomaly and fault detection: binary classifiers on telemetry windows use pos_weight to handle rare faults; thresholds are then tuned for the required false-alarm rate.
- Multi-label perception: a scene can contain a person, a vehicle and an obstacle at once, so each label gets its own BCE.
References
- C. E. Shannon (1948). “A mathematical theory of communication.” Bell System Technical Journal 27.
- D. R. Cox (1958). “The regression analysis of binary sequences.” Journal of the Royal Statistical Society B 20(2).
- E. B. Baum, F. Wilczek (1988). “Supervised learning of probability distributions by neural networks.” Neural Information Processing Systems.
- P. Golik, P. Doetsch, H. Ney (2013). “Cross-entropy vs. squared error training: a theoretical and experimental comparison.” Proc. Interspeech.
- T. Gneiting, A. E. Raftery (2007). “Strictly proper scoring rules, prediction, and estimation.” Journal of the American Statistical Association 102.