ArticleslgStudy

computer science

Triplet loss

Triplet loss is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Triplet loss rather than just read about it. In short: Triplet loss is a machine learning loss function widely used in one-shot learning, a setting where models are trained to generalize effectively from limited examples. It was conceived by Google researchers for their prominent FaceNet algorithm for face detection.

Triplet loss — main illustration
Triplet loss — illustration

Key takeaways

  • Triplet loss belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Triplet loss to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Triplet loss from memory before moving on to harder problems.

Reference excerpt

Triplet loss is a machine learning loss function widely used in one-shot learning, a setting where models are trained to generalize effectively from limited examples. It was conceived by Google researchers for their prominent FaceNet algorithm for face detection.

Triplet loss is designed to support metric learning. Namely, to assist training models to learn an embedding (mapping to a feature space) where similar data points are closer together and dissimilar ones are farther apart, enabling robust discrimination across varied conditions. In the context of face detection, data points correspond to images.

Definition The loss function is defined using triplets of training points of the form (A,P,N). In each triplet, A (called an "anchor point") denotes a reference point of a particular identity, P (called a "positive point") denotes another point of the same identity in point A, and N (called a "negative point") denotes a point of an identity different from the identity in point A and P. Let x be some point and let f(x) be the embedding of x in the finite-dimensional Euclidean space. It shall be assumed that the L2-norm of f(x) is unity (the L2 norm of a vector X in a finite dimensional Euclidean space is denoted by ‖X‖.) We assemble m triplets of points from the training dataset. The goal of training here is to ensure that, after learning, the following condition (called the "triplet constraint") is satisfied by all triplets (A(i),P(i),N(i)) in the training data set:

‖f(A(i))−f(P(i))‖22+α<‖f(A(i))−f(N(i))‖22 The variable α is a hyperparameter called the margin, and its value must be set manually. In the FaceNet system, its value was set as 0.2. Thus, the full form of the function to be minimized is the following:

L=∑i=1mmax⁡(‖f(A(i))−f(P(i))‖22−‖f(A(i))−f(N(i))‖22+α,0)

Intuition A baseline for understanding the effectiveness of triplet loss is the contrastive loss, which operates on pairs of samples (rather than triplets). Training with the contrastive loss pulls embeddings of similar pairs closer together, and pushes dissimilar pairs apart. Its pairwise approach is greedy, as it considers each pair in isolation. Triplet loss innovates by considering relative distances. Its goal is that the embedding of an anchor (query) point be closer to positive points than to negative points (also accounting for the margin). It does not try to further optimize the distances once this requirement is met. This is approximated by simultaneously considering two pairs (anchor-positive and anchor-negative), rather than each pair in isolation.

Triplet "mining"

One crucial implementation detail when training with triplet loss is triplet "mining", which focuses on the smart selection of triplets for optimization. This process adds an additional layer of complexity compared to contrastive loss. A naive approach to preparing training data for the triplet loss involves randomly selecting triplets from the dataset. In general, the set of valid triplets of the form (A(i),P(i),N(i)) is very large. To speed-up training convergence, it is essential to focus on challenging triplets. In the FaceNet paper, several options were explored, eventually arriving at the following. For each anchor-positive pair, the algorithm considers only semi-hard negatives. These are negatives that violate the triplet requirement (i.e, are "hard"), but lie farther from the anchor than the positive (not too hard). Restated, for each A(i) and P(i), they seek N(i) such that:

The rationale for this design choice is heuristic. It may appear puzzling that the mining process neglects "very hard" negatives (i.e., closer to the anchor than the positive). Experiments conducted by the FaceNet designers found that this often leads to a convergence to degenerate local minima. Triplet mining is performed at each training step, from within the sample points contained in the training batch (this is known as online mining), after embeddings were computed for all points in the batch. While ideally the entire dataset could be used, this is impractical in general. To support a large search space for triplets, the FaceNet authors used very large batches (1800 samples). Batches are constructed by selecting a large number of same-category sample points (40), and randomly selected negatives for them.

Extensions Triplet loss has been extended to simultaneously maintain a series of distance orders by optimizing a continuous relevance degree with a chain (i.e., ladder) of distance inequalities. This leads to the Ladder Loss, which has been demonstrated to offer performance enhancements of visual-semantic embedding in learning to rank tasks. In Natural Language Processing, triplet loss is one of the loss functions considered for BERT fine-tuning in the SBERT architecture. Other extensions involve specifying multiple negatives (multiple negatives ranking loss).

See also Siamese neural network t-distributed stochastic neighbor embedding Similarity learning

References

Illustrations

Triplet loss: The triplet loss function minimizes the distance between an anchor and a positive, both of which have the same identity, and maximizes the distance between the anchor and a negative of a different identity.
The triplet loss function minimizes the distance between an anchor and a positive, both of which have the same identity, and maximizes the distance between the anchor and a negative of a different identity.
Triplet loss: Triplet mining - various options for selecting the negative N(i) given an anchor A(i) and a positive P(i).  The very-hard and semi-hard negatives violate the triplet requirement, and so we would like the optimizer to push their embeddings farther away from the anchor.
Triplet mining - various options for selecting the negative N(i) given an anchor A(i) and a positive P(i). The very-hard and semi-hard negatives violate the triplet requirement, and so we would like the optimizer to push their embeddings farther away from the anchor.

Worked examples

Example 1 — a first encounter with Triplet loss

Start with the simplest possible case. Write down what Triplet loss claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Triplet loss before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Triplet loss ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Triplet loss

In research
Triplet loss appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Triplet loss in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Triplet loss is common in secondary-school and first-year university syllabi. It links to neighbouring topics Artificial neural networks, Machine learning algorithms, so understanding it makes those chapters shorter.
In everyday life
Look for Triplet loss outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Triplet loss” →

How to study Triplet loss in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Triplet loss means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Triplet loss out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Triplet loss in simple terms?

Triplet loss is a machine learning loss function widely used in one-shot learning, a setting where models are trained to generalize effectively from limited examples. It was conceived by Google researchers for their prominent FaceNet algorithm for face detection.

Why does Triplet loss matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Triplet loss?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Triplet loss.

Tags

  • Artificial neural networks
  • Machine learning algorithms

Keep exploring