Binary cross-entropy: what weighting estimates
二元交叉熵
Fit a constant Bernoulli model, derive the weighted optimum and verify logit gradients and reduction denominators.
binary-cross-entropyThe same accuracy can hide different probability errors
Two binary models predict the same class on a positive example, but assign probabilities 0.51 and 0.99. A zero-one accuracy score treats both predictions as correct. Binary cross-entropy, or BCE, distinguishes how much probability the model assigned to the observed outcome. It also penalizes a confident wrong prediction strongly.
BCE is a training objective and a probability-sensitive evaluation quantity. It is not the same as classification accuracy, a decision threshold or a cost matrix. Deep Learning, Section 6.2.2.2 derives the Bernoulli output loss. The fixed PyTorch 2.8 BCEWithLogitsLoss documentation specifies logit input, positive-class weighting and reduction semantics. Our implementation below is independent standard-library code, not a PyTorch execution.
Read Bernoulli and binomial distributions and sigmoid and tanh. This chapter concentrates on what the loss estimates and what weighting changes, rather than repeating the activation’s saturation comparison.
A Bernoulli likelihood becomes a loss
Let y be 0 or 1 and p be a predicted positive probability strictly between 0 and 1. Under a Bernoulli model:
Natural logs measure the loss in nats. R is the expected loss when the true conditional positive probability is η. Differentiating R gives(p−η)/(p(1−p)), so for the unique minimum is p=η. This is a population statement with unrestricted probabilities. Model misspecification, finite data and unsuccessful optimization can prevent a fitted system from recovering η.
Summing per-example negative log likelihood assumes conditional independence under the model. Averaging by the number of elements rescales the same finite objective without changing its minimizer, but it changes gradient magnitudes. A soft target y in[0,1] produces the cross-entropy of a Bernoulli target distribution; it is not literally one observed fractional Bernoulli outcome.
Positive-class weighting changes the optimum
Multiply only the positive term by c>0. At a fixed input with true positive probability η:
The minimum follows by setting the derivative to zero. The inverse relation assumes this ideal population optimum and the stated weighting model; applying it to an imperfect network does not automatically calibrate predictions. With η=1/4 and c=3, the optimal weighted output becomes 1/2 instead of 1/4. The weighted score should not simply be reported as the original positive probability.
At the ideal optimum, thresholding the weighted output at 1/2 corresponds to thresholding η at 1/(c+1). Weighting can therefore change decisions, but an unconditional promise that it improves recall or precision on every finite trained model would be too strong. Choose thresholds and weights using validation criteria suited to the application.
Compute the weighted loss directly from logits
For logit z, define stable softplus s(z)=max(z,0)+log(1+exp(−|z|)). Then:
This works for hard or soft targets. The two signed sigmoid terms avoid subtracting an output rounded to one. For mean reduction, each logit derivative is divided by N. Here N counts loss elements, not the sum of class weights; a different normalization is a different scaling convention.
Fit a constant predictor and audit the reduction
Our complete Python 3.12 example fits an intercept-only model to labels[1,0,0,0]. A closed-form optimum has logit log(c·n₊/n₋), provided both classes appear. It then computes the weighted loss and individual logit derivatives at that fitted score.
from math import exp, log, log1p, isfinite
def binary_objective(logits, targets, positive_weight=1, reduction='mean'):
logits=list(logits);targets=list(targets);c=positive_weight
if not 1<=len(logits)==len(targets)<=128:
raise ValueError('matching nonempty vectors of at most 128 elements required')
if type(c) not in (int,float) or not isfinite(c) or not 0<c<=100:
raise ValueError('positive finite weight at most 100 required')
if reduction not in ('mean','sum'):raise ValueError('mean or sum required')
if any(type(z) not in (int,float) or not isfinite(z) or abs(z)>1000 for z in logits):
raise ValueError('bounded finite logits required')
if any(type(y) not in (int,float) or not isfinite(y) or not 0<=y<=1 for y in targets):
raise ValueError('targets in [0,1] required')
values=[];gradients=[]
for z,y in zip(logits,targets):
e=exp(-abs(z));p=1/(1+e) if z>=0 else e/(1+e)
q=e/(1+e) if z>=0 else 1/(1+e)
softplus=log1p(e)
values.append((1-y)*(max(z,0)+softplus)+c*y*(max(-z,0)+softplus))
gradients.append((1-y)*p-c*y*q)
divisor=len(values) if reduction=='mean' else 1
return sum(values)/divisor,[g/divisor for g in gradients]
def fit_constant(targets, positive_weight=1):
targets=list(targets)
binary_objective([0]*len(targets),targets,positive_weight)
if any(type(y) is not int or y not in (0,1) for y in targets):
raise ValueError('constant fit uses hard binary integer labels')
positives=sum(targets);negatives=len(targets)-positives
if not positives or not negatives:raise ValueError('both classes needed for finite optimum')
return log(positive_weight*positives/negatives)
if __name__=='__main__':
y=[1,0,0,0]
for c in (1,3):
z=fit_constant(y,c);loss,grad=binary_objective([z]*4,y,c)
p=1/(1+exp(-z))
print('positive weight:',c,'fitted logit/probability/mean loss:',*[f'{v:.9f}' for v in (z,p,loss)],
'shared-logit gradient:',f'{sum(grad):.9f}')
mean,g=binary_objective([0]*4,y,3)
total,_=binary_objective([0]*4,y,3,'sum')
print('weighted per-element gradients:',g)
print('mean by 4 elements:',f'{mean:.9f}','sum:',f'{total:.9f}',
'alternative normalized by total class weight 6:',f'{total/6:.9f}')
Actual output:
positive weight: 1 fitted logit/probability/mean loss: -1.098612289 0.250000000 0.562335145 shared-logit gradient: 0.000000000
positive weight: 3 fitted logit/probability/mean loss: 0.000000000 0.500000000 1.039720771 shared-logit gradient: 0.000000000
weighted per-element gradients: [-0.375, 0.125, 0.125, 0.125]
mean by 4 elements: 1.039720771 sum: 4.158883083 alternative normalized by total class weight 6: 0.693147181
Without weighting, the fitted probability is 1/4. With c=3 it is 1/2. At the latter fit the per-element mean gradients are[−3/8,1/8,1/8,1/8]; they sum to zero because all examples share the same intercept. Individual logits would not all be stationary if they were independently trainable parameters.
At zero logits and c=3, the loss sum is 6 log 2. Dividing by 4 elements gives(3/2)log 2; dividing instead by total class weight 6 gives log 2. The two results are not a numerical discrepancy. They answer different normalization choices. Duplicating the entire batch doubles the summed loss while retaining the mean and the constant-fit optimum.
Evaluation costs O(N) scalar operations and O(N) storage for the returned derivatives. Constant fitting costs O(N) to count labels. The test suite checks the analytic optimum, reductions, soft-target finite differences, extreme finite logits and rejected one-class finite fits. No general-purpose classifier is trained here.
Good log loss is not the whole decision problem
For a dataset containing only one class, the intercept-only unregularized optimum lies at an infinite logit. The code rejects a request for a finite optimum in that case; it does not invent a finite maximum-likelihood estimate. A prior, regularization or probability constraint changes the problem and can produce a finite answer.
Multi-label prediction often sums one BCE per label. This models separate Bernoulli marginals and does not capture all label dependencies. Mutually exclusive classes usually call for a normalized categorical model instead. Padding masks, missing labels, sample weights and class weights require explicit broadcasting and denominators; silently averaging padded elements can change training.
A low BCE does not establish fairness, robustness or the suitability of a chosen action. Report probability quality alongside the decision metrics that matter, using held-out data. For unequal action costs, the Bayesian decision theory chapter separates probability estimation from action selection.
What did the weight change?
- What constant probability minimizes unweighted BCE for labels[1,0,0,0]?
Answer 1: One quarter, with logit−log 3.
- What probability minimizes the positive-weighted version with c=3?
Answer 2: One half. The class weight changes the optimum, not merely the overall loss scale.
- At zero logits and c=3, what is the loss averaged over four elements?
Answer 3: (3/2)log 2. Dividing by the total class weight instead would give log 2.
- Why can the shared-intercept gradient be zero when individual logit gradients are nonzero?
Answer 4: The intercept affects every logit, so its derivative is their sum; positive and negative contributions cancel.
Document the objective precisely enough to reproduce it
The textbook provides the likelihood interpretation, and the fixed-version library documentation provides an explicit interface contract. Our constant fit, optimum correction, reduction comparison and tests are original. We adopt the documented element-count mean; we do not adopt a universal claim that class weighting must improve a particular metric.
When reporting an experiment, specify whether inputs are logits or probabilities, target semantics, positive and sample weights, masks and reduction. That information is more useful than writing only “BCE loss.” Continue to model evaluation and calibration for checks beyond the training objective.
Make a prediction, then check
For one positive and three negatives with positive weight3, what is the fitted constant probability?
Learning objectives
- Derive the probability targeted by positive-class weighting.
- Check logits, target semantics and loss reduction.
Prerequisites & connections
Explore related knowledge →References
- Deep Learning — Chapter 6: Deep Feedforward Networks
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - BCEWithLogitsLoss — PyTorch 2.8
PyTorch contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. Rectifier update paths, smooth-gate moments/stationary points, batch intermediates and weighted Bernoulli optima are checked against literal references, analytic identities and finite differences. Forward-pass example uses pinned NumPy1.26.4; other examples use the standard library.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Strict MDX rendering found a raw chained inequality parsed as JSX. Converted only that inline condition to KaTeX in both languages and rebound article SHA; final render must pass before build acceptance.
Source locations checked:
- Deep Learning — Chapter 6: Deep Feedforward Networks · Section6.2.2.2 pp178–180, Bernoulli output likelihood and logit/softplus relation.
- BCEWithLogitsLoss — PyTorch 2.8 · Fixed2.8 BCEWithLogitsLoss definition, positive-term weight, element-count mean reduction and target range; unconditional metric-improvement wording not adopted.
Related topics