class
TripletMarginWithDistanceLoss
extends
ModuleTripletMarginWithDistanceLoss(distance_function: Callable[[Tensor, Tensor], Tensor] | None = None, margin: float = 1.0, swap: bool = False, reduction: Reduction = '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= NoneA function
(Tensor, Tensor) -> Tensor that computes pairwise
distances along the batch dimension. Defaults to the L2
(Euclidean) distance when None.marginfloat= 1.0Minimum required distance gap. Default
1.0.swapbool= FalseIf
True, uses the triangle-inequality-based swap.
Default False.reductionstr= 'mean''none' | 'mean' (default) | 'sum'.Attributes
distance_functioncallableThe distance function in use.
marginfloatThe margin threshold.
swapboolWhether the swap heuristic is active.
reductionstrThe reduction mode.
Notes
- 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 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)Used by 1
Constructors
1Instance methods
2Return a string representation of the layer's configuration.