Skip to content
class

BCELoss

extends_WeightedLoss
BCELoss(weight: Tensor | None = None, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

Implementing kernel

C++ engine symbols that back this Python API.

Binary cross-entropy loss.

Measures the element-wise binary cross-entropy between predictions x (probabilities in (0,1)(0, 1)) and binary targets y (values in {0,1}\{0, 1\}):

ℓ(x,y)=−[ylog⁡x+(1−y)log⁡(1−x)]\ell(x, y) = -\bigl[y \log x + (1 - y) \log(1 - x)\bigr]

The input must be valid probabilities, i.e. produced by a Sigmoid activation. Passing raw logits directly leads to undefined behaviour; use BCEWithLogitsLoss instead for better numerical stability when starting from logits.

Parameters

weightTensor= None
Element-wise weight tensor that is broadcast over the input and target tensors. Must be broadcastable to their shape.
reductionstr= 'mean'
'none' | 'mean' (default) | 'sum'.

Attributes

weightTensor or None
Optional element-wise weighting. A registered buffer: moved by .to() and saved in state_dict.
reductionstr
The reduction mode.

Notes

  • Input x : (∗)(*) — probabilities in (0,1)(0, 1).
  • Target y : (∗)(*) — binary labels in {0,1}\{0, 1\}.
  • Output : scalar for 'mean' / 'sum'; (∗)(*) for 'none'.
  • Values of x outside (0,1)(0, 1) will produce NaN or inf losses due to the logarithm.
  • For logits (pre-sigmoid values), prefer BCEWithLogitsLoss which uses the identity log⁡(1+e−x)=max⁡(x,0)+log⁡(1+e−∣x∣)\log(1 + e^{-x}) = \max(x,0) + \log(1 + e^{-|x|}).

Examples

Basic binary classification:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.BCELoss()
>>> probs   = lucid.tensor([0.9, 0.1, 0.8, 0.3])
>>> targets = lucid.tensor([1.0, 0.0, 1.0, 0.0])
>>> loss = criterion(probs, targets)
With element-wise sample weighting:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.BCELoss(weight=lucid.tensor([2.0, 1.0, 2.0, 1.0]))
>>> probs   = lucid.tensor([0.7, 0.2, 0.6, 0.4])
>>> targets = lucid.tensor([1.0, 0.0, 1.0, 0.0])
>>> loss = criterion(probs, targets)

Used by 1

Instance methods

2
fn

extra_repr

→strfrom _Loss
extra_repr()

Return a string representation of the layer's configuration.

fn

forward

→Tensor
forward(input: Tensor, target: Tensor)

Compute the loss between predictions and targets.

Parameters

inputTensor
Input tensor.
targetTensor
Input tensor.

Returns

Tensor

Scalar loss (or unreduced tensor depending on reduction).