AI Wiki中文/EN

Siamese networks

孪生网络

Differentiate both shared branches, train pair comparisons and build a version-aware cached gallery.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Suppose a catalogue receives a new item with only one reference image. A classifier with a fixed output class for every old item cannot automatically add this one. A pair-comparison system can instead ask how similar a query is to each reference, using the same encoder on both sides.

A Siamese network ties the encoder weights across two inputs. The 1993 signature-verification paper by Bromley and colleagues explicitly constrained the two subnetworks to be identical while training their weights. Koch, Zemel and Salakhutdinov later studied a Siamese image-comparison model for one-shot recognition. These are architectural and training precedents, not evidence that any shared encoder will generalize from one image. Signature Verification using a “Siamese” Time Delay Neural Network; Siamese Neural Networks for One-shot Image Recognition

We will fit same/different labels on six pairs, differentiate both uses of the shared weights, and reuse cached reference embeddings. The example’s reference and query points already participated in training; its final lookup is a cache check, not an unseen-class one-shot benchmark.

Definitions and derivation

Our encoder is a small tanh map. A symmetric score uses squared embedding distance and a learned bias. The sigmoid converts it to a same-object probability:

hi=tanh⁡(xiW),sij=b−∥hi−hj∥2,pij=11+e−sij.h_i=\tanh(x_iW),\qquad s_{ij}=b-\|h_i-h_j\|^2,\qquad p_{ij}=\frac1{1+e^{-s_{ij}}}.

For labels y equal to one for matching pairs and zero otherwise, binary cross-entropy can be evaluated stably with a log-sum-exp operation:

ℓij=log⁡(1+esij)−yijsij,eij=∂ℓij∂sij=pij−yij.\ell_{ij}=\log(1+e^{s_{ij}})-y_{ij}s_{ij},\qquad e_{ij}=\frac{\partial\ell_{ij}}{\partial s_{ij}}=p_{ij}-y_{ij}.

Let δ=hi−hj\delta=h_i-h_j. The two embedding gradients are opposite, but their parameter gradients do not generally cancel: the inputs and activation derivatives differ. For one pair:

gi=−2eijδ,gj=2eijδ,∇Wℓij=xi⊤[gi⊙(1−hi2)]+xj⊤[gj⊙(1−hj2)],∂bℓij=eij. g_i=-2e_{ij}\delta,\quad g_j=2e_{ij}\delta,\qquad \nabla_W\ell_{ij}=x_i^\top[g_i\odot(1-h_i^2)]+x_j^\top[g_j\odot(1-h_j^2)],\quad \partial_b\ell_{ij}=e_{ij}.

Accumulate these contributions for every appearance of an example, then average over the six pairs. Updating only one endpoint misses part of the derivative of a tied-weight network. The original signature model used a different comparison, and Koch’s model used a weighted absolute difference followed by a sigmoid; our squared-distance score is an explicitly different teaching choice. Weight sharing is the common architectural idea. Signature Verification using a “Siamese” Time Delay Neural Network; Siamese Neural Networks for One-shot Image Recognition

Run the calculation

Run CPython 3.12.4 with NumPy 1.26.4. Four two-dimensional observations generate two positive and four negative pairs. Four encoder weights and one comparison bias are optimized for 500 steps at rate 0.1. Mean BCE falls from 0.483131089 to 0.035118413. Positive-pair probabilities are about 0.922, while negative pairs are near 0.012. Cached references are observations 0 and 2; queries are observations 1 and 3. The nearest support indices are 0 and 1.

import numpy as np

X=np.array([[1.,.3],[1,-.3],[-1,.4],[-1,-.4]])
PAIRS=[(0,1,1),(2,3,1),(0,2,0),(0,3,0),(1,2,0),(1,3,0)]


def objective(theta):
    w=theta[:4].reshape(2,2);bias=theta[4];h=np.tanh(X@w);gh=np.zeros_like(h);gb=0.;loss=0.;probability=[]
    for i,j,label in PAIRS:
        delta=h[i]-h[j];score=bias-delta@delta;p=float(np.exp(-np.logaddexp(0,-score)));loss+=np.logaddexp(0,score)-label*score;error=p-label;g=-2*error*delta;gh[i]+=g;gh[j]-=g;gb+=error;probability.append(p)
    gw=X.T@(gh*(1-h*h));count=len(PAIRS)
    return float(loss/count),np.r_[gw.ravel(),gb]/count,np.array(probability)


def initial():return np.r_[np.array([[.5,.1],[-.2,.7]]).ravel(),0.]


def train():
    t=initial();start=objective(t)[0]
    for _ in range(500):t-=.1*objective(t)[1]
    return t,start,objective(t)


if __name__=='__main__':
    t,start,(end,g,p)=train();print('pair BCE before/after',round(start,9),round(end,9),'same-object probabilities',p.round(9).tolist());print('shared encoder weights',t[:4].reshape(2,2).round(9).tolist(),'comparison bias',round(t[4],9))
    w=t[:4].reshape(2,2);gallery=np.tanh(X[[0,2]]@w);queries=np.tanh(X[[1,3]]@w);distance=np.sum((queries[:,None,:]-gallery[None,:,:])**2,axis=2);print('cached-gallery distances',distance.round(9).tolist(),'nearest support indices',distance.argmin(axis=1).tolist())
pair BCE before/after 0.483131089 0.035118413 same-object probabilities [0.921985609, 0.921951843, 0.012064654, 0.011405923, 0.012564497, 0.011897596]
shared encoder weights [[1.751747889, 1.554688824], [-0.152369727, 0.225282831]] comparison bias 2.4702353
cached-gallery distances [[0.000598995, 6.834471353], [6.932386352, 0.001068341]] nearest support indices [0, 1]

When the method fails

Tied weights do not guarantee informative embeddings. If all inputs collapse to one embedding, every pair receives the same score b; the model cannot distinguish positive from negative pairs. Likewise, a pair score is not automatically a metric: probabilities generally have neither a zero self-distance nor a triangle inequality.

To evaluate one-shot recognition, separate training classes from evaluation classes, construct support/query episodes and report the number of candidate classes and examples per support class. Randomly splitting overlapping pairs can leak the same entity or image across the boundary. Koch’s one-shot setting motivates this distinction; our cached lookup deliberately makes no such evaluation claim. Siamese Neural Networks for One-shot Image Recognition

Caching M reference embeddings costs O(Md)O(Md) storage for d-dimensional features. A brute-force query then requires one encoder pass plus O(Md)O(Md) comparisons. Caches must be rebuilt or versioned when encoder weights or preprocessing change. Sharing architecture alone is insufficient: the two branches must use the same actual parameters and compatible preprocessing.

Exercises with answers

  1. Do opposite embedding gradients imply a zero shared-weight gradient?

Answer 1: No. Each is multiplied by a different input and activation derivative before summation.

  1. Does swapping pair endpoints change this score?

Answer 2: No. Squared distance is symmetric, and the encoder weights are tied.

  1. What breaks a cached gallery after a model update?

Answer 3: Old reference vectors and new query vectors no longer necessarily occupy the same learned coordinate system.

  1. Why is this lookup not an unseen-class result?

Answer 4: All four observations contributed training pairs; no evaluation classes were held out.

Sources and next steps

Read the tied-subnetwork description in the 1993 signature paper, then compare Koch’s weighted-L1 pair classifier with this squared-distance head. Continue with triplet loss: shared encoders can support pair BCE, contrastive objectives or ranking losses. “Siamese” specifies parameter sharing, not one mandatory loss function. Signature Verification using a “Siamese” Time Delay Neural Network; Siamese Neural Networks for One-shot Image Recognition

Make a prediction, then check

Which definition best describes a Siamese encoder?

Choose one answer

Learning objectives

  • Sum gradients through both uses of a tied encoder.
  • Distinguish cached comparison from genuine unseen-class one-shot evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. Signature Verification using a “Siamese” Time Delay Neural Network
    Jane Bromley; Isabelle Guyon; Yann LeCun; Eduard Säckinger; Roopak Shah · 1993
  2. Siamese Neural Networks for One-shot Image Recognition
    Gregory Koch; Richard Zemel; Ruslan Salakhutdinov · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter: finite-difference gradients, sample covariance, teacher/center update order, hidden-input isolation, independent least squares, PSD projection, margin feasibility, tied-branch derivatives and transported factor actions as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; teaching calculations, not image benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.