Deep Learning Slides 📂 Introduction · 15 of 18 31 min read

Python Implementation of CNNs: Build, Train, Diagnose

Build a convolutional neural network from a blank script. This visual guide stacks conv blocks in Keras, trains on CIFAR-10 with augmentation and dropout, reaches 79% accuracy, then scales to real pneumonia diagnosis with VGG16 transfer learning — every architecture and training choice explained.

Building a CNN in Python

From a blank script to a trained image classifier. We'll build a convolutional network layer by layer, train it on CIFAR-10, then scale up to a real medical diagnosis with transfer learning — every design choice explained.
Conv Blocks in Keras CIFAR-10 Augmentation & Dropout Transfer Learning

Press Next → or use ← → arrow keys

Section 01

Why CNNs Were Born

Feed a 1000×1000 image to a plain neural network and you must first flatten it into a one-million-element vector — throwing away every bit of spatial structure. A CNN keeps the 2-D layout and scans for local patterns, reusing the same detectors everywhere. It sees an eye as an eye wherever it appears.
1989LeCun's first CNN
1998LeNet-5 read bank cheques
15.3%AlexNet's 2012 ImageNet error — a revolution
🧩
Local patterns, shared weights, hierarchy

The three ideas that make CNNs work: look at small patches, reuse one filter across the whole image, and stack layers so simple features combine into complex ones.

Section 02

The Architecture — A Data Assembly Line

An image flows through stations that shrink it spatially while enriching it with channels, ending in class probabilities. Here's the network we'll build:

32×32×3 input 16×16×32 block 1 8×8×64 block 2 4×4×128 block 3 512 dense 10 softmax
📉
Spatial shrinks, channels grow

32×32 → 16×16 → 8×8 → 4×4 as pooling compresses; meanwhile filters climb 32 → 64 → 128. Then flatten and two dense layers turn features into a 10-way decision.

Section 02

The Building Blocks

Every CNN is assembled from a handful of standard layers. Each has one job:

🔲
Conv2D
Slides learnable filters to detect local patterns, producing feature maps.
ReLU
Adds the non-linearity that lets stacked layers learn complex functions.
🔻
MaxPool
Shrinks feature maps, keeping the strongest activations and adding shift-tolerance.
📊
BatchNorm
Normalises each layer's output — faster, more stable training at higher learning rates.
🎲
Dropout
Randomly zeroes neurons in training so the network can't just memorise.
🎯
Dense + Softmax
Flatten, combine features, and output a probability per class.
🧱
The repeating motif

Conv → BatchNorm → ReLU → (Conv…) → Pool → Dropout, stacked into blocks, then a dense head. Learn this pattern and you can read almost any CNN.

Section 03

The Dataset — CIFAR-10

60,000 tiny colour photos across 10 everyday classes — the classic proving ground for image models.

60kImages (50k train / 10k test)
32×32Pixels, 3 colour channels
10Classes — plane, car, cat, dog, ship…
1
Normalise: divide pixels by 255 so values sit in [0, 1] — raw 0–255 inputs make gradients unstable.
2
One-hot the labels: class 3 → [0,0,0,1,0,0,0,0,0,0], ready for softmax + cross-entropy.
⚠️
Never train on raw uint8

Normalising to [0, 1] (and using float32 for GPU speed) is the single most important preprocessing step — skip it and training may never converge.

Section 03

Data Augmentation

Randomly transform each training image on the fly so the network sees endless variations — and learns features that survive real-world wobble.

🔄
Rotate ±15°
A slightly tilted cat is still a cat.
↔️
Shift & zoom ±10%
Objects aren't always centred or the same size.
🪞
Horizontal flip
A mirrored car is a valid car (but never flip digits!).
🚫
Augment training only

Validation and test images stay untouched — you want to measure real-world performance, not performance on artificially varied pictures.

Section 04

The Three Convolutional Blocks

Each block runs conv layers, normalises, pools, and drops out — doubling the filters as the spatial size halves:

BlockLayersFiltersOutput
12× Conv 3×3 + BN → Pool → Dropout 0.253216×16×32
22× Conv 3×3 + BN → Pool → Dropout 0.25648×8×64
3Conv 3×3 + BN → Pool → Dropout 0.251284×4×128
🔑
Why two 3×3 convs instead of one 5×5

Two stacked 3×3 layers cover the same 5×5 receptive field with fewer parameters and an extra ReLU in between — more expressive, cheaper. All use padding='same' and light L2.

Section 04

The Classification Head

After the conv blocks, flatten the feature maps and let dense layers make the final decision:

1
Flatten: (4, 4, 128) → a 2048-element vector.
2
Dense 512 + ReLU + BatchNorm: combine the spatial features into abstract ones.
3
Dropout 0.5: heavy regularisation on the dense layer to fight overfitting.
4
Dense 10 + Softmax: ten class probabilities that sum to 1.
~1.29MTotal parameters
0.25Dropout on conv blocks
0.5Dropout on the dense head
Section 05

Compile & Train Smartly

Pick the optimiser and loss, then let callbacks babysit the training run:

Optimizer: Adam, lr = 0.001
Loss: categorical cross-entropy
Metric: accuracy (for humans)
EarlyStopping — halt when val-loss stalls, restore best
ReduceLROnPlateau — halve LR on a plateau
ModelCheckpoint — save the best model
⏱️
Capped at 100 epochs — usually stops near 47

EarlyStopping ends training once the validation loss stops improving, so you get the best model without wasting compute or overfitting.

Section 05

The Model in Keras

One block, expressed in a handful of layers — repeat with more filters for the deeper blocks:

from tensorflow.keras import layers, models, regularizers

model = models.Sequential([
    layers.Input((32, 32, 3)),
    # Block 1
    layers.Conv2D(32, 3, padding='same', activation='relu',
                  kernel_regularizer=regularizers.l2(1e-4)),
    layers.BatchNormalization(),
    layers.Conv2D(32, 3, padding='same', activation='relu'),
    layers.MaxPooling2D(2),
    layers.Dropout(0.25),
    # ... Block 2 (64 filters), Block 3 (128 filters) ...
    layers.Flatten(),
    layers.Dense(512, activation='relu'),
    layers.BatchNormalization(),
    layers.Dropout(0.5),
    layers.Dense(10, activation='softmax'),
])
model.compile(optimizer='adam', loss='categorical_crossentropy',
              metrics=['accuracy'])
🧩
Sequential = layers in a list

Keras' Sequential API stacks layers top to bottom. Swap the filter counts and you have blocks 2 and 3 — the pattern is deliberately repetitive.

Section 06

Results on CIFAR-10

After training, the custom CNN reaches solid accuracy on held-out test images:

78.9%Test accuracy
0.63Test loss
~47Epochs before early stop
Easiest classes (F1)Hardest classes (F1)
Automobile 0.90 · Ship 0.88 · Horse 0.87Cat 0.62 · Bird 0.69 · Dog 0.69
🐱
Why cats and birds struggle

Animals share fur, poses, and backgrounds, so they blur together. Vehicles have rigid, distinct shapes and separate cleanly. The confusion is in the data, not a bug.

Section 07

Case Study — Pneumonia from X-Rays

With only ~5,900 chest X-rays, training from scratch is hopeless. Transfer learning with a pretrained VGG16 turns a tiny dataset into a strong diagnostic model.

1
Freeze VGG16 (ImageNet weights) and train a fresh head: GlobalAveragePooling → Dense → Sigmoid.
2
Fine-tune the last conv block at a tiny LR (1e-5) to adapt without catastrophic forgetting.
3
Class weights & threshold 0.30 — favour catching pneumonia, since a missed case is far costlier than a false alarm.
0.972AUC-ROC
96%Pneumonia recall — catches nearly all cases
92%Overall accuracy
Section 08

Reading the Loss Curves

The training and validation loss curves are your dashboard. Learn to read them at a glance:

PatternWhat you seeFix
HealthyBoth losses fall together, small gapNothing — ship it
OverfittingTrain ↓ but val ↑More dropout / augmentation
UnderfittingLoss flat from epoch 1Bigger model, higher LR, add BatchNorm
OscillatingLoss bounces wildlyLower the learning rate
📈
Always plot both curves

Accuracy alone hides problems. The gap between train and val loss is what tells you whether to regularise more, train longer, or dial the learning rate.

Section 09

Which Architecture When?

ArchitectureBest forData size
Custom CNNLearning, full control50k–500k
VGG16 (transfer)Medical, domain-specific1k–50k
ResNet50General vision10k+
EfficientNet-B0Production, mobileAny
Vision TransformerMassive datasets1M+
🧭
The quick decision

Under 10k images? Reach for transfer learning. Learning the ropes? Build a custom CNN on CIFAR-10. Shipping to phones? EfficientNet. Have a million labelled images? A Vision Transformer.

Section 10

7 Golden Rules for Building CNNs

  Practitioner's cheat-sheet
1Normalise images first — divide by 255; never train on raw uint8.
2Start with transfer learning for under ~100k images — freeze the base, fine-tune carefully.
3Double the filters after each pool — 32 → 64 → 128 → 256 — trading space for depth.
4BatchNorm + light dropout (0.25 conv, 0.5 dense) — don't stack aggressive dropout and heavy L2.
5Watch AUC-ROC on imbalanced data — accuracy lies when one class dominates.
6Use padding='same' for conv layers and pool explicitly to downsample.
7Fine-tune gently — train the head first, then unfreeze the last block(s) at a 10–100× smaller LR.
🚀
You can now build, train, and diagnose a CNN

Normalise, augment, stack conv blocks, regularise, and read the loss curves. From CIFAR-10 to a medical classifier, it's the same recipe — scaled to the problem.