Code Architecture — Dynamic Routing Between Capsules (CapsNet)
Overview
The notebook builds a scaled-down CapsNet in PyTorch (squashing, PrimaryCaps, DigitCaps with routing-by-agreement, margin loss and a reconstruction decoder), trains it for 5 epochs on 20,000 MNIST images on a CPU, and shows reconstructions and capsule-dimension perturbations.
Section-by-Section Breakdown
1. Setup & Imports (cell 2)
- Imports
torch,torchvision,matplotlibandnumpy; saves figures as JPEG at dpi 80; registers theatexithook that saves the executed notebook on Kaggle. - Seeds Python, NumPy and PyTorch with
SEED = 42and turns on deterministic algorithms. Runs on CPU.
2. Data Loading (cell 4)
- MNIST via
torchvision.datasets.MNISTwithtransforms.ToTensor()only, so pixels stay in [0, 1] (the decoder’s sigmoid outputs reconstruct them). The download output is suppressed. Subsets: the first 20,000 training images and the first 5,000 test images. Train loader: batch size 64, shuffled with a seeded generator. Test loader: batch size 128.- Shows 5 training digits.
3. Squashing Function (cell 6)
squash(s): v = (‖s‖² / (1 + ‖s‖²)) · s / ‖s‖ (Eq. 1), with a small epsilon inside the square root.
4. PrimaryCaps Layer (cell 8)
PrimaryCapsule: a 9×9, stride-2 convolution from 64 channels to 8 × 4 channels, reshaped into 8 types × 6×6 positions = 288 capsules of 4D, then squashed. Output[B, 288, 4].
5. DigitCaps Layer with Dynamic Routing (cell 10)
DigitCapsule: weightWof shape[1, 10, 288, 8, 4](initialised with standard deviation 0.01) maps each 4D primary capsule to an 8D prediction for each of the 10 digit capsules:u_hat[B, 10, 288, 8].- Routing (Procedure 1), 2 iterations: logits
bstart at zero;c = softmax(b)over the 10 digit capsules;s = Σ c · u_hat;v = squash(s);b += u_hat · v. Output[B, 10, 8].
6. Margin Loss (cell 12)
MarginLoss: m⁺ = 0.9, m⁻ = 0.1, λ = 0.5 (Eq. 4), summed over the 10 classes and averaged over the batch.
7. Decoder (cell 14)
Decoder: FC 8→256 → ReLU → FC 256→512 → ReLU → FC 512→784 → sigmoid, reshaped to[B, 1, 28, 28].- Its input is the 8D vector of one digit capsule (the true class in training, the predicted class otherwise), so it does not see which class was selected.
8. Full CapsNet Model (cells 16–18)
CapsNet: Conv1 (1→64 channels, 9×9, stride 1, ReLU) → PrimaryCaps → DigitCaps → decoder.predictreturns the class with the longest digit capsule.- 799,408 parameters.
9. Training Loop (cell 20)
- Adam, learning rate 10⁻³, 5 epochs.
- Loss = margin loss + 0.0005 × reconstruction loss, where the reconstruction loss is the sum of squared differences over the 784 pixels of each image, averaged over the batch (Section 4.1).
- Test accuracy on the 5,000 test images after each epoch; prints the final accuracy and test error.
10. Evaluation & Visualisation (cells 22–26)
- 10.1: training loss and test accuracy per epoch.
- 10.2: 10 test images with predictions and reconstructions (decoder given the predicted class), and the mean sum of squared reconstruction error per test image.
- 10.3: for the first correctly classified test image (a 7), each of its 8 capsule dimensions is changed by 11 values from −0.25 to +0.25 and decoded (as in Figure 4).
11. Summary (cell 27)
- What the saved run shows: 98.12% test accuracy (1.88% error) after 5 epochs, still rising; not comparable with the paper’s 0.25%; blurry but recognisable reconstructions (mean squared error 33.13 per image); dimensions 2 and 3 of the digit-7 capsule visibly change stroke thickness and size.
Data Flow & Shapes
Input image: [B, 1, 28, 28]
Conv1 (64 × 9×9, stride 1, ReLU) -> [B, 64, 20, 20]
PrimaryCaps (9×9, stride 2, 8 types 4D) -> [B, 288, 4]
W_ij predictions -> [B, 10, 288, 8]
Routing (2 iterations) -> DigitCaps [B, 10, 8]
Select one class capsule -> [B, 8]
Decoder (8 -> 256 -> 512 -> 784) -> [B, 1, 28, 28]
Loss = margin loss + 0.0005 × sum of squared reconstruction error
Differences from the Paper
| Paper | Notebook | |
|---|---|---|
| Conv1 channels | 256 | 64 |
| Primary capsules | 32 types of 8D on 6×6 | 8 types of 4D on 6×6 |
| Digit capsules | 16D | 8D |
| Routing iterations | 3 | 2 |
| Decoder input | all 10 capsules, all but one masked | the selected capsule’s 8D vector only |
| Data | 60,000 images shifted by up to 2 pixels | 20,000 images, no shifts |
| Optimiser | Adam with exponentially decaying learning rate | Adam, fixed 10⁻³, 5 epochs |