Skip to content
fn

hinge_embedding_loss

→Tensor
hinge_embedding_loss(input: Tensor, target: Tensor, margin: float = 1.0, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

Hinge embedding loss.

Designed for similarity learning on pre-computed distances: given a (typically non-negative) score input 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

inputTensor
Per-pair score (distance) tensor, any shape.
targetTensor
Label tensor ±1\pm 1 with the same shape as input (one that does not broadcast with it raises ValueError).
marginfloat= 1.0
Margin enforced for negative pairs (default 1.0).
reductionstr= 'mean'
"mean" (default), "sum", or "none".
size_averagestr= 'mean'
"mean" (default), "sum", or "none".
reducestr= 'mean'
"mean" (default), "sum", or "none".

Returns

Tensor

Scalar or full-shape per reduction.

Notes

Per-element loss:

Li={xiyi=+1max⁡(0,  margin−xi)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)

Used by 2