fn
cosine_embedding_loss
→Tensorcosine_embedding_loss(x1: Tensor, x2: Tensor, y: Tensor, margin: float = 0.0, reduction: str = '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 .
x2TensorSecond embedding of the same shape.
yTensorLabel tensor of shape with values .
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.2928...)