class

MultilabelMarginLoss

extendsModule
MultilabelMarginLoss(reduction: str = 'mean')
source

Multi-label ranking margin loss.

Computes a pairwise ranking loss for multi-label classification where each sample can belong to multiple classes simultaneously. Given a sample with predicted scores x of shape (C,)(C,) and a target y listing the ground-truth class indices (padded with -1), the loss penalises every pair where a non-target class is ranked above a target class:

L(x,y)=1niposjposmax ⁣(0,  1x[yi]+x[j])\mathcal{L}(x, y) = \frac{1}{n} \sum_{i \in \text{pos}} \sum_{j \notin \text{pos}} \max\!\bigl(0,\; 1 - x[y_i] + x[j]\bigr)

where nn is the total number of classes CC.

Parameters

reductionstr= 'mean'
'none' | 'mean' (default) | 'sum'.

Attributes

reductionstr
The reduction mode.

Notes

  • Input x : (N,C)(N, C) or (C,)(C,).
  • Target y : (N,C)(N, C) or (C,)(C,) — integer class indices of positive labels; -1 entries pad the list.
  • Output : scalar for 'mean' / 'sum'; (N,)(N,) for 'none'.
  • Unlike MultiLabelSoftMarginLoss, this loss uses pairwise ranking comparisons and does not require probabilities.
  • The -1 padding convention means: fill the target tensor with positive label indices from the left and pad the remaining entries with -1.

Examples

One sample with 5 classes, two positive labels (0 and 3):
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultilabelMarginLoss()
>>> scores = lucid.tensor([[0.1, 0.5, 0.3, 0.8, 0.2]])
>>> target = lucid.tensor([[0, 3, -1, -1, -1]])
>>> loss = criterion(scores, target)
Batch of two samples:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultilabelMarginLoss(reduction="sum")
>>> scores = lucid.tensor([[1.0, 0.5, 0.2], [0.3, 0.9, 0.4]])
>>> target = lucid.tensor([[0, -1, -1], [1, 2, -1]])
>>> loss = criterion(scores, target)

Methods (3)

dunder

__init__

None
__init__(reduction: str = 'mean')
source

Initialise the MultilabelMarginLoss module. See the class docstring for parameter semantics.

fn

forward

Tensor
forward(x: Tensor, target: Tensor)
source

Compute the loss between predictions and targets.

Parameters

xTensor
Input tensor.
targetTensor
Input tensor.

Returns

Tensor

Scalar loss (or unreduced tensor depending on reduction).

fn

extra_repr

str
extra_repr()
source

Return a string representation of the layer's configuration.