class
HingeEmbeddingLoss
extends
ModuleHingeEmbeddingLoss(margin: float = 1.0, reduction: str = 'mean')Hinge embedding loss for binary similarity learning.
Given an input x representing a scalar distance measure and a
binary label y, the per-element loss is:
With the loss is the distance itself (the model should
produce small distances for positive pairs). With the
model is penalised only if the distance is smaller than margin
(dissimilar pairs should be pushed apart).
Parameters
marginfloat= 1.0Minimum required distance for dissimilar pairs. Default
1.0.reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
marginfloatThe minimum distance for dissimilar pairs.
reductionstrThe reduction mode.
Notes
- x : or — non-negative distance values.
- y : same shape as
x— labels in . - Output : scalar for
'mean'/'sum'; same shape as input for'none'.
- This loss is a one-sided generalisation of the hinge loss used in SVMs, applied here to embedding distances rather than margin-based decision functions.
- The input is typically a pre-computed distance (e.g. L2 norm between representations), not raw logits.
Examples
Embedding distances with margin of 1:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.HingeEmbeddingLoss(margin=1.0)
>>> dists = lucid.tensor([0.3, 1.5, 0.8, 2.1])
>>> labels = lucid.tensor([1.0, 1.0, -1.0, -1.0])
>>> loss = criterion(dists, labels)
Tighter margin to encourage more separation:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.HingeEmbeddingLoss(margin=2.0)
>>> dists = lucid.tensor([0.5, 1.0, 3.0])
>>> labels = lucid.tensor([-1.0, -1.0, 1.0])
>>> loss = criterion(dists, labels)Methods (3)
dunder
__init__
→None__init__(margin: float = 1.0, reduction: str = 'mean')Initialise the HingeEmbeddingLoss module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(x: Tensor, y: Tensor)Compute the loss between predictions and targets.
Parameters
xTensorInput tensor.
yTensorInput tensor.
Returns
TensorScalar loss (or unreduced tensor depending on reduction).
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.