Skip to content

← Loss Functions step 7 of 8

Medium Primitives

Triplet Loss

Triplet loss compares three embeddings (vectors representing examples): an anchor, a related positive, and an unrelated negative. The positive and negative names describe their relationship to the anchor, not the signs of their vector entries.

This exercise uses squared Euclidean distance: subtract two vectors, square each difference, then sum over their coordinates. For each triplet, compute max(0, d_pos - d_neg + margin).

For an anchor [0, 0], positive [1, 0], and negative [2, 0], the squared distances are 1 and 4. With margin 5, the loss is max(0, 1 - 4 + 5) = 2. With margin 2, it is zero.

A triplet has zero loss once the negative's squared distance is at least margin greater than the positive's. Otherwise the loss penalizes the shortfall. Minimizing this objective encourages that separation; it does not guarantee that every triplet will satisfy it after training.

Your task

Implement triplet_loss(anchor, positive, negative, margin):

  • Each embedding tensor has shape (N, d), with N > 0 and d > 0. Corresponding rows form one triplet. Entries are floating-point values.
  • margin is a nonnegative Python float, in squared-distance units.
  • Return a scalar tensor containing the mean loss over all N triplets.

Sum squared coordinate differences along the last axis. Do not take a square root or normalize the embeddings. Clamp each triplet's loss at zero before averaging. Include zero-loss triplets in the average. For per-triplet terms [2, -4], the answer is (2 + 0) / 2 = 1.

Use this squared-distance formula directly. A library triplet loss that uses unsquared Euclidean distance will produce different values.