Guide to AI and Data Courses · Lecture Notes

Chapter 5: Deep Learning

If a phone app is to recognize plant diseases from a leaf photo, the engineer does not write rules or features that describe each disease; the photos and their labels are fed to a network, and the network learns edges, texture and spots by itself. Deep learning is the course about this idea: learning representations from raw data, layer by layer. These notes introduce the course and work through its three core ideas with small examples you can compute by hand: convolution and pooling on images, the tools that make a deep network trainable, and the self-attention at the heart of transformers.

Learning outcomes

Representation learning
Explain, with an example, what separates deep learning from hand-designed features: layers learn increasingly abstract representations from raw data.
Convolution and pooling
Apply a filter to a small image, compute output sizes and parameter counts, and do pooling by hand.
Training tools
Compute a few steps of SGD, momentum and Adam; say why we use batch normalization and residual connections.
Attention
Compute self-attention weights and output for a three-element sequence; explain why transformers need position information supplied separately.
Place of the course
State what separates deep learning from neural networks, classical machine learning, computer vision and generative models.

5.1What question does the course ask?

How do many-layered networks learn useful representations from raw data?

Deep learning studies how multilayer neural networks learn useful intermediate representations from raw data (pixels, audio, text) on their own, layer by layer. The key idea is representation learning instead of hand-designed features; big data, GPUs and good architectures make it possible.

In classical machine learning much of the work is feature design: edge histograms are extracted from an image, word counts from a text, and the model is built on those features. In deep learning the model takes the raw data (pixels, audio samples, words) directly and finds the intermediate features, the representations, during training. Early layers capture simple patterns (edges, audio frequencies), later layers combine them (corners, eyes, syllables), and the last layers capture the abstract concepts that decide the class (a leaf spot, the meaning of a word).

Three things make this practical: very large labeled datasets, GPUs that compute in parallel, and architectures that can be trained. Most of the ideas are decades old; the leap of 2012 came when the same ideas met these three resources. So the course is not just "more layers". Each architecture builds an assumption into the model: a convolutional network says "the same pattern can occur anywhere in the image", a recurrent network says "a sequence is read in order", a transformer says "every element may look directly at any other, however far". Choosing the right assumption matters more than depth itself.

5.1.1How the course is organized

The course falls into three parts: architectures (convolutional networks, recurrent networks, transformers), training techniques (optimizers, normalization, dropout, data augmentation) and transfer (adapting a pretrained model to a new task). Backpropagation and gradient descent are assumed from Neural Networks; loss, generalization and the validation set come from Machine Learning. The course adds architecture and training practice on top of that base.

5.1.2At a glance

CriterionDeep Learning
Approachmultilayer representation learning
Inputraw data: images, text, audio
Outputlearned representation and prediction
Success measureaccuracy, loss, scaling
Math loadhigh: derivatives, matrices, probability
Data needslarge; needs GPUs

5.2A short history

YearMilestone
1997Hochreiter and Schmidhuber propose the LSTM: a cure for vanishing gradients on long sequences.
1998LeCun et al.'s LeNet-5 convolutional network recognizes handwritten digits.
2006Hinton et al. train deep belief networks with layer-wise pretraining; interest revives.
2012AlexNet, a convolutional network trained on GPUs, wins ImageNet by a wide margin.
2015He et al.'s residual networks (ResNet) win ImageNet with 152 layers.
2017Vaswani et al. introduce the transformer architecture: attention only.

5.3Core concepts

The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.

ConceptMeaning
Representation learningLayers learn ever more abstract features, from edges to objects.
ConvolutionSmall filters slide over the image; weights are shared.
PoolingShrinks spatial size, adds robustness to small shifts.
Recurrent networkRNN and LSTM: process a sequence step by step, carrying a state.
AttentionEach element weighs which other elements of the sequence to look at.
Residual connectionA path that skips a layer; makes very deep networks trainable.
NormalizationBatch and layer normalization stabilize training.
Transfer learningAdapting a model trained on big data to a new task.

5.4Convolution and pooling

Feeding an image to an ordinary fully connected network causes two problems. The first is the parameter count: producing an intermediate output of 24×24×6 = 3456 values from a tiny 28×28 image needs 784 · 3456 = 2,709,504 weights in a fully connected layer. The second is that a pattern (say a vertical edge) means the same thing everywhere in the image, yet this layer learns something separate for every position. Convolution solves both: a small filter (kernel) slides over the image and computes a sum with the same weights at every position. The weights are shared across positions.

Definition 5.1 (Convolution (strictly, cross-correlation))

Apply a k × k filter to an n × n image with stride s and p zeros of padding on every side, and the output side is (n − k + 2p)/s + 1. Each output value is the sum of the element-wise products of the filter and the image window it sits on. Libraries do not flip the filter; mathematics calls this cross-correlation, deep learning calls it "convolution".

Example 5.1: A vertical-edge filter

In a 5×5 binary image the left two columns are 1 and the rest 0; only in the third and fourth rows is the third column also 1 (so the edge is not straight). The filter is a 3×3 kernel whose every row is [1, 0, −1]; stride 1, no padding, so the output side is (5 − 3)/1 + 1 = 3.

Image
11000
11000
11100
11100
11000
  1. Top-left window (rows 1–3, columns 1–3): the three rows contribute (1 + 0 − 0) + (1 + 0 − 0) + (1 + 0 − 1) = 1 + 1 + 0 = 2.
  2. Top-middle window (columns 2–4): (1 − 0) + (1 − 0) + (1 − 0) = 3.
  3. Top-right window (columns 3–5): 0 + 0 + (1 − 0) = 1.
  4. The other six windows are computed the same way. The output is [[2, 3, 1], [1, 3, 2], [1, 3, 2]]: the large values in the middle column mark the edge where the image goes from 1 to 0.
  5. Pooling. Take another 4×4 feature map [[1,3,2,0],[4,2,0,1],[0,1,5,2],[2,3,1,1]]. Taking the largest value in each non-overlapping 2×2 window (max pooling) gives [[4, 2], [3, 5]]; taking the average gives [[2.5, 0.75], [1.5, 2.25]]. The size drops to a quarter.

In a real network the filter is not written by hand; its weights are learned by training. The filters of the first layer typically turn into edge and color-transition detectors.

LayerOutput sizeParameters
Input28 × 28 × 10
Convolution 5×5, 6 filters24 × 24 × 65·5·1·6 + 6 = 156
Max pooling 2×212 × 12 × 60
Convolution 5×5, 16 filters8 × 8 × 165·5·6·16 + 16 = 2416
Max pooling 2×24 × 4 × 160

The table shows a small LeNet-style network. The first convolution layer works with only 156 parameters; a fully connected layer would need 2.7 million weights for the same output. Pooling has no learned parameters; it shrinks the size and gives robustness to shifts of a few pixels. Layer by layer the image gets smaller and the number of filters grows: spatial detail turns into abstract features.

Common mistake

Believing that convolution also makes the network robust to rotation or scaling. Weight sharing helps only with translation (if a pattern slides elsewhere in the image, the same filter gives the same response). For rotation and scale changes the network has to see them in the data, that is, they must be taught by data augmentation.

5.5Training a deep network: momentum, Adam and normalization

The loss of a deep network depends on millions of parameters and is not a smooth bowl: steep in one direction, almost flat in another, with valleys and saddle points. Plain gradient descent (SGD) looks only at the current gradient at every step. We improve it in two ways. Momentum also takes the accumulation of past gradients into account: v ← βv + g, w ← w − ηv; speed builds up in a consistent direction and damps itself in oscillating ones. Adam keeps both an exponential average of the gradient (m) and of its square (v) and sets the step to η · m̂ / (√v̂ + ε); each parameter's step is thus divided by its own gradient scale.

Example 5.2: Three optimizers, one loss

Loss L(w) = w2 (gradient 2w), start w = 1, η = 0.1. Momentum uses β = 0.9; Adam uses β1 = 0.9, β2 = 0.999, and ε is negligibly small.

  1. SGD. g = 2: w = 1 − 0.1·2 = 0.8. Then g = 1.6: w = 0.64.
  2. Momentum. v = 0.9·0 + 2 = 2, w = 1 − 0.2 = 0.8. Second step: g = 1.6, v = 0.9·2 + 1.6 = 3.4, w = 0.8 − 0.34 = 0.46.
  3. Adam, step 1. m = 0.1·2 = 0.2, v = 0.001·4 = 0.004. Because they start at zero they are corrected: m̂ = 0.2/(1 − 0.9) = 2, v̂ = 0.004/(1 − 0.999) = 4. The step is 0.1 · 2/√4 = 0.1, so w = 0.9.
  4. Adam, step 2. g = 1.8; m = 0.36, v ≈ 0.007236; m̂ ≈ 1.895, v̂ ≈ 3.620. The step is ≈ 0.0996, w ≈ 0.8004.

Whether the gradient is 2 or 200, Adam's first two steps are almost exactly η; the scale of the gradient is divided out. Momentum drops to w ≈ 0.062 at the third step and passes 0 at the fourth; SGD creeps along at 0.512 after the third step.

5.5.1Batch normalization

Learning gets harder as the input distribution of the layers drifts during training. Batch normalization rescales the values in a mini-batch to mean 0 and variance 1, then shifts them again with learned γ and β: y = γ · (x − μ)/√(σ2 + ε) + β.

Example 5.3: Normalizing four values

The inputs of one neuron over a mini-batch are 2, 4, 6, 8; γ = 2, β = 1, and ε is neglected.

  1. Mean μ = 5; variance σ2 = (9 + 1 + 1 + 9)/4 = 5, σ ≈ 2.236.
  2. Normalize: (x − 5)/2.236 ≈ −1.342, −0.447, 0.447, 1.342.
  3. Scale and shift: 2z + 1 ≈ −1.683, 0.106, 1.894, 3.683.

In training, batch normalization uses the statistics of the batch; at inference it uses moving averages accumulated during training.

Very deep networks have one more problem: the gradient is multiplied layer after layer on its way back and can vanish. A residual connection builds the layer as y = x + F(x); its derivative is 1 + F'(x), so the gradient flows straight through the skip path. In a plain 20-layer network where every layer has local derivative 0.5, the gradient shrinks to 0.520 ≈ 10−6; with residual connections and F' = 0.05 the product is 1.0520 ≈ 2.65 (the values are illustrative). This is why ResNet's 152 layers can be trained.

Common mistake

Thinking that with Adam there is no need to tune the learning rate. In the example above, taking η = 2 gives w = 1 − 2 = −1 at the first step: the loss does not decrease, it stays at L = 1. The step size is bounded by η, and you still choose the right scale.

5.6Self-attention and transformers

Recurrent networks (RNN, LSTM) read a sequence step by step and carry a state; information between two distant elements has to pass through that state many times. Attention shortens this path: each element looks directly at all the elements of the sequence and chooses with weights how much importance to give to each. The transformer architecture drops recurrence entirely and is built on attention alone.

Definition 5.2 (Scaled dot-product self-attention)

For every element a query q, a key k and a value v vector are produced (the input times learned matrices). The output is softmax(QKT/√d) · V: the dot product of the query with every key is divided by √d, turned into weights by softmax, and the values are summed with those weights.

Example 5.4: Attention in a three-element sequence

The vectors of three elements are x1 = (1, 0), x2 = (0, 1), x3 = (1, 1). To keep the numbers small we take the query, key and value matrices to be the identity (so q = k = v = x), with d = 2. Let us compute the output of the third element.

  1. Dot products. q3·k1 = 1, q3·k2 = 1, q3·k3 = 2.
  2. Scaling. Dividing by √2 ≈ 1.414 gives 0.707; 0.707; 1.414.
  3. Softmax. e0.707 ≈ 2.028, e1.414 ≈ 4.113; the sum is ≈ 8.169. The weights are ≈ 0.248; 0.248; 0.503.
  4. Output. 0.248·(1, 0) + 0.248·(0, 1) + 0.503·(1, 1) ≈ (0.752; 0.752).

The third element attended most to itself (weight 0.503) and gave the rest equally to the others. In training the matrices are learned so that the weights concentrate on the elements useful for the task: in translation, a pronoun attends to its subject.

Why divide by √d? As the dimension grows, dot products grow in magnitude; at extreme values softmax gives nearly all the weight to a single element and its gradient begins to vanish. The division balances this. A transformer block runs this attention in parallel as several heads and then adds a small feedforward network, a residual connection and layer normalization; these blocks are stacked. Because the attention matrix computes all pairs, its cost grows with the square of the sequence length, but all steps can be computed in parallel, so on GPUs training is much faster than for an RNN. This scalability underlies the large language models you will meet in Natural Language Processing.

Common mistake

Thinking that self-attention knows order. In the calculation above, if we permute the elements the outputs are simply permuted the same way; attention treats the elements like a set. That is why transformers add a positional encoding to every input. Without it, "dog bit man" cannot be told from "man bit dog".

5.7How is the course taught?

5.7.1A typical workflow

Raw datapixels, audio,textChoosearchitectureCNN, RNN,transformerTrain onGPUmini-batch,AdamRegularizedropout,augmentationFine-tunetransferlearning
Figure 5.1: A typical workflow in Deep Learning

An app that recognizes plant diseases collects leaf photos, takes a ResNet pretrained on ImageNet, replaces its last layer with the disease classes and fine-tunes it on a GPU with data augmentation. No feature is defined by hand.

5.7.2Topics over the semester

  1. Deep feedforward networks and computational graphs
  2. Optimization: SGD, momentum, Adam
  3. Regularization: dropout, weight decay, augmentation
  4. Batch and layer normalization
  5. Convolutional networks: convolution and pooling
  6. CNN architectures: LeNet, AlexNet, VGG, ResNet
  7. Transfer learning and fine-tuning
  8. Recurrent networks: RNN, LSTM, GRU
  9. Sequence-to-sequence models and attention
  10. Transformers and self-attention
  11. Autoencoders and self-supervised learning
  12. Interpreting deep networks: saliency maps

This is a typical semester; the order and coverage vary between universities.

5.7.3Skills you will gain

  • building and training models in PyTorch
  • GPU training and mini-batch tuning
  • fine-tuning pretrained models
  • monitoring training with TensorBoard
  • using Hugging Face models
  • designing hyperparameter experiments

5.7.4Try it yourself

The Try It: How Do Filters See a Line? slide in the presentation lets you solve a typical problem of this course yourself: A school app will recognize signs drawn by children. Click the left grid to draw; two convolution filters scan the picture, and class scores come out of the feature maps.

5.8Are you ready for this course?

5.8.1Prerequisites

CourseWhy it is needed
Artificial Neural Networksmultilayer networks, backpropagation, activation functions
GPU Programming and Parallel Computingparallel training of large networks, tensor operations
Calculusmultivariable derivatives and the chain rule
Programmingcomfort with Python, NumPy and a deep learning library

5.8.2Ask yourself

For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.

QuestionIf not, start with
Can you explain backpropagation step by step in a small network?Artificial Neural Networks
Can you compute the gradient of a multivariable function?Partial derivatives and the chain rule from calculus
Can you say how shapes must match in a matrix product?Linear Algebra
Can you write a class in Python and work with NumPy arrays?An intro programming course, then a short NumPy tutorial

5.9Neighboring courses

Neural NetworksGPU & Parallel ComputingNLPReinforcement LearningGenerative ModelsComputer VisionSpeech and AudioTime SeriesEmbedded AIDeep Learning
subfieldbuilds onshares methodsapplication
Figure 5.2: Neighbors of Deep Learning and the kind of relation

5.9.1Where it overlaps

RelationCourseShared ground
subfieldThis course is a subfield of Artificial Neural Networksmultilayer networks, backpropagation, activation functions
subfieldGenerative Models is a subfield of this courseGANs, VAEs, diffusion, large language models
builds onThis course builds on GPU Programming and Parallel Computingparallel training of large networks, tensor operations
applicationEmbedded AI applies the methods of this coursequantization, pruning, small models
shares methodsShares methods with Natural Language Processing and Text Miningword embeddings, transformer architecture
shares methodsShares methods with Reinforcement Learningdeep Q-networks, deep policy networks
shares methodsShares methods with Computer Visionconvolutional neural networks, vision transformers
shares methodsShares methods with Speech Recognition and Audio Processingend-to-end speech recognition
shares methodsShares methods with Time Series Analysis and Forecastingrecurrent networks, attention-based forecasting

5.9.2Where it differs

  • Artificial Neural Networks: ANN builds neurons, loss and backpropagation on small networks; this course covers deep architectures and the practice of training them.
  • Machine Learning: Classic ML works with hand-designed features; deep learning learns features from raw data by itself.
  • Computer Vision: Computer vision is the problem of understanding images; deep learning is a toolkit shared by vision, language and speech.
  • Generative Models: Generative models aim to sample from the data distribution; this course mostly focuses on discriminative, predictive networks.

5.10In practice

5.10.1Applications

AreaWhat is done
Image classificationRecognizing an object or a disease in a photo.
Speech recognitionTurning an audio recording into text.
Machine translationTransformer-based translation systems.
Object detectionFinding pedestrians and vehicles for a self-driving car.
Protein structurePredicting 3D structure from an amino acid sequence.
Game playingAtari and Go with deep reinforcement learning.

5.10.2Risks and ethics

RiskExplanation
Compute and energy costTraining large models takes thousands of GPU hours and real carbon emissions, concentrating research in a few large organizations.
Adversarial examplesImperceptible pixel changes fool a classifier; researchers showed the same with stickers placed on a stop sign.
Data scraped from the webWeb-scraped datasets such as ImageNet can contain photos taken without consent and offensive labels; ImageNet later removed many of them.
Illusory progressHyperparameters tuned on the test set and results reported from a single seed make small differences look like real gains.

These issues are discussed in depth in Explainable AI and AI Ethics.

5.10.3Tools and datasets

Tools: PyTorch, TensorFlow, Keras, JAX, Hugging Face, CUDA, TensorBoard.

Well-known datasets: ImageNet, CIFAR-10/100, MNIST, COCO, LibriSpeech, Wikipedia text.

5.11Common misconceptions

Common mistake

Deep learning is best for every problem.

On small tabular data, gradient-boosted trees are often better and cheaper.

Common mistake

A deep network is a black box that cannot be inspected.

Tools such as gradient-based saliency maps and attention weights give partial explanations.

Common mistake

Deep learning was invented in 2012.

The ideas are decades old; big data and GPUs brought the 2012 leap.

Common mistake

More layers always mean better results.

Without residual connections and normalization, very deep networks may not train.

5.12Summary

  • Deep learning learns representations from raw data, layer by layer, instead of using hand-designed features; each architecture builds in an assumption (convolution: the same pattern can occur anywhere; attention: every element can look at every other).
  • Convolution scans the image with a small shared filter; the output side is (n − k + 2p)/s + 1, and the parameter count depends on the filter size, not the image size. Pooling shrinks the size.
  • Momentum accumulates past gradients and Adam divides the step by the gradient scale; batch normalization and residual connections make very deep networks trainable.
  • Self-attention turns each element into a weighted sum of all elements with softmax(QKT/√d)V; because it does not know order, positional encoding is needed.
  • Deep learning needs big data and GPUs; on small tabular data classical methods are often enough and cheaper.

5.13Test Yourself

  1. The input is 32×32×3 (RGB). A convolution layer with 16 filters of 3×3, stride 1, padding 1 on every side is applied, followed by 2×2 max pooling (stride 2). Find the output sizes and the parameter count of the convolution layer.

    Answer

    The convolution output is (32 − 3 + 2)/1 + 1 = 32, so 32×32×16. Parameters: 3·3·3·16 + 16 = 448. After pooling: 16×16×16. (A fully connected layer producing 16384 outputs from the same 3072 inputs would need 3072·16384 = 50,331,648 weights.)

  2. L(w) = w2, w = 2, η = 0.1, momentum β = 0.9. What is w after two momentum steps?

    Answer

    Step 1: g = 4, v = 4, w = 2 − 0.4 = 1.6. Step 2: g = 3.2, v = 0.9·4 + 3.2 = 6.8, w = 1.6 − 0.68 = 0.92. (Two SGD steps would have given 1.6 and then 1.28.)

  3. The inputs of a neuron over a batch are 3, 5, 9, 11. Let γ = 1, β = 0 and neglect ε. Find the batch normalization outputs.

    Answer

    μ = 7; deviations −4, −2, 2, 4; σ2 = (16 + 4 + 4 + 16)/4 = 10, σ ≈ 3.162. The outputs are ≈ −1.265, −0.632, 0.632, 1.265: mean 0, variance 1.

  4. In self-attention let x1 = (2, 0), x2 = (0, 2), q = k = v = x, d = 2. Compute the attention weights and the output of the first element.

    Answer

    The dot products are 4 and 0; dividing by √2 gives 2.828 and 0. e2.828 ≈ 16.92, e0 = 1; the weights are 16.92/17.92 ≈ 0.944 and 0.056. The output is 0.944·(2, 0) + 0.056·(0, 2) ≈ (1.888; 0.112).

  5. In a plain 20-layer network every layer has local derivative 0.5. By how much does the gradient reaching a weight at the start of the network shrink under this product? What would the result be if every layer were a residual block y = x + F(x) with F' = 0.05?

    Answer

    In the plain network 0.520 ≈ 9.5 × 10−7: the gradient all but disappears. With residual blocks the product is 1.0520 ≈ 2.65: the gradient does not vanish. (The values are illustrative; in reality derivatives vary from layer to layer.)

  6. A hospital wants to predict patient readmission from a table of 600 rows and 15 columns. Would you suggest a deep network or a classical method? Why?

    Answer

    A classical method (logistic regression or gradient-boosted trees). On small tabular data a deep network overfits and is costly to set up and tune; the table's features are already meaningful. Deep learning shines on raw, high-dimensional data (images, audio, text) and on large datasets. This distinction extends the model-selection theme of Machine Learning.

5.14After this course

Deep learning is the most widely used tool on the map today: computer vision, natural language processing, speech recognition, generative models and deep reinforcement learning are built on it. On the systems side, GPU programming, embedded AI and MLOps teach how to speed these models up and take them to production.

Courses that build on or extend this one: Generative Models, Embedded AI.

Related careers: Deep learning engineer, Computer vision engineer, Researcher, ML infrastructure engineer, Applied scientist.

5.15Further reading

  • I. Goodfellow, Y. Bengio and A. Courville, Deep Learning (2016), Chapters 8 and 9: optimization for deep models and convolutional networks at textbook level.
  • A. Zhang, Z. Lipton, M. Li and A. Smola, Dive into Deep Learning (2023): covers every topic with running code, so you can run the convolution, Adam and attention examples yourself.
  • S. Prince, Understanding Deep Learning (2023): explains the same architectures and training techniques with intuitive figures and plain mathematics.

5.16References

  1. Goodfellow, Bengio and Courville, Deep Learning, MIT Press, 2016.
  2. Zhang, Lipton, Li and Smola, Dive into Deep Learning, Cambridge University Press, 2023.
  3. Prince, Understanding Deep Learning, MIT Press, 2023.
  4. Chollet, Deep Learning with Python, 2nd ed., Manning, 2021.
  5. LeCun, Bengio and Hinton, "Deep learning", Nature 521, 2015.

Related pages: Slides · Slides (PDF) · Course page