Skip to content
fn

binary_cross_entropy_with_logits

→Tensor
binary_cross_entropy_with_logits(input: Tensor, target: Tensor, weight: Tensor | None = None, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean', pos_weight: Tensor | None = None)

Binary cross-entropy from raw logits (numerically stable).

Mathematically equivalent to binary_cross_entropy(sigmoid(input), target) but evaluated in a log-sum-exp-style form that avoids overflow/underflow when |input| is large. This is the preferred binary classification loss for training — composing a separate sigmoid with BCE risks catastrophic cancellation in log⁡(1−σ(x))\log(1 - \sigma(x)) for large positive logits.

Parameters

inputTensor
Raw logits (un-bounded reals), any shape.
targetTensor
Target probabilities (typically binary), same shape as input — another shape raises ValueError rather than being broadcast.
weightTensor or None= None
Element-wise rescaling factor that broadcasts to input's shape; one that does not, or that would enlarge it, raises ValueError.
reductionstr= 'mean'
"mean" (default), "sum", or "none".
size_averagestr= 'mean'
"mean" (default), "sum", or "none".
reducestr= 'mean'
"mean" (default), "sum", or "none".
pos_weightTensor or None= None
Per-class weight applied to the positive term only — useful for highly-imbalanced binary tasks, where setting pos_weight = n_neg / n_pos recovers the prevalence- balanced gradient. It broadcasts to input's shape, as weight does, and is no bool (RuntimeError).

Returns

Tensor

Scalar or full-shape per reduction, in target's dtype.

Notes

The numerically stable form is

Li=(1−yi) xi+softplus⁡(−xi),L_i = (1 - y_i)\,x_i + \operatorname{softplus}(-x_i),

equivalent to −(ylog⁡σ(x)+(1−y)log⁡(1−σ(x)))-(y\log\sigma(x) + (1-y)\log(1-\sigma(x))) but free of overflow, and smooth at x=0x = 0 (the max⁡(x,0)+log⁡(1+e−∣x∣)\max(x, 0) + \log(1 + e^{-|x|}) spelling has the same value but a kink in each piece there). With pos_weight:

Li=(1−yi) xi+(1+(w+−1)yi)softplus⁡(−xi).L_i = (1 - y_i)\,x_i + \big(1 + (w^{+} - 1) y_i\big)\operatorname{softplus}(-x_i).

Gradient w.r.t. input is the clean σ(xi)−yi\sigma(x_i) - y_i (modulo weighting) — the canonical reason this form is used in practice instead of the explicit sigmoid + BCE composition.

Examples

>>> import lucid
>>> from lucid.nn.functional import binary_cross_entropy_with_logits
>>> logits = lucid.tensor([2.0, -1.0, 0.5])
>>> target = lucid.tensor([1.0, 0.0, 1.0])
>>> binary_cross_entropy_with_logits(logits, target)
tensor(0.3048)

Used by 2