TRIPLET#

Functions#

utils.triplet.batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft')[source]#

Build the triplet loss over a batch of embeddings.

For each anchor, get the hardest positive and hardest negative to compute the triplet loss.

Parameters:
  • labels – labels of the batch, of shape (batch_size,)

  • embeddings – tensor of shape (batch_size, embed_dim)

  • k – number of negatives to consider

  • margin – margin for triplet loss

  • margin_type – ‘soft’ or ‘hard’. If ‘soft’, the loss is log(1 + exp(positives - negatives + margin)). If ‘hard’, the loss is max(0, positives - negatives + margin).

Returns:

scalar tensor containing the triplet loss

Return type:

torch.Tensor

utils.triplet.negative_only_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft')[source]#

Variant of the triplet loss, computed only to separate the hardest negatives.

See batch_hard_triplet_loss for details.

Parameters:
  • labels – labels of the batch, of shape (batch_size,)

  • embeddings – tensor of shape (batch_size, embed_dim)

  • k – number of negatives to consider

  • margin – margin for triplet loss

  • margin_type – ‘soft’ or ‘hard’. If ‘soft’, the loss is log(1 + exp(positives - negatives + margin)). If ‘hard’, the loss is max(0, positives - negatives + margin).

Returns:

scalar tensor containing the triplet loss

Return type:

torch.Tensor