Skip to content
class

MultiMarginLoss

extends_WeightedLoss
MultiMarginLoss(p: int = 1, margin: float = 1.0, weight: Tensor | None = None, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

Multi-class hinge (SVM-style) margin loss.

For each sample with predicted scores x∈RCx \in \mathbb{R}^C and correct class index yy, the per-sample loss sums hinge contributions from all incorrect classes:

L(x,y)=1C∑j=1j≠yCmax⁡ ⁣(0,  margin−x[y]+x[j])p\mathcal{L}(x, y) = \frac{1}{C} \sum_{\substack{j=1 \\ j \neq y}}^{C} \max\!\bigl(0,\; \text{margin} - x[y] + x[j]\bigr)^p

When weight is provided, each class contribution is scaled by weight[y].

Parameters

pint= 1
Exponent of the hinge term; 1 (default) gives the standard hinge, 2 gives the squared hinge.
marginfloat= 1.0
Minimum required score gap between the true class and all others. Default 1.0.
weightTensor of shape (C,)= None
Manual rescaling weight per class.
reductionstr= 'mean'
'none' | 'mean' (default) | 'sum'.

Attributes

pint
Hinge exponent.
marginfloat
The score margin.
weightTensor or None
Per-class weight tensor. A registered buffer: moved by .to() and saved in state_dict.
reductionstr
The reduction mode.

Notes

  • Input x : (N,C)(N, C) — class scores.
  • Target y : (N,)(N,) — integer class indices in [0,C)[0, C).
  • Output : scalar for 'mean' / 'sum'; (N,)(N,) for 'none'.
  • This is the multi-class generalisation of the SVM hinge loss.
  • With p=2 the loss is the squared hinge, which penalises margin violations more aggressively.

Examples

Standard hinge loss over 3 classes:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultiMarginLoss(margin=1.0)
>>> scores  = lucid.tensor([[0.3, 2.1, 0.5], [1.8, 0.2, 1.0]])
>>> targets = lucid.tensor([1, 0])
>>> loss = criterion(scores, targets)
Squared hinge with class weights:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.MultiMarginLoss(
...     p=2,
...     weight=lucid.tensor([1.0, 2.0, 1.0]),
... )
>>> scores  = lucid.tensor([[0.5, 1.5, 0.1]])
>>> targets = lucid.tensor([1])
>>> loss = criterion(scores, targets)

Used by 1

Constructors

1
dunder

__init__

→None
__init__(p: int = 1, margin: float = 1.0, weight: Tensor | None = None, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

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

Instance methods

2
fn

extra_repr

→str
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).