Capsule networks: agreement changes the route
胶囊网络
Compute routing by agreement, check the softmax axis and squash function, and distinguish capsule lengths from calibrated probabilities.
capsule-networksStart with the problem
A detector may say that an eye is present; a richer detector might also describe where it is and how it is oriented. Capsules organize several outputs into a vector intended to describe an entity and its instantiation. Lower capsules can then predict the state of a possible parent, such as a face, and compare their predictions.
Transforming Auto-encoders develops the representation idea with transformed image pairs. Dynamic Routing Between Capsules gives an iterative agreement mechanism. We calculate that routing with explicit fixed votes. No image network or learned pose representation is hidden inside the example.
Definitions and derivation
A lower capsule i produces vector uᵢ. A learned transformation Wᵢⱼ can turn it into a prediction for upper capsule j. For this routing-only example those predictions, or votes, are supplied directly:
Softmax runs over candidate parents j for each lower capsule i. Each lower capsule distributes unit mass across parents. It does not normalize incoming children for each parent. Our array layout is lower×upper×dimension. Initialize routing logits to zero, giving uniform parent coefficients.
Compress each parent sum with the squash nonlinearity and update logits by agreement:
For a sum of length r, the output length is r²/(1+r²), always below one for finite r. Direction is preserved for nonzero inputs. The zero case is explicitly defined to avoid division by zero. Agreement is a dot product, so its magnitude depends on both direction and vector lengths.
Each round recomputes coefficients from the accumulated logits, forms sums and squashes them. We omit the final logit update because no subsequent round consumes it; the returned vector is unchanged from the source algorithm. Routing iterations infer couplings for one input. They are not gradient-descent updates of the transformation matrices.
The paper’s separate class margin loss uses capsule lengths:
Tₖ indicates whether class k is present. The example uses one positive label, though the independent class terms can support multiple present entities. Lengths do not sum to one across classes. Interpreting them as existence scores does not prove probability calibration. The margin loss is also distinct from the routing softmax: one scores outputs, the other assigns lower capsules to parents.
Run the calculation
Complete Python 3.12 / NumPy 1.26.4 calculation:
import numpy as np
def squash(s):
s=np.asarray(s,dtype=float);norm=np.linalg.norm(s,axis=-1,keepdims=True)
scale=np.divide(norm,1+norm**2,out=np.zeros_like(norm),where=norm>0)
return scale*s
def route(votes,rounds=3):
u=np.asarray(votes,dtype=float)
if u.ndim != 3 or not all(1 <= n <= 8 for n in u.shape) or not np.isfinite(u).all() or np.max(np.abs(u))>10 or type(rounds) is not int or not 1 <= rounds <= 8:
raise ValueError('Use bounded lower-by-upper-by-dimension votes and 1..8 rounds.')
logits=np.zeros(u.shape[:2]);trace=[]
for step in range(rounds):
probability=np.exp(logits-logits.max(axis=1,keepdims=True));probability/=probability.sum(axis=1,keepdims=True)
output=squash(np.sum(probability[:,:,None]*u,axis=0));trace.append(probability.copy())
if step+1<rounds:logits+=np.sum(u*output[None,:,:],axis=2)
return output,probability,trace
def margin_loss(output,label):
length=np.linalg.norm(output,axis=1);positive=np.arange(len(length))==label
return float(np.sum(positive*np.maximum(.9-length,0)**2+.5*(~positive)*np.maximum(length-.1,0)**2))
def example():return np.array([[[1.,0],[0,.2]],[[.8,.1],[0,-.2]],[[.9,-.1],[.1,0]]])
if __name__ == '__main__':
for rounds in (1,3):
v,c,_=route(example(),rounds);print('rounds',rounds,'couplings',c.round(9).tolist(),'lengths',np.linalg.norm(v,axis=1).round(9).tolist(),'label-0 margin loss',round(margin_loss(v,0),9))
print('squash zero / (3,4)',squash(np.array([[0.,0],[3,4]])).round(9).tolist())
Actual output:
rounds 1 couplings [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] lengths [0.645704163, 0.002493766] label-0 margin loss 0.064666373
rounds 3 couplings [[0.801584167, 0.198415833], [0.753401679, 0.246598321], [0.778379651, 0.221620349]] lengths [0.815851094, 0.000583677] label-0 margin loss 0.007081038
squash zero / (3,4) [[0.0, 0.0], [0.576923077, 0.769230769]]
Three lower capsules vote mainly along the same direction for parent 0. After one round its length is about 0.64570; after three rounds it is about 0.81585. Its incoming coefficients become roughly 0.80158, 0.75340 and 0.77838. These do not sum to one, because the normalization is along each lower capsule’s parent choices. Parent 1’s inconsistent small votes largely cancel.
The class-0 margin loss decreases in this particular example, but routing is not guaranteed to minimize that loss monotonically for arbitrary inputs. We have not trained any parameters. For I lower capsules, J parents, D vote dimensions and R rounds, routing costs O(RIJD) and stores O(IJD) votes plus logits. Producing votes with full learned matrices has its own cost.
When the method fails
A vector output does not automatically encode pose, nor does agreement automatically establish geometric equivariance. Those claims depend on the representation, transformations and training data. Our fixed votes test the routing mechanics alone.
Large vote magnitudes can dominate agreement, and repeated routing adds compute. Zero or conflicting votes can leave little evidence for a parent. Compare a capsule architecture against a strong simpler baseline under matched training and evaluation conditions; the historical papers’ particular results do not imply universal superiority to convolution or attention.
Exercises with answers
- Along which axis is routing softmax applied?
Answer 1: Across upper capsules for each lower capsule, so each lower row sums to one.
- What does squash do to (3,4)?
Answer 2: Its input length is five; the result is (15/26,20/26), of length 25/26.
- Why omit the last agreement update in the code?
Answer 3: No later softmax uses those logits, so the returned capsules are identical.
- Do output lengths form a calibrated categorical distribution?
Answer 4: No. They need not sum to one, and calibration is an empirical property not supplied by squash.
Sources and next steps
Sabour and colleagues’ physical pages 2–3 provide squash, votes, routing softmax, Procedure 1 and the margin loss. The earlier transforming-autoencoder paper’s physical pages 1–2 explain vector-valued instantiation parameters and transformed-pair supervision. Our numeric votes are original. Compare equivariant networks for an explicit symmetry proof, and mixture of experts for a different meaning of routing.
Make a prediction, then check
Which sums to one during routing?
Learning objectives
- Implement routing with the correct normalization axis.
- Separate iterative inference, training loss and geometric claims.
Prerequisites & connections
Explore related knowledge →References
- Dynamic Routing Between Capsules — arXiv v2
Sara Sabour; Nicholas Frosst; Geoffrey E. Hinton · 2017 - Transforming Auto-encoders
Geoffrey E. Hinton; Alex Krizhevsky; Sida D. Wang · 2011
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · 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, including independent finite differences, literal calculations, recurrence and convolution comparisons, permutation symmetry, closed-form limits and expressive counterexamples. All eight programs use NumPy 1.26.4. CPU teaching calculations, not framework or GPU 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.
- Bilingual Matplotlib 3.9.1 SVGs use executed article functions for rigid coordinate updates, per-round routing allocations and reconstruction/label tradeoffs. Figures and sample data are hash-bound. Displacements are unscaled, rounds are not training steps, and diagnostic-table accuracy is not a held-out estimate.
Source locations checked:
- Dynamic Routing Between Capsules — arXiv v2 · Physical pages 2–3, Equations 1–4 and Procedure 1: squash, votes, lower-to-upper softmax, agreement and margin loss.
- Transforming Auto-encoders · Physical pages 1–2: vector instantiation parameters, part–whole motivation and supervised transformed pairs.
Related topics