class
CosineEmbeddingLoss
extends
ModuleCosineEmbeddingLoss(margin: float = 0.0, reduction: str = 'mean')Cosine embedding loss for learning similarity/dissimilarity.
Measures whether two inputs are similar or dissimilar using cosine
similarity. The label y must be +1 (similar) or -1
(dissimilar):
where .
Parameters
marginfloat= 0.0Minimum cosine similarity below which dissimilar pairs incur
zero loss. Must be in . Default
0.0.reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
marginfloatThe cosine similarity margin for dissimilar pairs.
reductionstrThe reduction mode.
Notes
- x1 : .
- x2 : .
- y : with values in .
- Output : scalar for
'mean'/'sum'; for'none'.
- Useful when the magnitude of embeddings is not informative — only the angle between them matters (e.g. sentence similarity, image pairing).
- Setting
margin > 0means dissimilar pairs are only penalised when their cosine similarity exceeds the margin.
Examples
Paired sentence embeddings:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.CosineEmbeddingLoss(margin=0.5)
>>> x1 = lucid.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]])
>>> x2 = lucid.tensor([[0.9, 0.1, 0.0], [0.0, 0.0, 1.0]])
>>> y = lucid.tensor([1.0, -1.0])
>>> loss = criterion(x1, x2, y)
Zero margin for dissimilar pairs:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.CosineEmbeddingLoss()
>>> x1 = lucid.tensor([[1.0, 2.0]])
>>> x2 = lucid.tensor([[2.0, 1.0]])
>>> y = lucid.tensor([1.0])
>>> loss = criterion(x1, x2, y)Methods (3)
dunder
__init__
→None__init__(margin: float = 0.0, reduction: str = 'mean')Initialise the CosineEmbeddingLoss module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(x1: Tensor, x2: Tensor, y: Tensor)Compute the loss between predictions and targets.
Parameters
x1TensorInput tensor.
x2TensorInput tensor.
yTensorInput tensor.
Returns
TensorScalar loss (or unreduced tensor depending on reduction).
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.