LeNet

Dive into Deep Learning · §6.6

Convolutional Neural Networks (LeNet)
convolutional encoder · dense head · parameter vs. FLOP split · learned filters · pixel-shuffle test

Pitting a Spatial CNN Against Our Flattened MLP

Motivation & The Fashion-MNIST Benchmark

  • Chapter 4 MLP (784 \to 256 \to 10): Flattens 28 \times 28 images, using 203{,}530 parameters to reach \approx 87\% validation accuracy.
  • LeNet-5 spatial CNN: Preserves 2D locality and shares 5 \times 5 kernels across space, reaching \approx 88\text{--}90\% with 3.3\times fewer parameters (61{,}706).
  • Controlled test: We will also permute all 784 pixels to isolate spatial inductive bias.

The LeNet Architecture: Encoder Plus Dense Head

Two Convolutional Blocks Followed by Three Dense Layers

LeNet divides into a convolutional encoder (trading spatial resolution 28 \to 14 \to 10 \to 5 for channel depth 1 \to 6 \to 16) and a dense classification head (400 \to 120 \to 84 \to 10):

  • Convolutional Block 1: 5 \times 5 conv (1 \to 6 channels, p=2, s=1) \to Sigmoid \to 2 \times 2 AvgPool (s=2).
  • Convolutional Block 2: 5 \times 5 conv (6 \to 16 channels, p=0, s=1) \to Sigmoid \to 2 \times 2 AvgPool (s=2).
  • Dense Head: Flatten (16 \times 5 \times 5 = 400) \to Dense (120) \to Sigmoid \to Dense (84) \to Sigmoid \to Dense (10).

Historical LeNet-5 (1998) vs. Our Pedagogical LeNet

Why the First Layer Uses Padding p = 2 on 28×28 Images

  • Padding p = 2 on Conv1: Pads 28 \times 28 Fashion-MNIST images to 32 \times 32 to match the 1998 paper’s 32 \times 32 input grid.
  • Simplified primitives: Uses standard sigmoid \sigma(x), parameter-free 2 \times 2 AvgPool, all-to-all 6 \to 16 Conv2 wiring, and linear softmax cross-entropy instead of Euclidean RBF units.

Implementing LeNet as a Sequential Module

Xavier Uniform Weight Initialization and Sequential Layer Stack

We Xavier-initialize all weights and stack the encoder and dense head in one Sequential:

class LeNet(d2l.Classifier):
    """The layout of LeNet-5, with sigmoid activations and average pooling."""
    def __init__(self, lr=0.1, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.LazyConv2d(6, kernel_size=5, padding=2), nn.Sigmoid(),
            nn.AvgPool2d(kernel_size=2, stride=2),
            nn.LazyConv2d(16, kernel_size=5), nn.Sigmoid(),
            nn.AvgPool2d(kernel_size=2, stride=2),
            nn.Flatten(),
            nn.LazyLinear(120), nn.Sigmoid(),
            nn.LazyLinear(84), nn.Sigmoid(),
            nn.LazyLinear(num_classes))

    def weight_init(self, module):
        # The Trainer calls this after the first minibatch fixed the shapes
        init_cnn(module)  # Xavier-uniform weights
        if type(module) in (nn.Linear, nn.Conv2d) and module.bias is not None:
            nn.init.zeros_(module.bias)

Tracing Tensor Shapes Through LeNet

Spatial Shrinkage and Channel Expansion, Layer by Layer

def layer_summary(self, X_shape):
    X = d2l.randn(*X_shape)
    for layer in self.net:
        X = layer(X)
        name = getattr(layer, '__name__', type(layer).__name__)
        print(f'{name:<22} {tuple(X.shape)}')

model = LeNet()
model.layer_summary((1, 1, 28, 28))
Conv2d                 (1, 6, 28, 28)
Sigmoid                (1, 6, 28, 28)
AvgPool2d              (1, 6, 14, 14)
Conv2d                 (1, 16, 10, 10)
Sigmoid                (1, 16, 10, 10)
AvgPool2d              (1, 16, 5, 5)
Flatten                (1, 400)
Linear                 (1, 120)
Sigmoid                (1, 120)
Linear                 (1, 84)
Sigmoid                (1, 84)
Linear                 (1, 10)

Where Parameters Live vs. Where FLOPs Happen

The Fundamental Memory–Compute Asymmetry of CNNs

  • Convolutions (4.2\% params, 85.9\% MACs): Conv1 (156 params) and Conv2 (2{,}416 params) reuse each weight across 784 and 100 spatial positions (357{,}600 MACs).
  • Dense head (95.8\% params, 14.1\% MACs): Dense1 (400 \to 120) holds 78\% of all weights (48{,}120) but executes only once per image.

Pitfall: Four Sigmoids and Vanishing Gradients

Why LeNet Needs Learning Rate 2.0 Instead of the MLP’s 0.1

  • Derivative ceiling \sigma'(x) \le \tfrac{1}{4}: The Conv1 gradient carries four \sigma' factors, whose product is at most (1/4)^4 = 1/256.
  • Initial \ln 10 \approx 2.30 plateau: Sigmoids cluster near 0.5, crushing logit variance at start of training.
  • Compensation: Classical LeNet requires \eta = 2.0 (20\times higher than the ReLU MLP’s \eta = 0.1).

Training LeNet on Fashion-MNIST

30 Epochs of Minibatch SGD (Batch Size 128, lr = 2.0)

trainer = d2l.Trainer(max_epochs=30, num_gpus=1)
data = d2l.FashionMNIST(batch_size=128)
model = LeNet(lr=2.0)
trainer.fit(model, data)

  • Trajectory: After a 1–3 epoch sigmoid plateau at \mathcal{L} \approx 2.30, validation accuracy reaches \approx 88\text{--}90\% (3.3\times fewer parameters than the MLP).

Extracting First-Layer Kernels and Feature Maps

Probing Conv1 on a Validation Sneaker and Shirt

Unlike a dense layer’s 28 \times 28 global templates, Conv1 learns six 5 \times 5 local kernels. To see what each channel detects, we extract the 6 learned 5 \times 5 kernels alongside their post-sigmoid 28 \times 28 feature maps on a sneaker and a shirt:

X, y = trainer.prepare_batch(next(iter(data.val_dataloader())))
labels = d2l.numpy(y)
X = d2l.stack([X[int(np.argmax(labels == c))] for c in (7, 6)], 0)
maps = model.net[1](model.net[0](X))  # The first convolution and its sigmoid
images, maps = d2l.numpy(X[:, 0]), d2l.numpy(maps)
kernels = d2l.numpy(model.net[0].weight[:, 0])  # Six 5x5 kernels

Visualizing LeNet’s Learned Edge & Silhouette Filters

Emergence of Oriented Edge Detectors from Class Labels Alone

names = data.text_labels([7, 6])
axes = d2l.show_images(
    [kernels[0], *kernels, images[0], *maps[0], images[1], *maps[1]], 3, 7,
    titles=['', *[f'channel {c}' for c in range(1, 7)],
            names[0], *[''] * 6, names[1], *[''] * 6], cmap='gray')
axes[0].set_visible(False)  # No kernel above the input images

Controlled Experiment: The Pixel-Shuffling Test

Destroying Spatial Adjacency with One Fixed Random Permutation

perm = np.random.permutation(28 * 28)  # One fixed order for every image

def shuffle_pixels(images):
    """Rearrange the 784 pixels of every image into the order perm."""
    return images.reshape(len(images), -1)[:, perm].reshape(images.shape)
data_shuffled = d2l.FashionMNIST(batch_size=128)
for split in (data_shuffled.train, data_shuffled.val):
    split.data = shuffle_pixels(split.data)  # The stored 8-bit images
  • MLP invariance: (\mathbf{X}\mathbf{P})\mathbf{W}^{(1)} = \mathbf{X}(\mathbf{P}\mathbf{W}^{(1)}) merely permutes i.i.d. initial rows (\approx 87\%).
  • CNN locality broken: Each 5 \times 5 window reads 25 scattered pixels.

Visualizing Pixel-Shuffled Fashion-MNIST Garments

Same Information Content, Zero Local Geometry

Every permuted image still contains the exact same 784 pixel intensities in a consistent coordinate order, yet looks like pure white noise to human vision:

data_shuffled.visualize(next(iter(data_shuffled.val_dataloader())))

Ordered vs. Shuffled Pixels: The Spatial Prior

Retraining LeNet on Shuffled Fashion-MNIST

curves = {'pixels in place': trainer.history['val_acc']}
trainer.board.display = False
trainer.fit(LeNet(lr=2.0), data_shuffled)
curves['pixels shuffled'] = trainer.history['val_acc']
d2l.plot(list(range(1, trainer.max_epochs + 1)), list(curves.values()),
         'epoch', 'validation accuracy', legend=list(curves))
for name, acc in curves.items():  # A single epoch can land a point low
    print(f'{name}: {sum(acc[-5:]) / 5:.3f} averaged over the last 5 epochs')

Ordered vs. Shuffled Pixels: The Spatial Prior (cont.)

Retraining LeNet on Shuffled Fashion-MNIST

pixels in place: 0.897 averaged over the last 5 epochs
pixels shuffled: 0.853 averaged over the last 5 epochs
  • Inductive bias isolated: Destroying 2D spatial locality drops LeNet by 3\text{--}4 points (\approx 85\text{--}86\%), erasing its gain over the MLP.

Where LeNet Falls Short of Shift Invariance

Boundary Effects, Local Pooling Blocks, and the Dense Flatten Head

  • 1. Padded borders: Shifting near the frame alters zero counts in Conv1 (p=2).
  • 2. Local pool blocks: 2 \times 2 AvgPool jumps whenever a peak crosses a block boundary.
  • 3. Flattened dense head (400 \to 120): Assigns separate weights to each of the 5 \times 5 spatial cells.

Thirty Years of Evolution: LeNet to Modern CNNs

Same Encoder-Plus-Head Blueprint, Modernized Components

  • Signal propagation: Modern CNNs replace Sigmoid + Xavier with ReLU/GELU + He init + BatchNorm/LayerNorm + residual skips, eliminating the (1/4)^L gradient attenuation.
  • Downsampling & head: Stride-2 convolutions and Global Average Pooling replace average pooling and the 3-layer dense head.

Concept Check: LeNet Architecture & Cost

Concept Check

  • 1. Global Average Pooling head: Replacing Flatten + 3 Dense (59{,}134 params) with GAP (16 \times 5 \times 5 \to 16) + a 16 \to 10 linear layer (170 params) cuts total LeNet parameters 22.5\times (61{,}706 \to 2{,}742).
  • 2. Why lower LR with ReLU: ReLU has unit slope (\sigma' = 1 for x>0), removing the four \sigma' \le \tfrac{1}{4} factors, so \eta = 2.0 explodes.

Summary & Key Takeaways: MLP vs. LeNet

Section & Chapter Synthesis

Metric / Component Chapter 4 MLP (784 \to 256 \to 10) Classical LeNet (1998 Layout) Modern CNNs (Chapter 7 Preview)
Parameters 203{,}530 (98.6\% in layer 1) 61{,}706 (4.2\% conv, 95.8\% dense) Bottlenecks + Global Avg Pool head
Multiply-Adds / Image \approx 203{,}000 416{,}520 (85.9\% in conv layers) Dominated by spatial conv layers
Activation & LR ReLU, \eta = 0.1 Sigmoid (\sigma' \le 1/4), \eta = 2.0 ReLU / GELU + BatchNorm / LayerNorm
Downsampling & Head None (flattens input at start) 2 \times 2 AvgPool + 3-layer dense head Strided conv / MaxPool + Global Avg Pool
Fashion-MNIST (Ordered) \approx 87\% \approx 88\text{--}90\% (3.3\times fewer params) > 92\% with deeper residual stages
Fashion-MNIST (Shuffled) \approx 87\% (permutation-invariant) \approx 85\text{--}86\% (locality destroyed) Drops sharply without spatial grid