TripletMarginWithDistanceLoss
ModuleTripletMarginWithDistanceLoss(distance_function: Callable[[Tensor, Tensor], Tensor] | None = None, margin: float = 1.0, swap: bool = False, reduction: str = 'mean')Triplet margin loss with a user-supplied distance function.
A generalisation of TripletMarginLoss that replaces the
fixed norm with an arbitrary differentiable distance
function. Given anchor , positive , and negative
embeddings and a callable :
When distance_function is None, the default falls back to the
Euclidean (L2) distance, making this equivalent to
TripletMarginLoss with .
The swap option: if True, the loss also considers
as an alternative negative distance and replaces
with , exploiting the
triangle inequality.
Parameters
distance_functioncallable= None(Tensor, Tensor) -> Tensor that computes pairwise
distances along the batch dimension. Defaults to the L2
(Euclidean) distance when None.marginfloat= 1.01.0.swapbool= FalseTrue, uses the triangle-inequality-based swap.
Default False.reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
distance_functioncallablemarginfloatswapboolreductionstrNotes
- anchor : .
- positive : .
- negative : .
- Output : scalar for
'mean'/'sum'; for'none'.
- Custom distance functions allow cosine distance, Mahalanobis distance, or any learned distance to be used as the training objective without changing the loss formulation.
- The
distance_functionmust return a 1-D tensor of shape — one scalar distance per sample in the batch.
Examples
Default L2 distance (equivalent to :class:`TripletMarginLoss`):
>>> import lucid
>>> import lucid.nn as nn
>>> criterion = nn.TripletMarginWithDistanceLoss(margin=1.0)
>>> anchor = lucid.tensor([[1.0, 0.0, 0.0]])
>>> positive = lucid.tensor([[1.1, 0.0, 0.0]])
>>> negative = lucid.tensor([[5.0, 0.0, 0.0]])
>>> loss = criterion(anchor, positive, negative)
Custom cosine distance:
>>> import lucid
>>> import lucid.nn as nn
>>> import lucid.nn.functional as F
>>> def cosine_dist(a: lucid.Tensor, b: lucid.Tensor) -> lucid.Tensor:
... cos_sim = F.cosine_similarity(a, b, dim=1)
... return 1.0 - cos_sim
>>> criterion = nn.TripletMarginWithDistanceLoss(
... distance_function=cosine_dist, margin=0.5
... )
>>> anchor = lucid.tensor([[1.0, 0.0]])
>>> positive = lucid.tensor([[0.9, 0.1]])
>>> negative = lucid.tensor([[0.0, 1.0]])
>>> loss = criterion(anchor, positive, negative)Methods (3)
__init__
→None__init__(distance_function: Callable[[Tensor, Tensor], Tensor] | None = None, margin: float = 1.0, swap: bool = False, reduction: str = 'mean')Initialise the TripletMarginWithDistanceLoss module. See the class docstring for parameter semantics.
forward
→Tensorforward(anchor: Tensor, positive: Tensor, negative: Tensor)Compute the loss between predictions and targets.
Parameters
anchorTensorpositiveTensornegativeTensorReturns
TensorScalar loss (or unreduced tensor depending on reduction).
extra_repr
→strextra_repr()Return a string representation of the layer's configuration.