binary_cross_entropy(x: Tensor, target: Tensor, weight: Tensor | 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 — 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 , 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
is floored at , so the
gradient stays finite at the boundaries too. For a float16 input the
floor is , the smallest that keeps a float16 gradient
finite. Under autocast the loss is computed in float32.
Parameters
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.targetTensorValueError rather than
being broadcast. Its range is checked as x's is.x'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".Returns
TensorScalar or full-shape per reduction.
Notes
Per-element loss:
Gradient w.r.t. x is
, which grows
without bound as or until the floor
caps it — the reason the logits-form (which yields a clean
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)