TL;DR
A siamese network is two copies of one network that share the same weights. Each copy turns one input into a list of numbers called an embedding, and the two embeddings are compared by their distance. Small distance means the inputs are judged alike, and large distance means they are judged different. Because the network learns a way to place inputs in space, not a fixed list of answers, it can compare inputs it has never seen before.
Builds on: Contrastive Learning, Embedding Layer · Leads to: Few-Shot Learning, Sentence-BERT
Where it's used
Signature verification. In the early 1990s a group at AT&T Bell Labs used a siamese network to check whether a handwritten signature matched a stored one. A bank cannot train a classifier with one class per customer, because new customers join all the time. A siamese network instead learns what makes two signatures match, and a new customer can be enrolled by storing one reference signature.
Face verification. A phone unlock or a door check asks one question: is this face the same person as the enrolled face? This is the same pattern as signature verification. The embeddings of two photos are compared, and the answer is yes when they are close enough.
Searching sentences. Sentence-BERT, published in 2019, uses a siamese arrangement of a language model (BERT). Each sentence is embedded once, and sentences are then compared by cosine similarity. The alternative, feeding every pair of sentences through the model together as a cross-encoder, would be far slower when searching a large collection, because every new query would need a fresh pass through the model for each stored sentence.
How it works
Take a tiny encoder that turns a two-number input into a two-number embedding. For an input , the rule is . The same rule is used for both inputs. Take three inputs: , and . We know that and are similar, and that and are not. The rule for "close enough" is a distance below 1.0.
- Feed two inputs through the same network. Take the pair . Both go through the same function , with the same weights. Check: the second copy does not learn separately, so the two copies are one function.
- Encode each input. . . Check: the embeddings are lists of numbers in the same space.
- Measure the distance. The difference is . Its length, the Euclidean distance, is . Check: a small distance means the embeddings nearly coincide.
- Decide. is below the threshold , so the network says and are the same kind of input. Check: the threshold is a choice made on labelled data, not something the network decides by itself.
- Repeat for the other pair. . The difference from is , with length . Check: is above , so the network says and differ.
- Why the weights are shared. If the two copies had different weights, and could land in different places simply because they went through different functions. Their distance would then say nothing about similarity.
flowchart LR A["Input A"] --> E["Shared encoder f"] B["Input B"] --> E E --> EA["Embedding of A"] E --> EB["Embedding of B"] EA --> D["Distance between embeddings"] EB --> D D --> Y["Same or different, by threshold"]
The math
A siamese network is an encoder with parameters . Both inputs use the same . For two inputs and , the distance is
Here is the length of a vector, the Euclidean distance. The network is trained on labelled pairs. A label is 1 for a similar pair and 0 for a dissimilar pair. The contrastive loss for one pair is
where is a margin chosen in advance.
Step 2 in symbols: the encoding
Each input goes through , giving and . In the example, and .
Step 3 in symbols: the distance
The difference is . Squaring and adding gives . Taking the square root gives .
Step 4 in symbols: the decision
The decision rule is: call the pair similar if , where is a threshold. In the example .
Step 5 in symbols: the loss
The loss is small when the labels agree with the distances. For a similar pair, , so the loss is and training pulls the pair together. For a dissimilar pair, , so the loss is . It is zero once the distance is at least the margin , and training pushes the pair apart until that happens.
Because the loss is written in terms of distances, every training step changes so that the whole space is reshaped: similar inputs cluster, and dissimilar inputs spread out.
Worked examples
The encoder is , shared by both inputs. The pair is and , with label , meaning dissimilar. Use margin .
- Encode: and .
- Distance: .
- Loss: , so .
Interpretation: the two inputs are too close for a dissimilar pair, so the loss is 1 and training would push them apart.
Use the encoder and the inputs from the walkthrough, and margin .
- Pair is similar, so . The distance is and .
- The loss is . It is small, so this pair pulls only gently on the weights.
- Pair is dissimilar, so . The distance is , which is above the margin .
- The loss is .
- Decision with threshold : is judged similar, and is judged different. Both match the labels, and the loss is for the first pair and for the second.
Interpretation: the loss is small when the distances and the labels agree, and it is only the similar pair that still costs something.
A siamese encoder has turned three sentences into embeddings. The numbers are made up for this example. Cosine similarity compares the directions of two vectors, and it equals the dot product divided by the product of their lengths.
- Query: "a cat sleeps", .
- Candidate 1: "a kitten naps", .
- Candidate 2: "stock prices fell", .
- Dot product with candidate 1: .
- Lengths: and .
- Cosine: .
- Dot product with candidate 2: .
- Length of candidate 2: . Cosine: .
- Ranking: candidate 1 at comes first, and candidate 2 at comes last.
Interpretation: the search returns the kitten sentence first, because its embedding points almost the same way as the query.
Try it: a query has embedding . Which of the candidates and has the higher cosine similarity with it? Answer: the cosine with is , and with it is . So is the closer match.
Common mistakes and tradeoffs
It is tempting to think a siamese network is two different networks that happen to be compared. In fact the two branches are one network, with the same weights. That sharing is the point, because it makes the two embeddings live in the same space, and the distance between them has a meaning.
It is tempting to think the network outputs a class label. In fact it outputs an embedding, and a separate decision, a threshold on the distance, turns that into same or different. The threshold must be chosen on labelled data, and it depends on the scale of the embeddings.
It is tempting to think a fixed margin works for any model. In fact the margin is a scale choice. If the embeddings are scaled up, the same margin is too small and training stops pushing dissimilar pairs apart early.
When to use it: when there are many possible categories, when new categories appear over time, or when there are only a few examples per category. Verification and search tasks are the typical cases.
When not to use it: when there is a fixed, small set of categories with many labelled examples each. A standard classifier is simpler and often more accurate there.
Alternatives: a joint network that takes both inputs at once. It can be more accurate, because it compares the two inputs directly, but it has to run once for every pair, so it is slow for large searches. The Sentence-BERT paper is built around this tradeoff.
History
Siamese networks were introduced for handwriting and signature checking. In 1993, Bromley and colleagues at AT&T Bell Labs described a siamese time-delay network that compared two signatures, and the name comes from the two identical branches that share weights.
In 2005, Chopra, Hadsell and LeCun applied the same shared-weight idea to face verification, training the two branches with a contrastive-style loss that pulls matching pairs together and pushes others apart.
Siamese networks became common in language after 2019, when Sentence-BERT applied the shared-weight design to sentence embeddings, so that large collections of sentences could be searched by cosine similarity.
Recap
- A siamese network runs two inputs through the same encoder with shared weights.
- Each input becomes an embedding, and the distance between embeddings is the measure of similarity.
- A contrastive loss pulls similar pairs together and pushes dissimilar pairs apart until they are at least a margin away.
- The approach fits verification and search, where categories are open-ended and examples are few.
Read next: Few-Shot Learning, which uses the same idea to classify new categories from a handful of examples, and Sentence-BERT, the sentence-search application.