Module 2 — Deep Neural Networks
Same theory-first structure as Module 1: for every technique below, what it is, why it exists — the specific limitation of what came before it — what else you could use instead, and a real financial example. Module 1 built a logistic-regression baseline; every concept here exists because that baseline has a specific, nameable limit, and this module builds the tool that addresses it.
Why neural networks, and why now
Module 1's logistic regression is one linear decision boundary. It cannot represent an interaction like "risk is high when debt-to-income is high and credit history is short, but only above a combined threshold" without someone manually engineering that exact interaction term first. That specific gap — not fashion, not hype — is why Module 2 exists.
The panel, not the interviewer
Logistic regression is one interviewer with a fixed checklist. A neural network is a panel of specialists (hidden neurons), each attuned to a different combination of signals, with a final layer combining their opinions.
Pixels aren't ratios
A cheque image is not "16 financial ratios" — meaning lives in local spatial patterns. This is the specific reason Module 2 also introduces CNNs, not just deeper tabular networks.
A second kind of attack
Module 1 showed training data can be poisoned. Module 2 shows a cleanly trained model can still be fooled at prediction time — a different attack surface entirely.
The Perceptron
The smallest possible neural unit — and the historical dead end that explains why depth matters.
A perceptron computes a weighted sum of its inputs plus a bias, then applies a threshold: fire (1) if the sum crosses zero, stay silent (0) otherwise. Every neuron in every network in this entire course — up to and including transformers in Module 4 — is a descendant of this one idea.
✓ What it teaches
- The exact atomic computation (weighted sum + threshold) every later layer reuses
- Why depth, not just width, was historically necessary
✗ What it cannot do alone
- Represent any pattern that isn't linearly separable — including XOR, and by extension most interesting financial risk interactions
Update: w ← w + η(y−ŷ)x
ANN Architecture (Feedforward Networks)
Stacking neurons to fix what one perceptron structurally cannot do.
An Artificial Neural Network (ANN) stacks layers of neurons: an input layer, one or more hidden layers, and an output layer. Each layer's output feeds the next layer's input — literally the perceptron equation, repeated and composed.
| Option | Trade-off |
|---|---|
| Logistic regression (Module 1) | Fast, interpretable, but one linear boundary only |
| Tree-based models (Random Forest, XGBoost) | Capture non-linear interactions well and often win on small-to-medium tabular data with far less tuning than a neural net |
| ANN | Can represent arbitrary non-linear interactions given enough capacity and data — the trade-off is needing more data, more tuning, and losing easy interpretability |
✓ Use it when
- You suspect genuine feature interactions a linear model can't capture
- You have enough data to support the extra capacity without overfitting
✗ Don't reach for it when
- The dataset is small and the relationship is plausibly linear — Module 2's own notebook shows the ANN losing to logistic regression on RR Finance's real 800-row dataset. That is the honest lesson, not a bug: check the simple model first.
Activation Functions
Without them, depth is mathematically pointless.
An activation function is a non-linear transformation applied after each layer's weighted sum. ReLU (rectified linear unit) is the modern default for hidden layers; Sigmoid and Softmax are used on output layers for binary and multi-class probabilities respectively.
✓ Where each belongs
- ReLU: hidden layers, by default
- Sigmoid: output layer, binary classification (e.g. default probability)
- Softmax: output layer, multi-class classification (e.g. 10 cheque digits)
✗ Common mistakes
- Using Sigmoid in deep hidden layers — invites vanishing gradients
- Forgetting Softmax must operate on a vector of scores, not a single number
Backpropagation
How a network figures out which direction to move millions of weights from one number.
Backpropagation is the chain-rule-based algorithm that computes how much each weight in the network contributed to the final error, working backward from the output layer to the input layer, so gradient descent (next lesson) knows which direction to nudge every weight.
| Option | Trade-off |
|---|---|
| Numerical differentiation (perturb each weight, remeasure loss) | Conceptually simple, but requires a full forward pass per weight — computationally impossible at the scale of millions of parameters |
| Backpropagation (reverse-mode autodiff) | Computes gradients for every weight in roughly the cost of one extra forward pass, regardless of how many parameters there are — the only reason training large networks is computationally feasible at all |
.backward() call in every model trained across this entire 12-module course — the cheque-digit CNN here, the fine-tuned LLM in Module 4 — runs on exactly this mechanism. Understanding it once means every later "training is unstable" or "loss exploded" problem has a mechanism you can actually reason about, not just a button you press and hope.Gradient Descent & Optimizers
Backprop tells you the direction. Optimizers decide how far, and whether to remember the last step.
Given a gradient, an optimizer decides the actual weight update. SGD takes a fixed-size step in the gradient's direction; Momentum adds memory of previous steps to smooth noisy updates; RMSprop and Adam adapt the step size per parameter based on recent gradient behaviour.
| Optimizer | When it's the right call |
|---|---|
| SGD (plain) | Simple, sometimes generalises better with careful tuning — common in some published vision benchmarks |
| SGD + Momentum | A strong, well-understood default when you have time to tune the learning rate |
| RMSprop | Good on noisy or non-stationary problems (originally motivated by RNN training) |
| Adam | The reasonable first choice with minimal tuning — used throughout this course's default training loops |
Momentum: v←βv+∇L; w←w−ηv
Adam: combines momentum + per-parameter adaptive step size
Batch Normalisation & Dropout
Two different problems, both fixed by deliberately adding a bit of controlled disruption.
BatchNorm normalises each layer's activations to zero mean/unit variance per mini-batch (then lets the network re-learn an optimal scale), stabilising training. Dropout randomly zeroes a fraction of activations during training only, preventing the network from over-relying on any single neuron.
model.eval() before inference leaves Dropout randomly zeroing activations and BatchNorm using batch statistics instead of learned running statistics — silently corrupting predictions in a way that produces no error message, just quietly wrong numbers. This is one of the most common real-world PyTorch bugs, and the notebook demonstrates it directly rather than just warning about it.Dropout: zero each unit with probability p (train only)
CNN Foundations: Convolution, Padding, Stride, Pooling
Why images need a fundamentally different architecture than tables do.
A convolution slides a small, learnable filter across an image, computing a local dot product at every position — the same pattern-detector is reused everywhere in the image, rather than learning a completely separate weight for every pixel. Pooling then downsamples, keeping the strongest signal in each small region.
| Option | Trade-off |
|---|---|
| Flatten the image, feed a plain ANN | A 28×28 image needs 784 separate weights per neuron, with zero spatial reuse — pixel (0,0) is treated as no more related to pixel (0,1) than to pixel (27,27), throwing away the one thing that makes an image an image |
| Convolution | A 3×3 filter (9 weights) is reused at every position — far fewer parameters, and pattern detection becomes position-independent by construction |
(conv[i,j] = Σ kernel · input patch)
Building and Training a CNN
RR Finance's cheque-digit reader, built from the pieces above.
The lab combines everything so far — convolution, pooling, BatchNorm, Dropout, ReLU, Softmax, backprop, Adam — into one trained model that classifies a 28×28 handwritten digit image into one of 10 classes, using the standard MNIST dataset as a stand-in for real cheque-digit crops.
✓ What this lab teaches
- How the architectural pieces (Lessons 3–7) compose into one trainable system
- Why the flattened size before the final layer follows directly from the pooling arithmetic (28→14→7)
✗ What it doesn't cover yet
- Real cheque images have scan noise, skew, and varied handwriting the clean MNIST set doesn't — Module 8 (Multimodal AI) extends this exact pattern to messier real-world document data
Transfer Learning
Reusing what a network already learned, when you don't have millions of your own labelled images.
Instead of training a CNN from scratch, load a network already trained on a large general dataset (e.g. ImageNet), freeze its early layers (which tend to have learned general-purpose features like edges and textures), and only retrain the final layer(s) for your specific task.
✓ Use it when
- You have a new image task but limited labelled data — exactly RR Finance's real-world cheque-digit situation, where labelled crops are expensive and slow to collect under confidentiality constraints
✗ Be careful when
- Freezing too much prevents adaptation to real quirks (paper texture, ink variation, scan skew)
- Freezing too little re-introduces the "not enough data" problem transfer learning was meant to solve — how much to freeze is itself a hyperparameter to validate
Adversarial Examples: FGSM & PGD
Fooling a correctly trained model, without ever touching its training data.
An adversarial example is an input deliberately perturbed by a tiny, often visually imperceptible amount, crafted specifically to cause a correctly-trained model to misclassify it with high confidence — using the model's own gradients against it.
| Attack | When it happens | What the attacker needs |
|---|---|---|
| Data poisoning (Module 1) | Training time | Ability to influence training data — never touches the deployed model |
| Adversarial examples (this lesson) | Inference time | Access to (or the ability to estimate) the trained model's gradients, plus a small perturbation budget |
PGD: iterate FGSM step, clip to ε-ball, repeat
Adversarial Training
The first defence — and an honest look at its limits.
Adversarial training generates adversarial examples during training and includes them in the training loss, alongside clean examples — explicitly teaching the model to classify attacked inputs correctly too, not just clean ones.
Module 2 hand-off
The notebook benchmarks its ANN against Module 1's exact saved baseline, trains and saves a cheque-digit CNN, and produces a measured (not assumed) adversarial-robustness comparison. Module 3 reuses the same skeleton one more time — business problem → representation → model → cybersecurity angle → lab — this time for text instead of tables or pixels.