Chapter 5: Deep Learning
Neural network fundamentals, backpropagation, CNNs, and modern architectures that power computer vision.
- Topics
- 4
- Demo
- 1
- Videos
- 3
- Min read
- 33
Chapter Overview
Deep learning has revolutionized computer vision, achieving superhuman performance on tasks that once seemed impossible. But neural networks aren't magic—they're built on simple mathematical principles.
What is this chapter about? We demystify deep learning by building up from the basics: neurons, layers, and how networks learn through backpropagation. Then we explore Convolutional Neural Networks (CNNs)—the architecture specifically designed for images.
Why does this matter? Nearly every state-of-the-art computer vision system uses deep learning:
- Image classification (ResNet, EfficientNet)
- Object detection (YOLO, Faster R-CNN)
- Semantic segmentation (U-Net, DeepLab)
- Image generation (GANs, Diffusion models)
How the topics connect: We start with neural network fundamentals—understanding what neurons compute and how layers compose. Then backpropagation explains how networks learn from data. CNNs introduce convolution layers that exploit image structure. Finally, we survey modern architectures that achieve state-of-the-art results.
Chapter Roadmap
Click any topic to jump in
Neural Network Fundamentals
Neurons, activation functions, and loss functions — the atomic units that compose every deep learning model.
Backpropagation
The chain rule applied to computational graphs — how networks learn by propagating error signals backward through layers.
Convolutional Neural Networks
Convolutions, pooling, and receptive fields — the architecture designed to exploit the spatial structure of images.
Modern Architectures
ResNets, transformers, batch normalization, and dropout — the innovations that enable training very deep networks at scale.
Topics
4 topics in this chapter
The previous chapter fit models by writing down the equations ourselves — a line, a homography, a total-variation energy — and solving for their parameters. But most vision problems have no equation we can write: nothing tells us the precise function that maps a grid of pixels to the label "cat." We need a model flexible enough to represent almost any mapping and then learn it from examples instead of deriving it. That is what a neural network provides, and this topic builds it from its smallest part. The building block is the artificial neuron: it takes a weighted sum of its inputs, adds a bias, and passes the result through a non-linear activation function. One neuron alone draws a single decision boundary, but stack many into layers and compose them, and the network can approximate essentially any continuous function. This topic covers the neuron, the activation functions that supply the crucial non-linearity, the universal-approximation guarantee that justifies the whole enterprise, and the loss functions that measure how wrong the network is — the quantity the next topic teaches us to minimize.
Definition
An artificial neuron computes a weighted sum of its inputs plus a bias, then applies a non-linear activation function. A neural network stacks layers of such neurons so their compositions approximate complex functions, with a loss function measuring prediction error and activations supplying the non-linearity that makes depth more expressive than a single linear map.
In this topic
- 1Artificial Neuron
- 2Activation Functions
- 3Universal Approximation
- 4Loss Functions
Artificial Neuron
An artificial neuron (perceptron) computes a weighted sum of inputs, adds a bias, and applies a non-linear activation function :
- : Input values from previous layer
- : Learnable weights (connection strengths)
- : Bias term (shifts the activation threshold)
- : Activation function (introduces non-linearity)
Geometric Interpretation: The weighted sum defines a hyperplane in input space. The neuron classifies inputs based on which side of this hyperplane they fall on.
Why Non-linearity is Essential: Without non-linear activations, stacking layers would be equivalent to a single linear transformation (). Activations enable learning complex, non-linear decision boundaries.
A single neuron computes the affine map followed by a pointwise nonlinearity . The weight vector defines a hyperplane that partitions the input space into two half-spaces. The bias shifts this hyperplane away from the origin. A single neuron with a step activation is equivalent to a linear classifier — it can only separate linearly separable classes. Stacking neurons in layers composes these half-space decisions, and the universal approximation theorem guarantees that with enough neurons in one hidden layer, any continuous function on a compact set can be approximated to within for any .
A neuron with weights [0.5, -0.3], bias 0.1, and ReLU activation receives input [2, 1]. What's the output?
Activation Functions
Activation functions introduce non-linearity, enabling neural networks to learn complex mappings:
- ReLU (Rectified Linear Unit): Simple, fast, avoids vanishing gradients for positive values. Most popular for hidden layers. Variant: Leaky ReLU allows small gradient for negative inputs.
- Sigmoid: Outputs in , good for probabilities. Can suffer from vanishing gradients. Derivative: .
- Tanh: Outputs in , zero-centered. Derivative: .
- GELU (Gaussian Error Linear Unit): Used in transformers. Smoother than ReLU.
- Softmax: Converts outputs to probability distribution: .
ReLU is defined as , a piecewise-linear function with derivative . Its key property is that gradients are either 0 or 1 — no exponential decay across layers. Sigmoid has maximum derivative , so chaining layers multiplies gradients by at most — vanishing exponentially. Softmax maps to the probability simplex via . Its Jacobian is , connecting it directly to the cross-entropy gradient .
For z = 2, compute ReLU(z), sigmoid(z), and tanh(z).
Universal Approximation
The Universal Approximation Theorem states that a neural network with a single hidden layer can approximate any continuous function to arbitrary accuracy, given enough neurons.
Key insight: Neural networks are function approximators. Training finds the weights that make the network approximate the target function (mapping inputs to outputs).
Why Depth Matters: While a single wide layer suffices in theory, deep networks learn hierarchical features more efficiently. They can represent some functions exponentially more compactly than shallow networks.
Caveat: The theorem guarantees existence but says nothing about:
- How many neurons are needed
- Whether gradient descent will find the optimal weights
- Generalization to unseen data
The theorem (Cybenko 1989, Hornik 1991) states: for any continuous and any , there exists and parameters such that . The proof uses the Stone-Weierstrass theorem for sigmoidal activations and density arguments for ReLU. The catch is that may grow exponentially with dimension — the curse of dimensionality. Depth helps: functions requiring neurons in a shallow network can sometimes be represented with neurons in a deep network, because composition creates exponentially many linear regions. A ReLU network with layers and neurons per layer partitions input space into at most linear regions.
How can a network with ReLU activations approximate the function f(x) = |x|?
Loss Functions
Loss functions measure how wrong the network's predictions are:
- MSE (Mean Squared Error): For regression. Penalizes large errors heavily. Gradient: .
- Cross-Entropy: For classification. Measures KL divergence between predicted and true distributions.
- Binary Cross-Entropy: for binary classification.
- Huber Loss: Less sensitive to outliers than MSE.
Gradient Behavior: Cross-entropy has better gradient properties than MSE for classification—when predictions are very wrong, gradients are larger, enabling faster learning.
MSE loss is the negative log-likelihood under a Gaussian noise model where . Cross-entropy is the negative log-likelihood under a categorical distribution — it equals the KL divergence plus the entropy , which is constant during optimization. The gradient of cross-entropy with softmax simplifies to , which is bounded and well-conditioned. MSE with sigmoid outputs has gradient which vanishes when predictions are confident, making training slow.
True label is cat (class 1). Model predicts [0.7, 0.2, 0.1] for [cat, dog, bird]. Compute cross-entropy loss.
Theory Exercise
Problem:
A neuron has inputs x = [1, 2], weights w = [0.5, -0.3], and bias b = 0.1. Calculate the output using (a) linear activation, (b) ReLU, and (c) sigmoid.
Hints:
- First compute the weighted sum: z = w·x + b
- z = 0.5×1 + (-0.3)×2 + 0.1
- Apply each activation function to z
Related Problems on PixelBank
The last topic ended with a loss function that scores how wrong the network is, but scoring the error is useless unless we can reduce it. A modern network has millions of weights, and each one nudges the loss by some tiny amount; to improve the network we need the gradient of the loss with respect to every single weight. Computing those millions of partial derivatives naively, one finite-difference at a time, would be hopeless. Backpropagation is the algorithm that computes them all efficiently in a single backward sweep, and it is the engine behind essentially all deep-learning training. Its foundation is the chain rule of calculus: the loss depends on a weight only through a chain of intermediate quantities, and the chain rule multiplies the local derivatives along that chain. This topic develops backpropagation step by step — the chain rule that decomposes the gradient, the gradient-descent update that uses it, the vanishing and exploding gradients that plague deep chains, and the computational graph that frameworks like PyTorch traverse automatically when you call backward.
Definition
Backpropagation computes the gradient of the loss with respect to every network parameter by applying the chain rule backward through the layers, reusing intermediate results so all gradients cost roughly one extra forward pass. Gradient descent then updates each weight in the direction that lowers the loss.
In this topic
- 1Chain Rule
- 2Gradient Descent Update
- 3Vanishing/Exploding Gradients
- 4Computational Graph
Chain Rule
Backpropagation applies the chain rule to compute how the loss changes with a weight buried deep in the network. The loss depends on the weight only through a chain: sets the pre-activation , which sets the layer output , which finally sets . Each factor , , and is a simple local derivative, and multiplying them gives the full gradient. Because these factors are computed once and reused across every path that shares them, backprop is efficient. The failure mode is a broken chain — a non-differentiable step severs it — which is why activations must be differentiable, connecting back to the activation functions of the previous topic.
For a composition , the chain rule gives where is the activation at layer . Each Jacobian is a matrix, and the product of matrices determines whether gradients vanish or explode. If all singular values are less than 1, gradients decay exponentially as . Backpropagation computes this product right-to-left in time, where is the number of parameters — the same order as the forward pass.
For , , , find when , , .
Gradient Descent Update
Once backpropagation supplies the gradient, gradient descent actually changes the weights. The update steps each weight opposite to its gradient, because moving against the slope lowers the loss. The learning rate scales the step: too small and training crawls, too large and the update overshoots the minimum and can diverge, oscillating with growing loss. The gradient tells us both the direction and, through its magnitude, how sensitive the loss is to that weight. This is the same minimize-an-error idea as least squares from the previous chapter, but solved iteratively rather than in closed form because the loss surface is non-convex.
SGD updates parameters via . For a quadratic loss surface , convergence requires where is the largest eigenvalue of the Hessian . The condition number determines convergence speed: . Adam adapts per-parameter learning rates using running estimates of first moment and second moment , effectively scaling by — larger for rare features, smaller for frequent ones.
Weight w=2.0, gradient ∂L/∂w = 0.5, learning rate α=0.1. Compute the updated weight.
Vanishing/Exploding Gradients
In a deep network the gradient reaching an early layer is a product of many per-layer factors, one from each layer above. That product misbehaves in two opposite ways. If the factors stay below one — sigmoid derivatives peak at only — the product shrinks exponentially with depth, so early layers receive almost no gradient and learn glacially: the vanishing gradient. If the factors exceed one, the product blows up and updates become unstable: the exploding gradient. The cure is to keep each factor near one, using ReLU activations, careful weight initialization, batch normalization, and residual connections — the very innovations covered later in this chapter.
Consider a deep linear network . The gradient norm scales as . If each , then the product is — exponential growth for (explosion) and decay for (vanishing). Xavier initialization sets so that output variance equals input variance. He initialization uses to account for ReLU zeroing half the activations. Gradient clipping bounds — geometrically, it projects the gradient onto a ball of radius , preserving direction.
A 10-layer network uses sigmoid (max derivative 0.25). How much does the gradient shrink reaching layer 1?
Computational Graph
A computational graph represents the network as nodes for operations and edges for the tensors flowing between them. Backpropagation is just a disciplined traversal of this graph. In the forward pass each node computes its output and caches the intermediate values; in the backward pass the graph is walked in reverse, and each node multiplies the incoming upstream gradient by its own local derivative to route gradient to its inputs. Frameworks like PyTorch build this graph automatically as your code runs — autograd — so one .backward() call computes every parameter's gradient. The main cost is memory: every cached activation is held until backward consumes it, straining GPU memory.
A computational graph is a directed acyclic graph (DAG) where nodes represent operations and edges carry tensors. The forward pass evaluates nodes in topological order in time. The backward pass traverses the reverse topological order, applying the chain rule at each node. For a node computing , the backward pass computes and where is the upstream gradient. Memory cost is because all intermediate activations must be stored for the backward pass — this is why memory, not compute, is often the bottleneck. Gradient checkpointing trades memory for compute by recomputing activations.
For with x=3, y=4, what are the local gradients?
Theory Exercise
Problem:
For a single neuron with sigmoid activation, input x=1, weight w=0.5, bias b=0, and target y=1, compute the gradient ∂L/∂w using MSE loss.
Hints:
- Forward: z = wx + b, a = σ(z), L = ½(y-a)²
- Chain rule: ∂L/∂w = ∂L/∂a × ∂a/∂z × ∂z/∂w
- σ'(z) = σ(z)(1 - σ(z))
Related Problems on PixelBank
Everything so far has treated an input as a flat vector of numbers, but an image is not a flat vector — it is a grid where nearby pixels are related and the same object can appear anywhere in the frame. A fully connected network ignores this: it wires every pixel to every neuron, which explodes the parameter count and forces the network to relearn the same edge detector separately at every location. Convolutional neural networks fix both problems by reusing the convolution operation from the image-processing chapter, but now the filter weights are learned rather than hand-designed. A small kernel slides across the image, sharing its weights at every position, so a feature learned in one corner is recognized everywhere, and the parameter count stays small. This topic builds the CNN from its pieces: the convolution that extracts local features with shared weights, the pooling that shrinks spatial resolution and adds translation tolerance, the overall layered architecture that grows from edges to objects, and the receptive field that quantifies how much of the image each deep neuron can ultimately see.
Definition
A convolutional neural network processes images with layers of learnable convolution kernels that slide across the input, sharing weights to detect the same feature at every location. Interleaved pooling layers reduce spatial resolution, so stacked layers build a hierarchy from simple edges to complex objects with far fewer parameters than a fully connected network.
In this topic
- 1Convolution Operation
- 2Pooling
- 3CNN Architecture
- 4Receptive Field
Convolution Operation
Convolution slides a small kernel (filter) across the image, computing a weighted sum at each position:
- : Input image or feature map
- : Kernel (learnable filter weights)
- : Convolution operator (actually correlation in practice)
Key Properties:
- Weight sharing: Same kernel everywhere → fewer parameters
- Translation equivariance: Shifted input → shifted output
- Local connectivity: Each output depends only on a small region
Output Size: where =padding, =stride
The discrete 2D convolution is where is a kernel. For an input of size with channels and filters, the output size is where is padding and is stride. The operation has parameters — dramatically fewer than a fully connected layer which would need parameters. This parameter sharing exploits translation equivariance: where is a spatial shift.
Input is 32×32, kernel is 5×5, stride=1, padding=0. What's the output size?
Pooling
Pooling reduces spatial dimensions by taking the max (or average) over small regions:
- Reduces computation: Fewer parameters in later layers
- Translation invariance: Small shifts in input don't change output much
- Larger receptive field: Each neuron 'sees' a larger portion of the original image
Types:
- Max pooling: Takes maximum value—preserves strongest activation
- Average pooling: Takes mean—smoother downsampling
- Global pooling: Reduces entire feature map to single value
Modern Trend: Strided convolutions often replace pooling as they're learnable.
Max pooling selects the maximum over each window: . It reduces spatial dimensions by factor while preserving the strongest activations. The gradient flows only to the argmax location (winner-take-all), making it a form of local routing. Average pooling computes and distributes gradients equally. Global average pooling (GAP) over the entire feature map produces a vector, replacing fully connected layers and reducing parameters from to . Pooling provides a degree of translation invariance: small shifts in input produce the same pooled output.
Apply 2×2 max pooling to: [[1, 3], [2, 4]]. What's the output?
CNN Architecture
A typical CNN stacks convolutional blocks followed by fully connected layers:
- Early layers: Learn simple features (edges, colors)
- Middle layers: Combine into textures, parts
- Deep layers: Recognize high-level concepts (faces, objects)
- Classifier: Makes final decision
Key Architectures:
- LeNet (1998): First successful CNN
- AlexNet (2012): ImageNet breakthrough, ReLU, dropout
- VGG (2014): Deep 3×3 convolutions
- ResNet (2015): Skip connections, 100+ layers
- EfficientNet (2019): Compound scaling
A typical CNN stacks convolution blocks , progressively reducing spatial resolution while increasing channel depth. If the input is , after 5 pooling layers of stride 2 the spatial dimensions are . The FLOPs for a conv layer are . VGG-16 uses 138M parameters and 15.5G FLOPs. Modern architectures use depthwise separable convolutions to factorize the into , reducing compute by factor .
A CNN has 3 conv layers (64, 128, 256 channels) with 3×3 kernels. How many parameters in the second conv layer?
Receptive Field
The receptive field is the region of the input image that influences a particular output neuron. It grows with each layer:
- : Kernel size
- : Stride at layer
Why It Matters:
- Must be large enough to see relevant context
- Deeper layers = larger receptive fields = global context
- Trade-off: large RF needs many layers or large kernels
Effective RF: In practice, not all input pixels contribute equally—central pixels have more influence (Gaussian-like distribution).
The receptive field of a neuron in layer is the region of the input that influences its activation. For a stack of layers each with kernel size and stride , the receptive field grows as . With and , each layer adds 2 pixels: after 5 layers, . With pooling, the growth is exponential in depth. The effective receptive field (ERF) — the region that actually contributes significantly to the output — is much smaller than the theoretical one, typically following a Gaussian distribution centered on the neuron. Dilated convolutions increase the receptive field to without reducing resolution, where is the dilation rate.
Three 3×3 conv layers with stride 1. What's the total receptive field?
Theory Exercise
Problem:
Apply a 3×3 edge detection kernel to a 5×5 image. The kernel is [[-1,-1,-1],[0,0,0],[1,1,1]]. Calculate the output size and the value at position (1,1) of the feature map.
Hints:
- Output size = input_size - kernel_size + 1
- For position (1,1), center the kernel at input position (2,2)
- Multiply element-wise and sum
Related Problems on PixelBank
The plain CNN of the previous topic works, but a naive attempt to make it very deep fails: stacking dozens of layers actually raised training error in practice, because the vanishing-gradient problem from earlier in this chapter starves the early layers of signal. Modern architecture is largely the story of engineering around that limit, and this topic surveys the innovations that made today's state-of-the-art possible. ResNet's skip connections give the gradient a direct highway back through the network, letting layers learn a small residual and enabling networks over a hundred layers deep. Vision Transformers borrow self-attention from language models so every image patch can attend to every other from the very first layer, capturing global context that convolution reaches only gradually. Batch normalization stabilizes and speeds training by renormalizing each layer's activations, and dropout regularizes by randomly silencing neurons so the network cannot over-rely on any one path. Together these four ideas — residual connections, attention, normalization, and dropout — are the components underlying nearly every modern vision system, and understanding each explains why deep networks finally became trainable at scale.
Definition
Modern architectures combine four key innovations: residual (skip) connections that let gradients flow directly through very deep networks, self-attention that captures global context by relating every position to every other, batch normalization that stabilizes training by renormalizing activations, and dropout that regularizes by randomly deactivating neurons.
In this topic
- 1Residual Learning (ResNet)
- 2Self-Attention (Transformers)
- 3Batch Normalization
- 4Dropout
Residual Learning (ResNet)
ResNet introduced skip connections that add the input directly to the output of a block:
- : The residual function learned by the conv layers
- : Identity mapping (skip connection)
- : Block output
Key insight: It's easier to learn small residuals than the full mapping. If the optimal function is close to identity, the network can simply learn . This enables training networks with 100+ layers.
A residual block computes where is the residual function. The gradient through the skip connection is , so the identity matrix ensures gradients always have a direct path — they cannot vanish through the skip connection. For a network with residual blocks, the gradient decomposes into paths of different lengths. The loss surface of ResNets is empirically smoother (smaller Lipschitz constant of the gradient) than plain networks, enabling higher learning rates. ResNet-50 achieves 76% top-1 on ImageNet with 25.6M parameters — the skip connections make training 152-layer networks practical where plain networks of the same depth fail to converge.
In a ResNet block, input x=10, and the conv layers output F(x)=2. What is the block output?
Self-Attention (Transformers)
Self-attention lets every position in a sequence look directly at every other position and decide what to focus on. Each position emits a query (what it is looking for), a key (what it contains), and a value (what it offers). The dot product scores how well each query matches each key, softmax turns those scores into weights, and the weighted sum of values is the output. The factor rescales the scores so they do not grow with dimension and saturate the softmax. Vision Transformers apply this to image patches, gaining global context from the first layer — unlike convolution, which only widens its receptive field gradually across depth.
Self-attention computes where are queries, keys, and values. The dot product has entries, each measuring similarity between a query-key pair — this is why attention is in both time and memory. The scaling prevents the dot products from growing with dimension (variance of a sum of products is , so dividing by normalizes to unit variance). Multi-head attention splits dimensions into heads of size , allowing each head to attend to different representation subspaces. Vision Transformers (ViT) split an image into patches, treating each as a token — for 224x224 with P=16, this gives tokens.
A ViT splits a 224×224 image into 16×16 patches. How many tokens (patches) are there?
Batch Normalization
Batch Normalization renormalizes a layer's activations using the statistics of the current mini-batch. It subtracts the batch mean and divides by the batch standard deviation , so each activation has roughly zero mean and unit variance, then rescales with learnable parameters and so the network can undo the normalization when useful. This keeps activations in a well-behaved range, which smooths the loss surface, permits higher learning rates, and reduces the vanishing-gradient trouble from earlier in this chapter. Its failure mode is small batches: with too few samples the batch statistics are noisy and unreliable, which is why alternatives like layer normalization are used in transformers.
For a mini-batch , BN normalizes: then scales and shifts: . Here and . BN reduces internal covariate shift — the changing distribution of layer inputs during training. Mathematically, BN makes the loss landscape smoother: the Lipschitz constant of the loss is bounded, enabling larger learning rates. During inference, and are replaced by running averages computed during training — the BN layer becomes a fixed affine transform.
Batch activations are [2, 4, 6, 8]. Compute the normalized values (ignore γ, β).
Dropout
Dropout randomly sets each neuron to zero during training with probability , then scales the survivors by so the expected output is unchanged. By training with a different random subset of neurons on every step, the network cannot lean on any single neuron or fragile co-adapted group, so it learns redundant, robust features — in effect training an ensemble of many thinned subnetworks that share weights. At test time dropout is switched off and all neurons are used. The main failure mode is misuse: too large a starves the network of capacity and underfits, and applying dropout at inference would inject noise, so it is a training-only regularizer.
During training, dropout sets each neuron to zero with probability , then scales surviving activations by : where . This is equivalent to training an ensemble of thinned networks (where is the number of neurons) that share weights. At test time, all neurons are active and no scaling is needed (inverted dropout). The expected output is unchanged: . Dropout can be interpreted as approximate Bayesian inference — it samples from an approximate posterior over network weights, providing uncertainty estimates via Monte Carlo dropout at test time.
Dropout p=0.5 applied to [2, 4, 6, 8] with mask [1, 0, 1, 0]. What's the output during training?
Theory Exercise
Problem:
In a ResNet block, the input x has shape [B, 64, 32, 32]. Two 3×3 conv layers with 64 filters are applied (with padding=1). Show that the skip connection is possible and explain why.
Hints:
- With padding=1 and kernel=3, output size = input size
- Both conv layers have 64 input and 64 output channels
- For addition, tensors must have same shape