def init_cnn(module):
"""Initialize weights for CNNs."""
if type(module) == nn.Linear or type(module) == nn.Conv2d:
nn.init.xavier_uniform_(module.weight)6.6 LeNet
We now have all the building blocks of a convolutional neural network in hand: convolutional layers (Section 6.2), padding and stride (Section 6.3), multiple channels (Section 6.4), and pooling (Section 6.5). It is time to assemble them into a complete image classifier and put our earlier arguments to the test: does respecting two-dimensional spatial structure actually outperform a standard MLP?
Our baseline is the MLP from Section 4.2, which reaches roughly 87% validation accuracy on Fashion-MNIST after 30 epochs. Whereas the MLP flattens each image into 784 unordered numbers (Section 6.1), a CNN preserves the pixel grid and applies shared local kernels across every spatial position. To compare the two architectures fairly, we train our CNN with the same cross-entropy loss, SGD optimizer, and 30-epoch budget. Because a single accuracy number never tells the whole story, we will also inspect the filters learned by the first convolutional layer and run a controlled experiment on pixel-shuffled images to verify where the CNN’s advantage originates.
The architecture we implement is LeNet, named after Yann LeCun, who developed it with colleagues at AT&T Bell Labs to recognize handwritten digits (LeCun et al. 1998). It marked the culmination of a decade of research that began with one of the earliest end-to-end convolutional networks trained by backpropagation (LeCun et al. 1989). By 1998, LeNet-5 achieved error rates below 1% on handwritten digits, rivaling the support vector machines that dominated machine learning at the time, and variants of it were deployed commercially to read handwritten amounts on bank checks and ATM deposits. LeNet provided early, compelling proof that an end-to-end learned network could replace carefully hand-engineered vision pipelines.
6.6.1 The LeNet Architecture
At a high level, LeNet divides cleanly into two stages, illustrated in Figure 6.6.1: a convolutional encoder built from two convolutional blocks, followed by a dense classification head consisting of three fully connected layers.
Each convolutional block pairs a \(5\times5\) convolutional layer and a sigmoid activation with a \(2\times2\) average-pooling layer of stride 2. The first convolutional layer outputs 6 channels and the second outputs 16.
The encoder output has channels-first shape (batch_size, channels, height, width).
The encoder output has channels-last shape (batch_size, height, width, channels).
The encoder output has channels-last shape (batch_size, height, width, channels).
The encoder output has channels-first shape (batch_size, channels, height, width).
To connect the convolutional encoder to the dense block, we flatten each example’s spatial feature maps into a single vector, producing a two-dimensional matrix with one row per minibatch example. Three fully connected layers then project this vector through 120 and 84 hidden units to 10 output logits, one per class, just as in softmax regression.
Note that this is the standard pedagogical version of LeNet-5 rather than a bit-for-bit historical replica. It preserves the 1998 network’s alternating convolutions and pooling as well as its layer widths (6, 16, 120, and 84), while simplifying legacy details that are rarely used today (such as a scaled \(\tanh\) activation, learnable pooling scales and biases, sparse channel wiring between the two convolutions, and radial-basis-function output units). One historical detail does remain visible in our code: the original LeNet-5 took \(32\times32\) inputs. MNIST digits are \(28\times28\), and the 1998 paper surrounded them with two background pixels on every side so that strokes near the edge of a digit fall inside the receptive fields of the top feature detectors. Two pixels of padding in our first convolutional layer do the same job, and the first \(5\times5\) convolution again produces a \(28\times28\) output.
Before defining the network, we write init_cnn to initialize all convolutional and linear weights with Xavier uniform initialization (Section 4.4.2.1).
With modern deep learning frameworks, assembling LeNet requires only a single Sequential block self.net that chains the two convolutional–pooling stages with the three fully connected layers, setting all biases to zero.
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)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 = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(6, kernel_size=5, padding='same'),
tf.keras.layers.Activation('sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Conv2D(16, kernel_size=5),
tf.keras.layers.Activation('sigmoid'),
tf.keras.layers.AvgPool2D(pool_size=2, strides=2),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(120), tf.keras.layers.Activation('sigmoid'),
tf.keras.layers.Dense(84), tf.keras.layers.Activation('sigmoid'),
tf.keras.layers.Dense(num_classes)])class LeNet(d2l.Classifier):
"""The layout of LeNet-5, with sigmoid activations and average pooling."""
def __init__(self, lr=0.1, num_classes=10, kernel_init=None, rngs=None):
super().__init__()
self.save_hyperparameters(ignore=['rngs', 'kernel_init'])
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
kernel_init = (nnx.initializers.xavier_uniform() if kernel_init is None
else kernel_init)
def avg_pool(x): # 2x2 windows, stride 2
return nnx.avg_pool(x, window_shape=(2, 2), strides=(2, 2))
def flatten(x):
return x.reshape((x.shape[0], -1))
self.net = nnx.Sequential(
nnx.Conv(1, 6, kernel_size=(5, 5), padding=2,
kernel_init=kernel_init, rngs=rngs), nnx.sigmoid,
avg_pool,
nnx.Conv(6, 16, kernel_size=(5, 5), padding='VALID',
kernel_init=kernel_init, rngs=rngs), nnx.sigmoid,
avg_pool,
flatten,
nnx.Linear(400, 120, kernel_init=kernel_init, rngs=rngs),
nnx.sigmoid,
nnx.Linear(120, 84, kernel_init=kernel_init, rngs=rngs),
nnx.sigmoid,
nnx.Linear(84, num_classes, kernel_init=kernel_init, rngs=rngs))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()
self.net.add(
nn.Conv2D(6, kernel_size=5, padding=2), nn.Activation('sigmoid'),
nn.AvgPool2D(pool_size=2, strides=2),
nn.Conv2D(16, kernel_size=5), nn.Activation('sigmoid'),
nn.AvgPool2D(pool_size=2, strides=2),
nn.Flatten(),
nn.Dense(120), nn.Activation('sigmoid'),
nn.Dense(84), nn.Activation('sigmoid'),
nn.Dense(num_classes))
self.net.initialize(init.Xavier())6.6.2 Layer Shapes
Because a single mismatched padding value or a forgotten flatten layer shifts every downstream tensor shape, it is good practice to verify intermediate shapes before starting training. Figure 6.6.2 diagrams LeNet in compressed notation alongside the expected tensor shape at each boundary. To check that our implementation matches this diagram, we pass a single-channel \(28 \times 28\) dummy tensor through the model and print the output shape after each layer. We package this diagnostic as a layer_summary method on d2l.Classifier so that we can reuse it for deeper architectures in the next chapter.
@d2l.add_to_class(d2l.Classifier)
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)
@d2l.add_to_class(d2l.Classifier)
def layer_summary(self, X_shape):
X = d2l.normal(X_shape)
for layer in self.net.layers:
X = layer(X)
name = getattr(layer, '__name__', type(layer).__name__)
print(f'{name:<22} {tuple(X.shape)}')
model = LeNet()
model.layer_summary((1, 28, 28, 1))Conv2D (1, 28, 28, 6)
Activation (1, 28, 28, 6)
AveragePooling2D (1, 14, 14, 6)
Conv2D (1, 10, 10, 16)
Activation (1, 10, 10, 16)
AveragePooling2D (1, 5, 5, 16)
Flatten (1, 400)
Dense (1, 120)
Activation (1, 120)
Dense (1, 84)
Activation (1, 84)
Dense (1, 10)
@d2l.add_to_class(d2l.Classifier)
def layer_summary(self, X_shape):
X = jnp.zeros(X_shape)
for layer in self.net.layers:
X = layer(X)
# Activations and pooling are plain functions: print their names
name = getattr(layer, '__name__', type(layer).__name__)
print(f'{name:<22} {tuple(X.shape)}')
model = LeNet()
model.layer_summary((1, 28, 28, 1))Conv (1, 28, 28, 6)
sigmoid (1, 28, 28, 6)
avg_pool (1, 14, 14, 6)
Conv (1, 10, 10, 16)
sigmoid (1, 10, 10, 16)
avg_pool (1, 5, 5, 16)
flatten (1, 400)
Linear (1, 120)
sigmoid (1, 120)
Linear (1, 84)
sigmoid (1, 84)
Linear (1, 10)
@d2l.add_to_class(d2l.Classifier)
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)
Activation (1, 6, 28, 28)
AvgPool2D (1, 6, 14, 14)
Conv2D (1, 16, 10, 10)
Activation (1, 16, 10, 10)
AvgPool2D (1, 16, 5, 5)
Flatten (1, 400)
Dense (1, 120)
Activation (1, 120)
Dense (1, 84)
Activation (1, 84)
Dense (1, 10)
The printed shapes match Figure 6.6.2 exactly and follow our output-shape rules from Section 6.3. An unpadded \(5\times5\) kernel reduces height and width by 4: our first convolutional layer adds 2 pixels of padding per side to preserve the \(28\times28\) resolution, whereas the second uses no padding and shrinks \(14\times14\) to \(10\times10\). Each \(2\times2\) average-pooling layer halves both spatial dimensions (\(28 \to 14\) and \(10 \to 5\)). Meanwhile, channel depth expands from 1 to 6 to 16 as the encoder trades spatial resolution for richer feature representations. Flattening the final \(16 \times 5 \times 5\) tensor yields a 400-dimensional vector, which the dense block progressively compresses down to 10 class logits.
6.6.3 Parameters and Multiply-Adds
With every layer’s output shape verified, we can tally both parameter memory and arithmetic cost. Recall from Section 6.4.2 that a convolutional layer with \(c_\textrm{i}\) input channels, \(c_\textrm{o}\) output channels, and a \(k\times k\) kernel stores \(c_\textrm{i} c_\textrm{o} k^2\) weights plus \(c_\textrm{o}\) biases, and reuses every weight once per output spatial location. By contrast, a fully connected layer uses each weight only once per example. Table 6.6.1 breaks down these figures across LeNet.
| layer | output | parameters | multiply-adds |
|---|---|---|---|
| \(5\times5\) convolution, 1 to 6 channels | 6@28×28 | \(150 + 6 = 156\) | \(150 \times 784 = 117{,}600\) |
| \(5\times5\) convolution, 6 to 16 channels | 16@10×10 | \(2{,}400 + 16 = 2{,}416\) | \(2{,}400 \times 100 = 240{,}000\) |
| fully connected, 400 to 120 | 120 | \(48{,}000 + 120 = 48{,}120\) | \(48{,}000\) |
| fully connected, 120 to 84 | 84 | \(10{,}080 + 84 = 10{,}164\) | \(10{,}080\) |
| fully connected, 84 to 10 | 10 | \(840 + 10 = 850\) | \(840\) |
| total | \(61{,}706\) | \(416{,}520\) |
The breakdown highlights a striking division between memory and computation that recurs throughout CNN design. The two convolutional layers account for just 4% of LeNet’s parameters yet perform 86% of its multiply-adds, because every kernel weight is evaluated across an entire spatial grid. Conversely, the first fully connected layer alone holds 78% of the parameters while contributing only 12% of the arithmetic. Compared with our earlier Fashion-MNIST MLP (203,530 parameters and roughly 203,000 multiply-adds per image), LeNet uses fewer than a third as many parameters while performing roughly twice as much computation.
6.6.4 Training
Just as with the MLP, we train LeNet by minimizing cross-entropy loss with minibatch SGD for 30 epochs, using a minibatch size of 128 (half the MLP’s 256). One hyperparameter, however, must change substantially: the learning rate. Because the derivative of the sigmoid activation never exceeds \(1/4\) (Section 4.1.4), gradients flowing back to the first convolutional layer are attenuated by four successive sigmoids. At the MLP’s learning rate of 0.1, training crawls: validation accuracy lingers near chance for the first two to four epochs and climbs only to about 73% after 10 epochs. We therefore raise the learning rate to 2.0 (an empirically tuned factor of twenty, reflecting the smaller gradient scale).
As in Section 5.7.4, d2l.Trainer automatically dispatches training to a GPU when one is available.
trainer = d2l.Trainer(max_epochs=30, num_gpus=1)
data = d2l.FashionMNIST(batch_size=128)
model = LeNet(lr=2.0)
trainer.fit(model, data)After 30 epochs, LeNet achieves roughly 88–90% validation accuracy, improving on the MLP’s ~87% despite having less than a third as many parameters.
Look closely at the beginning of the training curve, too. Depending purely on the random initialization, accuracy sometimes climbs immediately, while in other runs it hovers at chance (10%) with the loss pinned near \(\ln 10 \approx 2.3\) for a few epochs before suddenly taking off. During that initial plateau, the network predicts nearly identical uniform probabilities for every image: after passing through four sigmoid layers, input-dependent variations in the logits are initially too tiny to separate the classes. We quantify this vanishing-signal effect in an exercise below, and we will see the same plateau resurface in our pixel-shuffling experiment.
6.6.4.1 The Learned Features
For softmax regression, we could visualize each class’s weights directly as a \(28\times28\) template image (Section 3.3), and similarly each hidden unit of an MLP weighted fixed pixel locations (Section 4.2). A convolutional kernel, by contrast, is not tied to any particular pixel: it is just a \(5\times5\) patch of weights that is hard to interpret in isolation. To understand what the first convolutional layer has discovered, we first pull one sneaker (class 7) and one shirt (class 6) from a validation minibatch into a two-image tensor X.
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)Next, we pass X through the first convolutional layer and its sigmoid activation to extract the six \(28 \times 28\) feature maps alongside the learned \(5 \times 5\) kernels.
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 kernelslayers = model.net.layers
maps = layers[1](layers[0](X)) # The first convolution and its sigmoid
# Channels-last to channels-first, so that maps[k, c] is one 28x28 map
images, maps = d2l.numpy(X[..., 0]), d2l.numpy(maps).transpose(0, 3, 1, 2)
kernels = d2l.numpy(layers[0].kernel)[:, :, 0].transpose(2, 0, 1)layers = model.net.layers
maps = layers[1](layers[0](X)) # The first convolution and its sigmoid
# Channels-last to channels-first, so that maps[k, c] is one 28x28 map
images, maps = d2l.numpy(X[..., 0]), d2l.numpy(maps).transpose(0, 3, 1, 2)
kernels = d2l.numpy(layers[0].kernel[...])[:, :, 0].transpose(2, 0, 1)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.data()[:, 0]) # Six 5x5 kernelsWe can now display the six kernels on the top row above the input images and their six post-sigmoid feature maps, scaling each panel independently from its minimum (black) to its maximum (white).
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 imagesAcross training runs, two distinct families of feature maps consistently emerge. Some channels act as local brightness or foreground detectors, reproducing the filled silhouette of the garment (either bright on dark or inverted). The remaining channels light up selectively along the garment’s contours, especially its left or right boundaries. Examining their \(5\times5\) kernels reveals how they do it: bright columns paired beside dark columns, forming learned, multi-row relatives of the hand-crafted \((1, -1)\) vertical edge kernel from Section 6.2.2.2. Earlier, we had to supply an explicit target edge map for gradient descent to learn an edge filter; here, given nothing but raw garment pixels and class labels, LeNet discovers on its own that edges and silhouettes are useful building blocks for visual classification. (The exact assignment of roles across the six channels varies from run to run.)
6.6.4.2 Shuffled Pixels
How much weight should we put on a 1–3 percentage point gain over the MLP? Taken alone, that margin could be noisy: the MLP’s validation accuracy fluctuates by roughly a point from epoch to epoch (Section 4.2), and LeNet also differs in depth, activation function, and learning rate. A cleaner controlled experiment strips away the single piece of information that only convolutions exploit: spatial adjacency. Returning to the thought experiment from the chapter introduction, we draw one fixed random permutation of the 784 pixel positions and apply that exact same reordering to every training and validation image.
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)We now apply shuffle_pixels with this shared permutation perm to every image in the training and validation splits of data_shuffled.
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 imagesdata_shuffled = d2l.FashionMNIST(batch_size=128)
data_shuffled.train, data_shuffled.val = [
(shuffle_pixels(images), labels)
for images, labels in (data_shuffled.train, data_shuffled.val)]data_shuffled = d2l.FashionMNIST(batch_size=128)
data_shuffled.train, data_shuffled.val = [
(shuffle_pixels(images), labels)
for images, labels in (data_shuffled.train, data_shuffled.val)]data_shuffled = d2l.FashionMNIST(batch_size=128)
data_shuffled.train, data_shuffled.val = [
data_shuffled.to_dataset(shuffle_pixels(images), labels)
for images, labels in (data_shuffled.read(train=True),
data_shuffled.read(train=False))]Visualizing a validation minibatch from data_shuffled confirms that permuting the 784 pixel coordinates destroys all recognizable garment contours, leaving patterns that look like pure static to human eyes.
data_shuffled.visualize(next(iter(data_shuffled.val_dataloader())))An MLP is completely blind to this permutation, and we do not even need to retrain it to prove why: permuting the input coordinates merely reorders the rows of its first weight matrix \(\mathbf{W}^{(1)}\). Since every weight is initialized identically and independently, training on shuffled pixels is statistically identical to training on the original images, yielding the same ~87% accuracy. For LeNet, however, shuffling destroys spatial locality: every \(5\times5\) kernel now reads 25 pixels scattered randomly across the original garment. Let us retrain LeNet with the exact same settings on the shuffled dataset and plot both validation curves side by side.
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')pixels in place: 0.897 averaged over the last 5 epochs
pixels shuffled: 0.853 averaged over the last 5 epochs
pixels in place: 0.893 averaged over the last 5 epochs
pixels shuffled: 0.856 averaged over the last 5 epochs
pixels in place: 0.892 averaged over the last 5 epochs
pixels shuffled: 0.859 averaged over the last 5 epochs
pixels in place: 0.897 averaged over the last 5 epochs
pixels shuffled: 0.856 averaged over the last 5 epochs
On shuffled pixels, LeNet drops several percentage points to around 85–86% in a typical run, at or slightly below the MLP. Once spatial neighborhood structure is destroyed, LeNet’s advantage vanishes, confirming that its edge over the MLP comes directly from its convolutional inductive bias.
Notice that the initial chance-level plateau can reappear here as well, and just as unpredictably. While it rarely exceeds a few epochs on ordered images, on shuffled images an unlucky initialization can occasionally leave the model stuck near chance for much of the 30-epoch run, depressing final accuracy even further. That instability stems from stacking four sigmoid activations rather than from the pixel ordering itself; even in runs that escape the plateau immediately, LeNet on shuffled pixels never surpasses the MLP.
Finally, let us connect LeNet back to the symmetry principles of Section 6.1. Idealized image classifiers would have strictly translation-equivariant feature layers and a strictly translation-invariant output, yet LeNet achieves neither exactly: padded convolutions break equivariance near borders, pooling absorbs only shifts that stay within a pooling block (Section 6.5), and flattening the final \(5\times5\) maps assigns distinct dense weights to every spatial cell. LeNet’s shift tolerance is therefore only partial: sufficient for Fashion-MNIST, where every garment is neatly centered, though inadequate for unconstrained scenes.
Taken together, our two experiments demonstrate that a CNN can match and outperform an MLP using less than a third as many parameters, precisely because weight sharing lets each kernel learn a local visual pattern once and detect it anywhere on the grid. On tiny \(28\times28\) images, that efficiency is a modest bonus; on the megapixel photographs discussed in Section 6.1, where a single dense layer demands a billion weights, the same principle determines whether a model can be built at all. Making deep convolutional networks easy to train at scale is the next challenge, and the sluggish, erratic convergence of LeNet’s four sigmoid layers already hints at why modern architectures had to evolve far beyond 1998.
6.6.5 Summary
LeNet pairs a convolutional encoder (which progressively trades spatial resolution for deeper channel representations) with a three-layer fully connected classifier head. Its convolutional layers hold just 4% of the parameters yet perform 86% of the multiply-adds, whereas the first dense layer alone accounts for 78% of the parameters. Trained under the same 30-epoch SGD setup as the MLP of Section 4.2, LeNet reaches ~88–90% validation accuracy on Fashion-MNIST (versus ~87% for the MLP) with fewer than a third of the parameters, automatically learning silhouette and vertical-edge filters from class labels alone. Shuffling pixel positions erases that gain, isolating spatial locality as its source. At the same time, propagating gradients through four sigmoid layers forces a much larger learning rate (2.0 rather than 0.1) and causes unpredictable early training plateaus.
While the overall encoder-plus-head blueprint remains foundational, almost every individual component of LeNet has since been modernized: ReLUs replaced sigmoids, max-pooling and strided convolutions replaced average pooling, global average pooling followed by a single linear layer replaced heavy dense heads, and normalization layers stabilized deep training. In the next chapter, beginning with AlexNet (Section 7.1), we trace these architectural advances one by one as networks scale up in depth, width, and resolution.
6.6.6 Exercises
[code] Modern components. Retrain
LeNetwith the changes below, using the training settings of this section, and compare the validation accuracy of each variant after 30 epochs with that ofLeNet.- Replace average pooling with max-pooling.
- Replace the sigmoid activations with ReLU. If the loss diverges or the accuracy stays at chance, lower the learning rate until training succeeds, and report the learning rate you used.
- Make both changes together, and call the result the modernized LeNet. Which of the two changes accounts for most of the difference in accuracy?
- ● With the weights the model has at the start of training, measure for
LeNetand for the modernized LeNet the norm of the gradient of the loss with respect to the first convolutional kernel, and the standard deviation of the logits across a minibatch. The derivation of Xavier initialization in Section 4.4.2.1 assumes inputs with zero mean and no nonlinearity. Use the mean of the sigmoid’s output and its slope \(\sigma'(0) = 1/4\) to explain your measurements, the learning rate thatLeNetneeds, and the epochs at chance at the start of its training.
[code] Original MNIST. Write an
MNISTdata class by adaptingd2l.FashionMNIST, and train bothLeNetand the MLP of Section 4.2 on it, with the settings that each uses for Fashion-MNIST. LeCun et al. (1998) report a test error rate below 1% for LeNet-5 on MNIST.- Compare the validation error rate of
LeNetwith this figure. The two are measured on the same images: as for Fashion-MNIST, our validation set is the dataset’s official test set. - For each dataset, compute the difference and the ratio of the validation error rates of the two networks. Section 3.2 states that MNIST makes differences among model classes less visible. Does each of the two measures support this statement?
- Compare the validation error rate of
[code] Deeper feature maps. The text drew the feature maps of the first convolutional layer.
- Display the 16 feature maps of the second convolutional layer of the trained
LeNet, after its sigmoid, for validation images of two classes that are easily confused, for example pullovers and coats. Can you still say what a channel responds to? Which channels differ most between the two classes? - Train the modernized LeNet of problem 1 and measure the maximum activation of each of its two convolutional layers, taken after the ReLU, on Fashion-MNIST validation images, on out-of-distribution photos such as a cat or a car, and on uniform random noise. Convert each photo to a \(28 \times 28\) grayscale image, and keep every input in \([0, 1]\), the pixel range of
d2l.FashionMNIST. Do the maxima for photos and noise fall inside or clearly outside the range observed on the validation images?
- Display the 16 feature maps of the second convolutional layer of the trained
[code] Shifted garments. The text argued that
LeNetis only partly tolerant to shifts.- Shift every validation image by one, two, and four pixels to the right, filling the vacated columns with zeros, and measure the validation accuracy of the trained
LeNeton each shifted set. Which shifts does the network tolerate? Relate what you find to the two pooling layers and to the dense head. - Explain why training
LeNeton translated copies of its training images can improve the accuracy on shifted validation images even though its convolutional layers share weights across all locations.
Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 6.
- Shift every validation image by one, two, and four pixels to the right, filling the vacated columns with zeros, and measure the validation accuracy of the trained
[code] The dense head. ● Table 6.6.1 shows that the first fully connected layer holds 78% of LeNet’s parameters.
- Replace the entire dense head, from the flatten through the output layer, by global average pooling followed by a single linear layer from 16 to 10 units. How many parameters does the network now have? Before training, predict whether the validation accuracy changes by more than one percentage point relative to
LeNet; then retrain and compare. - Instead connect the flattened 400-dimensional convolutional output directly to a ten-way linear output layer. How many parameters does this network have? Retrain, and compare the accuracy of the two reduced heads with each other and with your prediction. What does the comparison say about where LeNet’s capacity is used?
Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 6.
- Replace the entire dense head, from the flatten through the output layer, by global average pooling followed by a single linear layer from 16 to 10 units. How many parameters does the network now have? Before training, predict whether the validation accuracy changes by more than one percentage point relative to