class
TripletMarginLoss
extends
ModuleTripletMarginLoss(margin: float = 1.0, p: float = 2.0, eps: float = 1e-06, swap: bool = False, reduction: str = 'mean')Triplet margin loss for metric learning.
Trains an embedding such that an anchor sample is closer to a
positive (same-class) sample than to a negative (different-class)
sample by at least margin. Given embeddings
:
where the distance is the norm:
The swap option: if enabled, the loss also considers as an alternative negative distance and uses the smaller of and .
Parameters
marginfloat= 1.0Minimum required distance gap. Default
1.0.pfloat= 2.0The norm degree for the distance computation. Default
2.0 (L2).epsfloat= 1e-06Small value added inside the norm to avoid zero-division.
Default
1e-6.swapbool= FalseIf
True, uses the triangle-inequality-based swap.
Default False.reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
marginfloatThe margin threshold.
pfloatThe norm degree.
epsfloatNumerical stabilisation constant.
swapboolWhether the distance swap is active.
reductionstrThe reduction mode.
Notes
- anchor : .
- positive : .
- negative : .
- Output : scalar for
'mean'/'sum'; for'none'.
- Used extensively in face verification, image retrieval, and few-shot learning.
- For variable distance functions (e.g. cosine distance), see
TripletMarginWithDistanceLoss. - Choosing
margindepends on the scale of the embedding space;0.2to1.0is typical for L2-normalised embeddings.
Examples
Basic triplet training step:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.TripletMarginLoss(margin=1.0)
>>> anchor = lucid.tensor([[1.0, 2.0, 3.0]])
>>> positive = lucid.tensor([[1.1, 2.1, 3.1]])
>>> negative = lucid.tensor([[5.0, 6.0, 7.0]])
>>> loss = criterion(anchor, positive, negative)
With L1 distance and larger margin:
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.TripletMarginLoss(margin=2.0, p=1.0)
>>> anchor = lucid.tensor([[0.0, 0.0]])
>>> positive = lucid.tensor([[0.2, 0.2]])
>>> negative = lucid.tensor([[3.0, 3.0]])
>>> loss = criterion(anchor, positive, negative)Methods (3)
dunder
__init__
→None__init__(margin: float = 1.0, p: float = 2.0, eps: float = 1e-06, swap: bool = False, reduction: str = 'mean')Initialise the TripletMarginLoss module. See the class docstring for parameter semantics.
fn
forward
→Tensorforward(anchor: Tensor, positive: Tensor, negative: Tensor)Compute the loss between predictions and targets.
Parameters
anchorTensorInput tensor.
positiveTensorInput tensor.
negativeTensorInput tensor.
Returns
TensorScalar loss (or unreduced tensor depending on reduction).
fn
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.