fn

hinge_embedding_loss

Tensor
hinge_embedding_loss(x: Tensor, y: Tensor, margin: float = 1.0, reduction: str = 'mean')
source

Hinge embedding loss.

Designed for similarity learning on pre-computed distances: given a (typically non-negative) score x representing a pairwise distance, push positive pairs (label +1+1) toward small distances and negative pairs (label 1-1) above a fixed margin. Common in Siamese network training and energy-based dissimilarity models.

Parameters

xTensor
Per-pair score (distance) tensor, any shape.
yTensor
Label tensor ±1\pm 1 with the same shape as x.
marginfloat= 1.0
Margin enforced for negative pairs (default 1.0).
reductionstr= 'mean'
"mean" (default), "sum", or "none".

Returns

Tensor

Scalar or full-shape per reduction.

Notes

Per-element loss:

Li={xiyi=+1max(0,  marginxi)yi=1L_i = \begin{cases} x_i & y_i = +1 \\ \max(0,\; \text{margin} - x_i) & y_i = -1 \end{cases}

The positive branch simply minimises the distance; the negative branch is a one-sided hinge that pushes apart only those pairs whose distance is below the margin — pairs already far apart contribute nothing. This asymmetric structure prevents the loss from collapsing all embeddings into a single point.

Examples

>>> import lucid
>>> from lucid.nn.functional import hinge_embedding_loss
>>> dist = lucid.tensor([0.2, 0.8])
>>> y = lucid.tensor([1.0, -1.0])
>>> hinge_embedding_loss(dist, y, margin=1.0)
Tensor(0.2)