cosine_embedding_loss(x1: Tensor, x2: Tensor, y: Tensor, margin: float = 0.0, reduction: Reduction = 'mean')Cosine embedding loss for pairwise similarity learning.
Encourages "similar" pairs (label ) to align in
direction and "dissimilar" pairs () to be at
least margin cosine-units apart. Operates purely on
angular (direction) information — magnitudes are normalised
away, which is useful when the relevant signal is the
direction of embeddings (e.g., word vectors, learned
representations).
Parameters
x1TensorFirst embedding of shape , or for one
unbatched pair (with a 0-d
y, and a 0-d loss under
"none").x2TensorSecond embedding of the same shape.
Label tensor of shape with values , or
0-d for one unbatched pair. A
y of any other rank, inputs of
a rank that does not match it, or shapes that do not line up
raise ValueError.marginfloat= 0.0Minimum desired cosine gap for dissimilar pairs, typically
in (default
0.0).reductionstr= 'mean'"mean" (default), "sum", or "none".Returns
TensorScalar or per-pair tensor of shape .
Notes
Per-pair loss:
With margin = 0, dissimilar pairs are only penalised when
they have positive cosine similarity — i.e., the loss is
satisfied as long as the angle between them exceeds .
Increasing margin toward 1 demands more separation.
Examples
>>> import lucid
>>> from lucid.nn.functional import cosine_embedding_loss
>>> x1 = lucid.tensor([[1.0, 0.0]])
>>> x2 = lucid.tensor([[0.5, 0.5]])
>>> y = lucid.tensor([1.0])
>>> cosine_embedding_loss(x1, x2, y)
tensor(0.2929)