class
BCELoss
extends
ModuleBCELoss(weight: Tensor | None = None, reduction: str = 'mean')Binary cross-entropy loss.
Measures the element-wise binary cross-entropy between predictions
x (probabilities in ) and binary targets y
(values in ):
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= NoneElement-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 NoneOptional element-wise weighting.
reductionstrThe reduction mode.
Notes
- Input
x: — probabilities in . - Target
y: — binary labels in . - Output : scalar for
'mean'/'sum'; for'none'.
- Values of
xoutside will produceNaNorinflosses due to the logarithm. - For logits (pre-sigmoid values), prefer
BCEWithLogitsLosswhich uses the identity .
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)Methods (3)
dunder
__init__
→None__init__(weight: Tensor | None = None, reduction: str = 'mean')Initialise the BCELoss module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(x: Tensor, target: Tensor)Compute the loss between predictions and targets.
Parameters
xTensorInput tensor.
targetTensorInput tensor.
Returns
TensorScalar loss (or unreduced tensor depending on reduction).
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.