Siamese networks
孪生网络
Differentiate both shared branches, train pair comparisons and build a version-aware cached gallery.
siamese-networksStart 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:
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:
Let . The two embedding gradients are opposite, but their parameter gradients do not generally cancel: the inputs and activation derivatives differ. For one pair:
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 storage for d-dimensional features. A brute-force query then requires one encoder pass plus 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
- 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.
- Does swapping pair endpoints change this score?
Answer 2: No. Squared distance is symmetric, and the encoder weights are tied.
- 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.
- 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?
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
- Signature Verification using a “Siamese” Time Delay Neural Network
Jane Bromley; Isabelle Guyon; Yann LeCun; Eduard Säckinger; Roopak Shah · 1993 - 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:
- Signature Verification using a “Siamese” Time Delay Neural Network · Physical page 4: all weights learned with both subnetworks constrained identical; original signature comparison scope.
- Siamese Neural Networks for One-shot Image Recognition · Physical pages 1 and 3: one-shot task, shared-image encoders, weighted absolute difference, sigmoid and binary cross-entropy.
Related topics