Skip to content
fn

binary_cross_entropy

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

Binary cross-entropy between predicted probabilities and targets.

The standard objective for binary classification and for multi-label classification with independent class predictions. Operates on probabilities in (0,1)(0, 1) — typically the output of a lucid.nn.functional.sigmoid. When working with raw logits, prefer binary_cross_entropy_with_logits for numerical stability.

Each logarithm is clamped below at −100-100, so a probability of exactly 0 or 1 costs at most 100 instead of an infinite or undefined loss, and the input gradient's denominator p(1−p)p(1-p) is floored at ε=10−12\varepsilon = 10^{-12}, so the gradient stays finite at the boundaries too. For a float16 input the floor is 1/655041/65504, the smallest that keeps a float16 gradient finite. Under autocast the loss is computed in float32.

Parameters

inputTensor
Predicted probabilities in [0,1][0, 1], any shape. For a CPU tensor an entry outside [0,1][0, 1] (or NaN) raises ValueError, as the reference's CPU kernel does; a Metal tensor is not read back, which would stall every step, and such an entry makes the loss NaN instead.
targetTensor
Target probabilities (typically binary) in [0,1][0, 1], of the same shape and dtype — another shape raises ValueError rather than being broadcast, and another dtype DtypeMismatch (outside autocast, which casts the operands itself). Its range is checked as input's is.
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. Use to up-weight rare classes or hard examples.
reductionstr= 'mean'
"mean" (default), "sum", or "none".
size_averagestr= 'mean'
"mean" (default), "sum", or "none".
reducestr= 'mean'
"mean" (default), "sum", or "none".

Returns

Tensor

Scalar or full-shape per reduction.

Notes

Per-element loss:

Li=−(yi max⁡(log⁡pi,−100)+(1−yi) max⁡(log⁡(1−pi),−100))L_i = -\big(y_i\,\max(\log p_i, -100) + (1 - y_i)\,\max(\log(1 - p_i), -100)\big)

Gradient w.r.t. input is (pi−yi)/max⁡(pi(1−pi),ε)(p_i - y_i) / \max(p_i(1 - p_i), \varepsilon), which grows without bound as pi→0p_i \to 0 or 11 until the floor caps it — the reason the logits-form (which yields a clean σ(x)−y\sigma(x) - y gradient) is preferred when training stability is critical.

Examples

>>> import lucid
>>> from lucid.nn.functional import binary_cross_entropy
>>> p = lucid.tensor([0.9, 0.2, 0.7])
>>> y = lucid.tensor([1.0, 0.0, 1.0])
>>> binary_cross_entropy(p, y)
tensor(0.2284)

Used by 2