Skip to content
fn

cosine_embedding_loss

→Tensor
cosine_embedding_loss(input1: Tensor, input2: Tensor, target: Tensor, margin: float = 0.0, size_average: bool | None = None, reduce: bool | None = None, reduction: Reduction = 'mean')

Cosine embedding loss for pairwise similarity learning.

Encourages "similar" pairs (label y=1y = 1) to align in direction and "dissimilar" pairs (y=−1y = -1) 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

input1Tensor
First embedding of shape (N,D)(N, D), or (D,)(D,) for one unbatched pair (with a 0-d target, and a 0-d loss under "none").
input2Tensor
Second embedding of the same shape.
targetTensor
Label tensor of shape (N,)(N,) with values ±1\pm 1, or 0-d for one unbatched pair. A target of any other rank, inputs of a rank that does not match it, or shapes that do not line up raise ValueError.
marginfloat= 0.0
Minimum desired cosine gap for dissimilar pairs, typically in [−1,1][-1, 1] (default 0.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 per-pair tensor of shape (N,)(N,).

Notes

Per-pair loss:

Li={1−cos⁡(x1(i),x2(i))yi=+1max⁡ ⁣(0,  cos⁡(x1(i),x2(i))−margin)yi=−1L_i = \begin{cases} 1 - \cos(x_1^{(i)}, x_2^{(i)}) & y_i = +1 \\ \max\!\big(0,\; \cos(x_1^{(i)}, x_2^{(i)}) - \text{margin}\big) & y_i = -1 \end{cases}

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 90°90°. 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)

Used by 2