class
MultiLabelSoftMarginLoss
extends
ModuleMultiLabelSoftMarginLoss(weight: Tensor | None = None, reduction: str = 'mean')Multi-label soft-margin loss (BCE with logits averaged over classes).
Treats each class as an independent binary classification problem and applies numerically stable binary cross-entropy with logits across all classes, then averages over the class dimension:
where is the sigmoid function. If weight is
provided, each class term is multiplied by weight[c].
Parameters
weightTensor of shape (C,)= NoneManual rescaling weight per class.
reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
weightTensor or NonePer-class weight tensor.
reductionstrThe reduction mode.
Notes
- Input
x: — raw logits. - Target
y: — binary labels in . - Output : scalar for
'mean'/'sum'; for'none'.
- This loss is appropriate when each sample can belong to multiple
classes simultaneously (multi-label classification), as opposed to
CrossEntropyLosswhich assumes mutually exclusive classes. - The input is expected to be raw logits; do not apply sigmoid before passing to this module.
Examples
Multi-label classification with 4 classes:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultiLabelSoftMarginLoss()
>>> logits = lucid.tensor([[1.5, -0.5, 0.3, 2.1],
... [0.2, 1.0, -1.5, 0.8]])
>>> targets = lucid.tensor([[1.0, 0.0, 1.0, 1.0],
... [0.0, 1.0, 0.0, 0.0]])
>>> loss = criterion(logits, targets)
With class-frequency re-weighting:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultiLabelSoftMarginLoss(
... weight=lucid.tensor([1.0, 2.0, 1.0, 0.5])
... )
>>> logits = lucid.tensor([[0.5, 1.0, -0.3, 0.8]])
>>> targets = lucid.tensor([[1.0, 0.0, 1.0, 1.0]])
>>> loss = criterion(logits, targets)Methods (3)
dunder
__init__
→None__init__(weight: Tensor | None = None, reduction: str = 'mean')Initialise the MultiLabelSoftMarginLoss 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.