liveBook · Manning

Chapter 8: Using convolutions to generalize

What you will learn in chapter 8 of Deep Learning with PyTorch, Second Edition

The introduction explains why the fully connected image classifier struggles to generalize and motivates replacing its dense transformation with convolution.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The introduction explains why the fully connected image classifier struggles to generalize and motivates replacing its dense transformation with convolution.

Key terms: fully connected layers, flattened vector, spatial structure, position independence, convolution

8.1 The case for convolutions

This section motivates convolutions for images by replacing image-wide weighted sums with weighted sums of nearby pixels.

Key terms: nearby pixels, patterns corresponding to objects, nn.Linear, weighted sum, immediate neighbors, linear operation

8.1.1 What convolutions do

This section explains how convolutions apply a shared, learnable kernel across image neighborhoods to recognize local patterns wherever they occur, using fewer parameters than a fully connected model.

Key terms: discrete convolution, kernel, neighborhood, channel, translation invariance, tied weights, backpropagation, parameters, convolution kernel, convolution filters

8.2 Convolutions in action

Introduces PyTorch’s 2D convolution for the bird-versus-airplane images, showing how to configure a layer, interpret its parameters, and inspect its output.

Key terms: nn.Conv2d, input features, output features, channels, kernel size, conv.weight, bias, out_ch, in_ch, convolutional filters

8.2.1 Padding the boundary

The section explains why convolutions shrink images at their boundaries and how zero padding preserves image size.

Key terms: convolution kernel, boundary, 3 × 3 neighborhood, padding, ghost pixels, padding=1, kernel_size=3, weight, bias, compatible size

8.2.2 Detecting features with convolutions

Hand-set convolution kernels show how local weighted sums can blur an image or detect edges, before the section explains how a CNN learns such feature-detecting kernels from data.

Key terms: kernel, 3 × 3 neighborhood, blurred, edge-detection kernel, vertical edge, weighted sum, kernels, filter banks, multichannel image, features

8.2.3 Looking further with depth and pooling

This section explains how downsampling between small convolutions lets a network detect larger, more complex image patterns.

Key terms: small kernels, locality, translation invariance, fully connected, downsampling, max pooling, feature maps, nn.MaxPool2d, stacking convolutions, receptive field

8.2.4 Putting it all together for our network

Builds a bird-versus-airplane convolutional network from convolutions, pooling, and fully connected layers, then identifies the reshape needed to connect them.

Key terms: nn.Conv2d, nn.MaxPool2d, Tanh, channels, features, 1D vector, nn.Linear(512, 32), nn.Sequential, view, batch dimension

8.3 Subclassing nn.Module

The section explains why and how to subclass nn.Module when a model needs computation beyond a simple sequence of premade layers.

Key terms: nn.Module, nn.Sequential, subclassing, forward, autograd, backward, torch operations, submodules, __init__, self

8.3.1 Our network as an nn.Module

This section rewrites the convolutional classifier as an nn.Module subclass and explains how its intermediate dimensions generally compress image information, with an exception at the first convolution.

Key terms: nn.Module, forward, nn.Sequential, self.pool2, view, batch dimension, classification networks, intermediate values, pooling, spatial resolution

8.3.2 How PyTorch keeps track of parameters and submodules

This section explains how PyTorch registers submodules, finds their parameters for optimization, and treats custom module methods differently from standard calls.

Key terms: nn.Module, submodule, nn.ModuleList, nn.ModuleDict, parameters(), grad, autograd, optimizer, hooks, __call__

8.3.3 The functional API

This section explains PyTorch’s functional API and when to use it instead of modules in a custom network.

Key terms: functional, torch.nn.functional, nn.Module, Parameters, nn.Linear, nn.Conv2d, pooling, activation, nn.Sequential, functional API

8.4 Training our convolutional neural network

The section assembles the convolutional network’s training loop from a Dataset, DataLoader, model, loss function, and optimizer.

Key terms: Dataset, DataLoader, epochs, forward pass, loss, gradients

8.4.1 Measuring accuracy

The section uses training and validation accuracy to evaluate the convolutional classifier and shows that it generalizes better than the earlier fully connected model despite having far fewer parameters.

Key terms: accuracy, training and validation datasets, loss, fully connected model, convolutional model, locality, translation invariance, generalizing, parameters

8.4.2 Saving and loading our model

The section explains that a saved model file contains parameters, so loading it requires recreating the model structure first.

Key terms: parameters, weights and biases, model class

8.4.3 Training on the GPU

This section shows how to train and validate a model on an available GPU and how to handle device placement when loading saved weights.

Key terms: GPU, device, torch.cuda.is_available, Tensor.to, nn.Module.to, Module.to, Optimizer, in place, out of place, weights

8.5 Model design

This section explains why more complex data calls for different neural network designs and why PyTorch provides the components to build them.

Key terms: ImageNet, visual clues, hierarchically organized, architecture, loss function, modules, tabular data, sequences, text

8.5.1 Adding memory capacity: Width

The section shows how to widen a convolutional network and explains the resulting trade-off between capacity and overfitting.

Key terms: width, output channels, features, view, fully connected layers, parameters, capacity, overfitting, input variability

8.5.2 Helping our model to converge and generalize: Regularization

This section explains how weight penalties, dropout, and batch normalization help a convolutional model train and generalize, including how dropout and batch normalization change at inference time.

Key terms: optimization, generalization, regularization, overfitting, L1 regularization, L2 regularization, weight decay, weight_decay, lambda, SGD

8.5.3 Going deeper to learn more complex structures: Depth

This section explains what depth can add to a convolutional network, why deep networks are difficult to train, and how residual blocks and training choices make greater depth practical.

Key terms: depth, hierarchical information, backpropagation, vanishing gradients, converge, skip connection, residual networks, ResNets, identity mapping, ResBlock

8.5.4 Comparing the designs from this section

The section compares network design changes while cautioning against reading too much into small accuracy differences and interpreting their training–validation gaps.

Key terms: validation accuracy, random seeds, learning rate, number of epochs, weight decay, dropout, batch norm, regularization, convergence, training accuracy

8.5.5 It’s already outdated

The section argues that, because neural network architectures change quickly, practitioners should focus on turning ideas from papers into PyTorch models or understanding others’ implementations.

Key terms: neural network architectures, translate the math behind a paper, PyTorch code

8.6 Conclusion

The conclusion describes how to use the bird-or-airplane classifier and highlights two limits that matter for real-world images.

Key terms: crop and resize, 32 × 32, bounding boxes, overgeneralization, training distribution

8.7 Exercises

8.8 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 7: Telling birds from airplanes: Learning from images Chapter 9: How transformers work →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.