Deep Learning for Computer Vision (CNNs)
7 min read
Welcome to the visual cortex of Artificial Intelligence! 👁️✨
Up until now, we’ve been throwing raw numbers and flattened arrays at Dense layers. But if you try to flatten a 4K image of a cat into a single line of pixels, you lose something specific: Structure. The network forgets that the ears are physically sitting on top of the head.
In this module, we are ditching the flat land and entering the world of Convolutional Neural Networks (CNNs). This is the tech behind FaceID, self-driving cars, and that filter that turns you into a potato on video calls.
1. Understanding Convolutions and MaxPooling
The Problem with Dense Networks for Images
Imagine you have a small image: 100x100 pixels in color (RGB). That's 30,000 input values. If you connect this to a Dense layer with 1,000 neurons, you are looking at 30 million weights just for the first layer.
- Issue 1: Computationally impossible for large images.
- Issue 2: No spatial invariance. If the cat moves 5 pixels to the left, a Dense network thinks it's a completely new object.
The Solution: The Convolution Operation
A convolution allows the network to look at small "patches" of the image at a time, rather than the whole thing at once.
What is a Convolution?
Mathematically, a convolution is a mathematical operation on two functions that produces a third function expressing how the shape of one is modified by the other.
In Deep Learning terms:
Imagine a small grid (usually 3x3) called a Kernel or Filter. You slide this little grid over your original image, left to right, top to bottom. At every stop, you do a matrix multiplication (dot product) between the filter and the chunk of the image it's hovering over.
- The "Flashlight" Analogy: Imagine you are in a dark room with a flashlight looking at a painting. You can only see a small circle at a time. You scan across the painting to understand the details. The scanner is the Filter. The features you find (eyes, edges, colors) make up the Feature Map.
Industry Fact: Early layers usually detect simple lines and edges. Deeper layers combine those lines to detect shapes (circles, squares). Even deeper layers combine shapes to detect objects (eyes, tires, noses).
The Solution for Size: MaxPooling
After we find features using convolutions, we often end up with a lot of data. We need to reduce the size of the image representation to make computation faster and reduce noise.
Max Pooling simply looks at a patch (say, 2x2 pixels) and keeps only the highest number.
- Why? The highest number represents the strongest presence of a feature. If we found a "sharp edge" in that 2x2 area, we keep the "sharp edge" signal and discard the precise location. We care that the feature exists, not exactly where (to the exact pixel) it is.
2. Building your First Convolutional Neural Network (CNN)
Let's get our hands dirty. We will use the Keras Sequential API.
The Architecture Standard
A standard CNN looks like a sandwich made by a perfectionist:
- Conv2D: Extract features.
- ReLU: Add non-linearity (turn negative numbers to 0).
- MaxPooling: Shrink it down.
- Repeat steps 1-3 (usually 2 or 3 times).
- Flatten: Turn the 3D cube of data into a 1D line.
- Dense: Perform the final classification.
The Code
We will build a model to classify the famous CIFAR-10 dataset (airplanes, cars, birds, cats, etc.).
import tensorflow as tf
from tensorflow.keras import layers, models
# 1. Setup the model
model = models.Sequential()
# 2. First Convolutional Block
# filters=32: The model learns 32 different filters (edge detectors, etc.)
# kernel_size=(3,3): The size of the sliding window
# input_shape=(32, 32, 3): Height, Width, RGB Channels
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
# 3. Second Convolutional Block
# Notice filter count usually increases (32 -> 64) as we go deeper
# because we are detecting more complex combinations of features.
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
# 4. Third Convolutional Block
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
# 5. The Classification Head
model.add(layers.Flatten()) # Convert 3D feature maps to 1D vector
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10)) # Output layer (10 classes for CIFAR-10)
# Check the architecture
model.summary()⚠️ Practical Tip: Always use model.summary() to check your shapes. If your shapes shrink to (0, 0, 64), your model crashes. This usually happens if you pool too many times on a small image.
3. Preventing Image Overfitting with Data Augmentation
The Problem
Neural networks are lazy students. If you show them 100 pictures of a cat facing right, and then test them with a picture of a cat facing left, they will say "That's not a cat." They memorized the pixels, they didn't learn the concept of "cat-ness." This is Overfitting.
The Solution: Data Augmentation
We cannot go out and take a million more photos. Instead, we generate "fake" new data from our existing data.
We randomly:
- Flip the images.
- Rotate them slightly.
- Zoom in/out.
This forces the model to learn that a cat is still a cat, even if it's upside down or zoomed in.
Implementing Augmentation (The Modern Way)
In the old days, we used ImageDataGenerator. That is now "legacy". The modern industry standard is to include augmentation inside the model as layers. This makes deployment easier because the preprocessing travels with the model!
# Define augmentation layers
data_augmentation = tf.keras.Sequential([
layers.RandomFlip("horizontal_and_vertical"),
layers.RandomRotation(0.2), # Rotate by 20%
layers.RandomZoom(0.1),
])
# Use it in your model pipeline
model = models.Sequential([
# Augmentation happens FIRST
data_augmentation,
# Then the pixel rescaling (0-255 -> 0-1)
layers.Rescaling(1./255),
# Then the rest of your CNN...
layers.Conv2D(16, 3, padding='same', activation='relu'),
layers.MaxPooling2D(),
# ... rest of model
])🧪 Fun Fact: If you accidentally rotate your digit '6' too much during training for digit recognition, the model might learn it as a '9'. Context matters!
4. Transfer Learning: Leveraging Pre-trained Models
The Problem
Training a CNN from scratch to high accuracy requires:
- Massive Datasets (Millions of images).
- Massive Compute (Expensive GPUs running for weeks).
- Massive Patience (Which we don't have).
The Solution: Transfer Learning
Why reinvent the wheel? Companies like Google and Microsoft have trained massive models (like ResNet, MobileNet, EfficientNet) on the ImageNet dataset (1.4 million images, 1000 classes).
We can take these models, cut off the "head" (the final classification layer), and attach our own simple classifier. The "body" of the model already knows how to detect edges, curves, fur, eyes, and textures. We just teach it what our specific data looks like.
Industry Standard: MobileNetV2
We often use MobileNetV2 for general tasks because it is lightweight, fast, and runs well on browsers/phones.
The Workflow
- Download the Base Model: Include weights from 'imagenet'.
- Freeze the Base: Set
trainable = False. Crucial! If you don't do this, the random noise from your new dense layers will destroy the beautiful pre-trained weights in the base model during the first backpropagation. - Add your Head: Pooling and Dense layers.
- Train: You are now only training the final few layers.
# 1. Download base model (Headless)
# include_top=False removes the final 1000-class classification layer
base_model = tf.keras.applications.MobileNetV2(
input_shape=(160, 160, 3),
include_top=False,
weights='imagenet'
)
# 2. Freeze the base
base_model.trainable = False
# 3. Build your model on top
inputs = tf.keras.Input(shape=(160, 160, 3))
# We usually need specific preprocessing for pre-trained models
# MobileNet expects pixels between -1 and 1
x = tf.keras.applications.mobilenet_v2.preprocess_input(inputs)
# Pass through base model (running in inference mode)
x = base_model(x, training=False)
# Convert features to a single vector per image
x = layers.GlobalAveragePooling2D()(x)
# Add a Dropout layer to prevent overfitting further
x = layers.Dropout(0.2)(x)
# Final prediction layer (Example: 1 output for Dog vs Cat)
outputs = layers.Dense(1)(x)
model = tf.keras.Model(inputs, outputs)
# Compile
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.0001),
loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])Fine-Tuning (Advanced)
Once the new head is trained and stable, you can "unfreeze" the top few layers of the base model and train them with a very low learning rate. This adapts the high-level features (specific object shapes) to your specific dataset.
🛑 Warning: Do not fine-tune until your top layer is trained! If you fine-tune a random head on a pre-trained base, the gradients will be too large and shatter the pre-trained weights.
📚 Resources & References
- TensorFlow: CNN Tutorial
- TensorFlow: Data Augmentation
- TensorFlow: Transfer Learning guide
- Visualizing what ConvNets learn (Distill.pub) - Highly recommended for visual learners!
🧪 Practical Challenge
Take a photo of your desk. Write a script using the pre-trained MobileNetV2 code above to see if it detects a "computer mouse" or "coffee mug". You'll be surprised how robust it is without you writing a single line of feature extraction code!
Challenge
Task
Your goal is to construct a Keras Sequential model for binary image classification using the transfer learning technique with MobileNetV2.
Requirements
- Instantiate the
MobileNetV2model as a base model. You must use the pre-trained'imagenet'weights, exclude the top classification layer, and set theinput_shapeto(160, 160, 3). - Freeze the entire base model to prevent its weights from being updated during training.
- Create a new
Sequentialmodel. - The first layer of your new model must be the frozen
base_model. - Add a
GlobalAveragePooling2Dlayer to process the output from the base model. - Add a
Dropoutlayer with a rate of0.2for regularization. - Add the final classification layer: a
Denselayer with a single output unit and asigmoidactivation function.
Expected result
The output should be the summary of a Keras Sequential model printed to the console. The summary must show the following structure:
- The model type is
Sequential. - The first layer is the
mobilenetv2model, which should have a large number of parameters (over 2 million), all of which are non-trainable. - The subsequent layers must be
global_average_pooling2d,dropout, anddensein that exact order. - The final
denselayer must have an output shape of(None, 1). - The total number of trainable parameters must be small, corresponding only to the weights of the final
denselayer (e.g., 1,281).