Convolutional Neural Networks (CNNs) for Vision
9 min read
Hey there, future computer vision wizard! π§ββοΈ Welcome to the fascinating world of Convolutional Neural Networks (CNNs) in PyTorch. Ever wondered how your phone's camera can detect faces, or how self-driving cars can see the road? A lot of that magic comes down to CNNs.
Before we dive in, let's understand the problem: How can a computer understand an image? For us, it's easy to see a picture of a cat and say, "Hey, that's a cat!" But for a computer, an image is just a bunch of numbers (pixel values). It has no inherent understanding of what those numbers represent. How do we teach it to recognize patterns, like the pointy ears and whiskers of a cat, no matter where they are in the image?
This is where CNNs come to the rescue! They are a special type of neural network designed to process and understand visual data.
π§ Understanding Convolutional Layers (nn.Conv2d) and Pooling
Let's start with the fundamental building blocks of any CNN.
The Convolutional Layer: Your Feature Detective π΅οΈββοΈ
Imagine you're a detective looking for clues in a large photo. You might use a magnifying glass to scan the image, looking for specific patterns. A convolutional layer does something similar. It uses "filters" (also called kernels) to slide over the input image and detect features like edges, corners, and textures.
In PyTorch, we use torch.nn.Conv2d to create a convolutional layer.
What it does: It takes an input image (or a feature map from a previous layer) and applies a set of learnable filters to it. Each filter is a small matrix of weights. The layer slides this filter over the input, performs an element-wise multiplication, and sums up the results to produce a single value in the output feature map. This process is called a convolution.
Under the Hood: The key idea is that a feature (like a vertical edge) can appear anywhere in the image. By sliding the same filter across the entire image, we can detect that feature wherever it is. This is called parameter sharing, and it makes CNNs much more efficient than traditional neural networks for image data.
Let's see it in code:
import torch
import torch.nn as nn
# Let's imagine a mini-image of 5x5 pixels with 3 color channels (RGB)
input_image = torch.randn(1, 3, 5, 5) # (batch_size, in_channels, height, width)
# Now, let's create a convolutional layer
# in_channels=3 because our input has 3 channels (RGB)
# out_channels=16 means we want to learn 16 different features
# kernel_size=3 is the size of our filter (3x3)
conv_layer = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3)
# Let's see what happens when we pass our image through the layer
output_feature_map = conv_layer(input_image)
print(output_feature_map.shape)
# Expected output: torch.Size([1, 16, 3, 3])Wait, why is the output 3x3 and not 5x5? π€ Good question! By default, the convolution operation is only "valid" where the filter fully overlaps with the input. To maintain the same spatial dimensions, you can use padding=1.
Key nn.Conv2d parameters you'll frequently use:
in_channels(int): Number of channels in the input image (e.g., 3 for RGB).out_channels(int): Number of filters to learn. This determines the number of channels in the output feature map.kernel_size(int or tuple): The dimensions of your filter.3is a common choice, which means a 3x3 filter.stride(int or tuple, optional): How many pixels the filter moves at a time. The default is 1.padding(int or tuple, optional): Adds a border of zeros around the input, which can help preserve the spatial dimensions.
Fun Fact: The concept of convolutions in neural networks was inspired by the biological processes in the animal visual cortex. Hubel and Wiesel discovered that some neurons in the brain are responsible for detecting specific features in our visual field.
Pooling Layers: The Shrinking Ray! π«
After a convolutional layer has detected a bunch of features, we often have a lot of data. A pooling layer's job is to reduce the spatial dimensions (height and width) of the feature maps, which has two main benefits:
- It makes the network more computationally efficient.
- It helps the network become more robust to small translations in the input image.
The most common type of pooling is Max Pooling.
What it does: It takes a small window of the feature map and keeps only the maximum value from that window.
Let's see it in code:
import torch
import torch.nn as nn
# Let's take the output from our previous convolutional layer
feature_map = torch.randn(1, 16, 10, 10) # (batch_size, channels, height, width)
# Create a max pooling layer
# kernel_size=2 means we'll take the max over 2x2 windows
# stride=2 means the windows will not overlap
max_pool_layer = nn.MaxPool2d(kernel_size=2, stride=2)
# Apply pooling
pooled_output = max_pool_layer(feature_map)
print(pooled_output.shape)
# Expected output: torch.Size([1, 16, 5, 5])As you can see, the height and width have been halved!
ποΈ Building a Basic CNN Architecture for Image Classification
Now that we know about the core components, let's put them together to build a simple CNN for classifying images. A typical CNN architecture for this task consists of:
- A sequence of convolutional and pooling layers to extract features.
- A "flattening" step to convert the 2D feature maps into a 1D vector.
- One or more fully connected (
nn.Linear) layers to perform the final classification.
Here's a simple CNN for classifying images from the CIFAR-10 dataset (which has 10 classes of 32x32 images):
import torch.nn as nn
import torch.nn.functional as F
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
# First convolutional and pooling layer
self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
# Second convolutional and pooling layer
self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
# Fully connected layers
# After two pooling layers, our 32x32 image is now 8x8
# So, the input to the first fully connected layer is 32 * 8 * 8
self.fc1 = nn.Linear(32 * 8 * 8, 128)
self.fc2 = nn.Linear(128, 10) # 10 output classes
def forward(self, x):
# Pass through the first conv-pool block
x = self.pool1(F.relu(self.conv1(x)))
# Pass through the second conv-pool block
x = self.pool2(F.relu(self.conv2(x)))
# Flatten the output for the fully connected layers
x = x.view(-1, 32 * 8 * 8)
# Pass through the fully connected layers
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
# Let's create an instance of our network
net = SimpleCNN()
print(net)A quick note on F.relu: This is our activation function. It introduces non-linearity into our model, allowing it to learn more complex patterns. It simply replaces all negative values with zero.
π Using Pre-trained Models (torchvision.models)
Building and training a deep CNN from scratch can take a lot of time and computational resources. What if we could stand on the shoulders of giants? That's the idea behind pre-trained models!
The problem: Training a state-of-the-art CNN on a massive dataset like ImageNet (which has over 14 million images and 1000 classes) is a huge undertaking.
The solution: Researchers at places like Google, Facebook, and various universities have already done the hard work for us! They've trained powerful CNN architectures on ImageNet and have made these models available. We can use these pre-trained models directly for our tasks.
The torchvision.models module provides a collection of popular pre-trained models.
How to use a pre-trained model:
import torchvision.models as models
# Load a pre-trained ResNet-18 model
# pretrained=True downloads the weights trained on ImageNet
resnet18 = models.resnet18(pretrained=True)
# Let's see the model architecture
# print(resnet18)
# By default, the model is in training mode.
# For inference, it's important to put it in evaluation mode.
resnet18.eval()Now you have a very powerful model ready to make predictions on your images!
Interesting Event: The ImageNet Large Scale Visual Recognition Challenge (ILSVRC) was an annual competition that played a huge role in the advancement of deep learning for computer vision. In 2012, a CNN-based model called AlexNet significantly outperformed all previous non-deep learning approaches, heralding the deep learning revolution.
π οΈ Transfer Learning: Fine-tuning and Freezing Network Layers
This is where things get really cool. We can take a pre-trained model and adapt it to our own specific task, even if our dataset is relatively small. This technique is called transfer learning.
The idea: A model trained on a large dataset like ImageNet has already learned to recognize a rich hierarchy of features, from simple edges and colors to more complex patterns like a dog's fur or a car's wheel. We can leverage this learned knowledge.
There are two main approaches to transfer learning:
1. Freezing Network Layers
If your new dataset is small and similar to the original dataset (e.g., classifying different types of flowers, when the model was trained on general objects), you can freeze the weights of the early convolutional layers. This means their weights won't be updated during training. You then replace the final classification layer with a new one that matches the number of classes in your dataset and train only this new layer.
Here's how to freeze layers:
import torchvision.models as models
import torch.nn as nn
# Load a pre-trained model
model = models.resnet18(pretrained=True)
# Freeze all the parameters in the model
for param in model.parameters():
param.requires_grad = False
# Replace the final fully connected layer (the classifier)
# ResNet-18's final layer is called 'fc'
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 10) # Assuming we have 10 new classes
# Now, only the parameters of model.fc will be updated during training2. Fine-tuning
If your new dataset is larger or a bit different from the original dataset, you might want to "fine-tune" the pre-trained model. This means you not only train the new classifier but also unfreeze some of the later convolutional layers and train them with a very small learning rate.
The intuition: The earlier layers learn more general features (edges, colors), while the later layers learn more task-specific features. We want to keep the general feature detectors and slightly adjust the more specialized ones.
How to fine-tune:
import torchvision.models as models
import torch.nn as nn
import torch.optim as optim
model_ft = models.resnet18(pretrained=True)
# Replace the classifier
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 10)
# We want to train all the parameters, but with different learning rates
# Let's create an optimizer that does this
optimizer_ft = optim.SGD([
{'params': model_ft.conv1.parameters()},
{'params': model_ft.bn1.parameters()},
# ... and so on for the early layers, with a smaller learning rate
{'params': model_ft.fc.parameters(), 'lr': 1e-2} # Higher learning rate for the new layer
], lr=1e-3, momentum=0.9)In practice, you'll often see people fine-tuning the entire network with a smaller learning rate for the pre-trained parts.
π References and Further Reading
- PyTorch Documentation on
nn.Conv2d: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html - PyTorch Documentation on
nn.MaxPool2d: https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html - Torchvision Models Documentation: https://pytorch.org/vision/stable/models.html
- PyTorch Transfer Learning Tutorial: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
- CS231n: Convolutional Neural Networks for Visual Recognition: https://cs231n.github.io/ (An excellent in-depth resource from Stanford)
Challenge
You are tasked with preparing a pre-trained ResNet-18 model for a transfer learning task. Your goal is to adapt the model, originally trained on ImageNet (1000 classes), for a new dataset with a different number of classes.
Complete the adapt_resnet_for_new_task function to perform the following steps:
- Load the pre-trained
resnet18model fromtorchvision.models. Ensure you load the pre-trained weights. - Iterate through all the parameters of the loaded model and "freeze" them by setting their
requires_gradattribute toFalse. This prevents them from being updated during training. - The final classification layer in ResNet-18 is an
nn.Linearlayer namedfc. You need to replace this layer with a new, unfrozennn.Linearlayer that is suitable for the new number of classes, which is passed as thenum_classesargument. The new layer's parameters should be trainable by default. - Return the modified model.
Expected result
Your function should return a torchvision.models.resnet.ResNet object. When this model's parameters are inspected, only the parameters of the final layer (fc.weight and fc.bias) should have requires_grad=True. All other parameters in the model must have requires_grad=False. The new fc layer should be an nn.Linear module with its in_features matching the original fc layer's input features (512 for ResNet-18) and its out_features matching the num_classes argument provided to the function.