Sign in

Siamese

Siamese network (triplet metric learning)

A network that maps inputs to points in an embedding space so that items of the same class end up close together and items of different classes end up far apart.

Overview

A classifier needs a fixed list of classes. Some problems have no such list: you may need to tell whether two face photos show the same person, including people never seen in training. A Siamese network learns a notion of distance instead. One encoder turns any input into a short vector, and the same encoder with the same weights is applied to every input being compared. Training shows it examples that should be near each other and examples that should be far apart, and adjusts the encoder until the distances agree. Afterwards, comparing two items is a matter of measuring the distance between their vectors.

A short history

Jane Bromley, Yann LeCun and colleagues at Bell Labs introduced the Siamese network in 1993 to verify signatures: two copies of one network embed two signatures, and the distance between the embeddings decides whether they match. Sumit Chopra, Raia Hadsell and LeCun added the contrastive loss in 2005. In 2015 FaceNet from Google popularised the triplet loss, training on an anchor, a matching example and a non-matching example.

How it works

  1. The encoder maps an input to an embedding: z=tanh⁡(xW1+b1)W2+b2\mathbf{z} = \tanh(\mathbf{x} W_1 + \mathbf{b}_1) W_2 + \mathbf{b}_2.
  2. At each step, sample a batch of triplets from the labelled data: an anchor, a positive with the same label, and a negative with a different label.
  3. Stack all the inputs into one batch and encode them with the same weights.
  4. With the triplet loss, penalise any triplet in which the anchor is not closer to the positive than to the negative by at least the margin, in squared distance.
  5. With the contrastive loss, pull same-class pairs together and push different-class pairs apart until they are at least the margin away.
  6. Add up the gradients from every branch in the shared weights and update with Adam.

Watch out for

  • The encoder can map every input to the same point. All distances are then zero and the triplet loss sits at the margin with no useful gradient. This is called collapse, and a large lr makes it more likely.
  • Most random triplets are already satisfied after a short while and contribute zero gradient, so learning slows. This template samples at random and does no hard-example mining.
  • The margin is measured on raw embeddings that are not normalised, so the network can meet it simply by scaling all its outputs up. Compare margins only at a fixed embedding scale.
  • The triplet loss here uses squared distances and the contrastive loss uses plain distances, so the same margin value means different things in the two.

Use cases

When to use it

Verification and retrieval problems where new classes appear after training and each has few examples: face or signature matching, duplicate detection, finding similar items.

In industry

Identity verification
Face verification: comparing the embedding of a live photo with that of an identity document photo.
Banking
Signature verification, the original use, comparing a new signature against stored genuine ones.
E-commerce
Visual search and duplicate listing detection by finding products whose image embeddings are close.

Choosing it: what must hold

  • Labels that say which items belong together, as classes or as matching pairs.
  • Many classes with few examples each, or classes that will be added after training.
  • A strategy for choosing informative pairs or triplets, since most random ones are too easy to teach anything.

When to choose something else

IfUse instead
The set of classes is fixed and each has many examplesAn ordinary classifier such as a CNN or ResNet with a softmax output
You are matching two different kinds of thing, such as users and itemsA two-tower model
You have no labelsAn autoencoder, or self-supervised contrastive learning

Math foundations

  1. The shared encoder

    z=f(x)=tanh⁡ ⁣(xW1+b1)W2+b2\mathbf{z} = f(\mathbf{x}) = \tanh\!\left(\mathbf{x} W_1 + \mathbf{b}_1\right) W_2 + \mathbf{b}_2

    One function, applied with the same weights to every input. Sharing the weights is what guarantees that two identical inputs get identical embeddings.

  2. Distance in embedding space

    d(x,x′)=∥f(x)−f(x′)∥2d(\mathbf{x}, \mathbf{x}') = \lVert f(\mathbf{x}) - f(\mathbf{x}') \rVert_2

    The Euclidean distance between two embeddings. The whole aim of training is to make this distance small for like items and large for unlike ones.

  3. Triplet loss

    Ltri=max⁡ ⁣(0,  ∥a−p∥2−∥a−n∥2+m)L_{\text{tri}} = \max\!\left(0,\; \lVert \mathbf{a} - \mathbf{p} \rVert^2 - \lVert \mathbf{a} - \mathbf{n} \rVert^2 + m\right)

    Zero once the negative is farther from the anchor than the positive by at least the margin mm, in squared distance. Satisfied triplets are left alone.

  4. Triplet gradients

    ∂Ltri∂a=2(n−p),∂Ltri∂p=−2(a−p),∂Ltri∂n=2(a−n)\frac{\partial L_{\text{tri}}}{\partial \mathbf{a}} = 2(\mathbf{n} - \mathbf{p}), \qquad \frac{\partial L_{\text{tri}}}{\partial \mathbf{p}} = -2(\mathbf{a} - \mathbf{p}), \qquad \frac{\partial L_{\text{tri}}}{\partial \mathbf{n}} = 2(\mathbf{a} - \mathbf{n})

    These hold when the loss is positive, and all three are zero otherwise. A descent step moves the positive toward the anchor and the negative away from it.

  5. Contrastive loss

    Lcon=s⋅12d2+(1−s)⋅12max⁡(0,  m−d)2L_{\text{con}} = s \cdot \tfrac{1}{2} d^2 + (1 - s) \cdot \tfrac{1}{2} \max(0,\; m - d)^2

    For a pair with distance dd. A same-class pair (s=1s = 1) is pulled together like a spring. A different-class pair (s=0s = 0) is pushed apart only while it is closer than the margin.

Symbols

x\mathbf{x}
an input row
ff
the encoder
W1,b1,W2,b2W_1, \mathbf{b}_1, W_2, \mathbf{b}_2
hidden and output parameters of the encoder
z\mathbf{z}
embedding of an input
a,p,n\mathbf{a}, \mathbf{p}, \mathbf{n}
embeddings of the anchor, the positive and the negative
dd
Euclidean distance between two embeddings
mm
the margin
ss
1 if a pair shares a class, 0 otherwise

Worked by hand

Embeddings in two dimensions with margin m=1m = 1: anchor a=(0,0)\mathbf{a} = (0, 0), positive p=(1,0)\mathbf{p} = (1, 0). Compare a near negative n=(0,1)\mathbf{n} = (0, 1) with a far negative n′=(0,2)\mathbf{n}' = (0, 2).

∥a−p∥2=1,∥a−n∥2=1,∥a−n′∥2=4\lVert \mathbf{a} - \mathbf{p} \rVert^2 = 1, \qquad \lVert \mathbf{a} - \mathbf{n} \rVert^2 = 1, \qquad \lVert \mathbf{a} - \mathbf{n}' \rVert^2 = 4
L(n)=max⁡(0,  1−1+1)=1L(\mathbf{n}) = \max(0,\; 1 - 1 + 1) = 1
L(n′)=max⁡(0,  1−4+1)=0L(\mathbf{n}') = \max(0,\; 1 - 4 + 1) = 0
∂L(n)∂n=2(a−n)=(0,  −2)\frac{\partial L(\mathbf{n})}{\partial \mathbf{n}} = 2(\mathbf{a} - \mathbf{n}) = (0,\; -2)

The near negative costs 1 and its gradient points down, so a descent step moves it up, away from the anchor. The far negative already clears the margin and produces no loss and no gradient.

Visual example

Loading the example.

Try this

  • Press Run and watch the three rings separate in the embedding space.
  • Click a point to make it the anchor, then click Loss in the diagram to see whether its hardest triplet is satisfied.
  • Start again with the margin at 3 and compare how far the embedding panel spans.

Code sample

import numpy as np
from impl import Siamese
from config import SiameseConfig

rng = np.random.default_rng(0)
labels = rng.integers(0, 3, size=300)
signal = np.array([[0.0, 2.0], [-2.0, -1.0], [2.0, -1.0]])[labels] + 0.3 * rng.normal(size=(300, 2))
X = np.hstack([signal, 5.0 * rng.normal(size=(300, 6))])   # 2 useful features hidden among 6 loud noise features

model = Siamese(SiameseConfig(loss="triplet", steps=500)).fit(X, labels)
Z = model.embed(X)                                         # (300, 8)
same = labels[:, None] == labels[None, :]
D = model.pairwise_distance(X, X)                          # (300, 300)
print(D[same].mean(), D[~same].mean())                     # same-class pairs are much closer
Read the implementation (155 lines)
"""Siamese network for metric learning with triplet or contrastive loss, manual backpropagation and Adam.

NumPy only. The encoder is embed(x) = tanh(x W1 + b1) W2 + b2. Every input of a pair or triplet goes through
the same weights: the inputs are stacked into one batch, encoded once, and the gradients from all branches add
up in the shared parameters.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import SiameseConfig
except ImportError:  # run from the template's own folder
    from config import SiameseConfig


class _Adam:
    """Adam optimizer over a dict of NumPy arrays; `step` updates the arrays in place."""

    def __init__(self, params: dict, lr: float, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.params, self.lr, self.beta1, self.beta2, self.eps = params, lr, beta1, beta2, eps
        self.m = {k: np.zeros_like(v) for k, v in params.items()}
        self.v = {k: np.zeros_like(v) for k, v in params.items()}
        self.t = 0

    def step(self, grads: dict) -> None:
        """Apply one update. grads: same keys and shapes as the parameters."""
        self.t += 1
        for k, g in grads.items():
            self.m[k] = self.beta1 * self.m[k] + (1 - self.beta1) * g
            self.v[k] = self.beta2 * self.v[k] + (1 - self.beta2) * g * g
            m_hat = self.m[k] / (1 - self.beta1**self.t)
            v_hat = self.v[k] / (1 - self.beta2**self.t)
            self.params[k] -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)

class Siamese:
    """Shared-encoder metric learner. After `fit`: `params`, `loss_history_` (loss at every step)."""

    def __init__(self, config: SiameseConfig | None = None) -> None:
        self.config = config or SiameseConfig()
        self.params: dict[str, np.ndarray] = {}
        self.loss_history_: list[float] = []

    def initialize(self, n_features: int) -> None:
        """Create the encoder weights for inputs with `n_features` columns."""
        rng = np.random.default_rng(self.config.seed)
        h, e = self.config.hidden_dim, self.config.embed_dim
        self.params = {
            "W1": np.sqrt(1.0 / n_features) * rng.normal(size=(n_features, h)),
            "b1": np.zeros(h),
            "W2": np.sqrt(1.0 / h) * rng.normal(size=(h, e)),
            "b2": np.zeros(e),
        }

    def embed(self, X: np.ndarray) -> np.ndarray:
        """Encode inputs. X: (n, d). Returns embeddings of shape (n, embed_dim)."""
        if not self.params:
            raise RuntimeError("call fit (or initialize) before embedding")
        p = self.params
        return np.tanh(np.asarray(X, dtype=float) @ p["W1"] + p["b1"]) @ p["W2"] + p["b2"]

    def _backward(self, X: np.ndarray, dZ: np.ndarray) -> dict:
        """Gradients of the encoder weights given dZ = d loss / d embed(X). X: (n, d). dZ: (n, embed_dim)."""
        p = self.params
        hidden = np.tanh(X @ p["W1"] + p["b1"])
        d_hidden = (dZ @ p["W2"].T) * (1.0 - hidden**2)
        return {"W1": X.T @ d_hidden, "b1": d_hidden.sum(axis=0), "W2": hidden.T @ dZ, "b2": dZ.sum(axis=0)}

    def triplet_loss_and_grads(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray) -> tuple[float, dict]:
        """Mean of max(0, ||a - p||^2 - ||a - n||^2 + margin) and its gradients.

        anchor, positive, negative: inputs of shape (n, d); row i of each forms one triplet.
        """
        n = len(anchor)
        X = np.vstack([anchor, positive, negative])
        Z = self.embed(X)
        a, p, q = Z[:n], Z[n : 2 * n], Z[2 * n :]
        violation = np.sum((a - p) ** 2, axis=1) - np.sum((a - q) ** 2, axis=1) + self.config.margin
        active = (violation > 0)[:, None] / n
        dZ = np.vstack([2.0 * (q - p) * active, -2.0 * (a - p) * active, 2.0 * (a - q) * active])
        return float(np.mean(np.maximum(violation, 0.0))), self._backward(X, dZ)

    def contrastive_loss_and_grads(self, left: np.ndarray, right: np.ndarray, same: np.ndarray) -> tuple[float, dict]:
        """Mean of same * 0.5 d^2 + (1 - same) * 0.5 max(0, margin - d)^2 and its gradients.

        left, right: inputs of shape (n, d); row i of each forms one pair. same: (n,), 1 for same class, else 0.
        """
        n = len(left)
        same = np.asarray(same, dtype=float)
        X = np.vstack([left, right])
        Z = self.embed(X)
        diff = Z[:n] - Z[n:]
        dist = np.sqrt(np.sum(diff**2, axis=1) + 1e-12)
        short = np.maximum(self.config.margin - dist, 0.0)
        loss = np.mean(same * 0.5 * dist**2 + (1.0 - same) * 0.5 * short**2)
        # d loss / d dist, then d dist / d diff = diff / dist
        d_dist = (same * dist - (1.0 - same) * short) / n
        d_diff = (d_dist / dist)[:, None] * diff
        return float(loss), self._backward(X, np.vstack([d_diff, -d_diff]))

    def sample_triplets(self, labels: np.ndarray, rng: np.random.Generator, size: int) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        """Random row indices (anchor, positive, negative), each of shape (size,).

        The positive shares the anchor's label (and is a different row when the class has more than one row);
        the negative has another label.
        """
        anchors = rng.integers(0, len(labels), size=size)
        positives = np.empty(size, dtype=int)
        negatives = np.empty(size, dtype=int)
        for i, a in enumerate(anchors):
            same = np.flatnonzero(labels == labels[a])
            others = same[same != a]
            positives[i] = rng.choice(others) if len(others) else a
            negatives[i] = rng.choice(np.flatnonzero(labels != labels[a]))
        return anchors, positives, negatives

    def fit(self, X: np.ndarray, labels: np.ndarray) -> "Siamese":
        """Train on labelled rows by sampling triplets (or pairs) at every step.

        X: inputs, shape (n, d). labels: class of each row, shape (n,), at least two classes.
        """
        cfg = self.config
        X = np.asarray(X, dtype=float)
        labels = np.asarray(labels)
        if X.ndim != 2 or len(X) != len(labels):
            raise ValueError("X must have shape (n, d) and labels must have n entries")
        if len(np.unique(labels)) < 2:
            raise ValueError("labels must hold at least two classes")
        self.initialize(X.shape[1])
        optimizer = _Adam(self.params, cfg.lr)
        rng = np.random.default_rng(cfg.seed + 1)
        self.loss_history_ = []
        for _ in range(cfg.steps):
            a, p, q = self.sample_triplets(labels, rng, cfg.batch_size)
            if cfg.loss == "triplet":
                loss, grads = self.triplet_loss_and_grads(X[a], X[p], X[q])
            else:
                # First half of the batch: same-class pairs. Second half: different-class pairs.
                half = cfg.batch_size // 2 or 1
                right = np.concatenate([p[:half], q[half:]])
                same = np.concatenate([np.ones(half), np.zeros(cfg.batch_size - half)])
                loss, grads = self.contrastive_loss_and_grads(X[a], X[right], same)
            optimizer.step(grads)
            self.loss_history_.append(loss)
        return self

    def distance(self, left: np.ndarray, right: np.ndarray) -> np.ndarray:
        """Euclidean distance between the embeddings of paired rows. left, right: (n, d). Returns (n,)."""
        return np.sqrt(np.sum((self.embed(left) - self.embed(right)) ** 2, axis=1))

    def pairwise_distance(self, A: np.ndarray, B: np.ndarray) -> np.ndarray:
        """Euclidean distance between every embedded row of A (n, d) and of B (m, d). Returns (n, m)."""
        za, zb = self.embed(A), self.embed(B)
        sq = (za**2).sum(axis=1)[:, None] + (zb**2).sum(axis=1)[None, :] - 2.0 * za @ zb.T
        return np.sqrt(np.maximum(sq, 0.0))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Create three clusters of points in ten dimensions, with a class label per cluster. Fit Siamese with SiameseConfig loss set to triplet and embed_dim 2, then call embed and plot the result coloured by label. Use pairwise_distance to compare the average distance within a class with the average distance between classes, before and after training.

Check on learning

  1. Why must the two branches share exactly the same weights? What could go wrong if each input had its own encoder?
    A way to think about it

    Feed the same input to both branches. With separate encoders the distance between an item and itself need not be zero.

  2. The triplet loss only compares distances. It never says how far apart classes should be in absolute terms. What freedom does that leave the network?
    A way to think about it

    Scale all embeddings by 10 and see what happens to the difference of squared distances relative to a fixed margin.

  3. After some training most triplets give zero loss, yet retrieval quality is still poor. What kind of triplets are still informative, and how would you find them?
    A way to think about it

    A triplet teaches something only when the negative is close to the anchor. Think about picking, within a batch, the negatives nearest each anchor.

  4. For a new class with five examples, how would you classify with this model without retraining, and why can a softmax classifier not do the same?
    A way to think about it

    Embed the five examples and compare a new item's distance to them. A softmax layer has one fixed output per class it was trained on.