Understanding CNN Architecture

Illustration of connected neurons in Convolutional Neural Networks 
Title: Illustration of connected neurons in Convolutional Neural Networks 
Source: CNN Overview by Encord

Introduction

Convolutional Neural Networks (CNNs) have revolutionized computer vision by enabling machines to automatically learn hierarchical features from raw image data. Unlike traditional machine learning approaches that require hand-engineered features, CNNs can detect edges, textures, shapes, and even high-level semantics directly from pixels. Their ability to exploit spatial hierarchies and translation invariance makes them especially powerful for tasks like image classification, object detection, and image segmentation.

This post explores why it is so effective in computer vision tasks,  the key components of a CNN, and its architecture.

Why CNNs are Effective

Before diving into the architecture of Convolutional Neural Networks (CNNs), let’s first understand why they have become the backbone of modern computer vision. CNNs are not just another type of neural network. tThey are uniquely designed to process visual and spatial information with good efficiency and accuracy. Their effectiveness stems from three core principles:

  • Localized Feature Detection: Convolutional layers focus on local patterns, making CNNs highly effective for spatially structured data. For instance, in facial recognition, convolutional layers detect edges, corners, and textures in small regions of an image, allowing the model to recognize individual facial features such as eyes, nose, and mouth.

  • Parameter Sharing: In convolutional neural networks (CNNs), filters (also called kernels) are shared across the spatial dimensions of the image, which reduces the number of learnable parameters and improves efficiency. For example, in handwriting recognition (e.g., MNIST dataset), the same convolutional filters are applied across different parts of the image, enabling the model to recognize the digit “3” regardless of whether it appears in the top-left or bottom-right corner.

  • Translation Invariance: Pooling layers ensure the model’s robustness to slight changes in position. For example, in self-driving cars, traffic signs may appear at different locations in the camera feed. Pooling layers help ensure that a “STOP” sign is still recognized even if it is slightly shifted due to camera movement or perspective changes.

These features make CNNs not only accurate but also computationally efficient and scalable, ideal for high-dimensional tasks like image classification, object detection, and video analysis.

Now that we’ve seen why CNNs are so powerful, let’s explore how they work under the hood by breaking down their architecture and components.

Key Components of CNN Architecture

 A CNN typically consists of several key layers, each serving a distinct purpose in processing and extracting information from data.

Convolutional Layer

A convolutional layer is designed to extract features from input data by applying convolutional filters. These filters, also known as kernels, slide over the input data and compute the dot product at each step, producing a feature map that captures essential patterns in the input. This process allows the network to detect key visual elements such as edges, textures, and specific shapes, which are crucial for understanding images in tasks like classification and object detection. 

Example 1

For example, in the figure below, the convolution kernel scans every patch of the image, performing a dot product at each location to generate a feature map that highlights specific patterns such as edges or eyes. For example, applying a 3×3 kernel to a 5×5 grayscale image yields a smaller feature map where high values indicate strong matches between the kernel and image patches. The two highlighted values of 100 show regions where the kernel, acting as an eye detector, identified a strong correlation, while the surrounding zeros indicate weak or no matches. This process enables convolutional layers to extract meaningful visual features that are further processed in deeper layers. 

Intuitive Understanding of 1D, 2D, and 3D Convolutions
Title: an eye kernel capturing the feature around the eye in the image
Source: Intuitive Understanding of 1D, 2D, and 3D Convolutions in Convolutional Neural Networks by Thakur, A

Do note that the network will automatically learn what features each kernel will extract, and might not be as clearly defined as identifying eyes or nose as mentioned in this simplistic example. 

2D convolution example
Title: 2D convolution example
Source: Detection and Tracking of Pallets using a Laser Rangefinder and Machine Learning Techniques by Ihab S. Mohamed et al.

Example 2

In another example, his figure shows the 2D convolution process in a CNN. A small matrix (the kernel or filter) slides over the input image (left), performing element-wise multiplication with each 3×3 patch and summing the results to produce the output feature map (right). For instance, the red-highlighted region in the input yields the value “4” in the green-highlighted output cell. This process is repeated across the image. In CNNs, filter values are not manually set but learned during training, enabling the model to detect useful patterns like edges or textures.

Activation Function

An Activation Function introduces non-linearity into the network, allowing it to learn complex patterns beyond simple linear transformations. Common activation functions include ReLU (Rectified Linear Unit), Sigmoid, and Tanh, each with distinct properties suited for different tasks. Among them, ReLU is widely used due to its simplicity and efficiency. It converts all negative values in the feature map to zero while retaining positive values, helping the network train faster and mitigate the vanishing gradient problem.

Activation Functions: ReLU, Sigmoid, and Tanh 
Title: Visualization of Activation Functions: ReLU, Sigmoid, and Tanh 
Source:AIML.com Research

Pooling Layer

The Pooling Layer plays a crucial role in reducing the spatial dimensions of feature maps, enhancing computational efficiency while making the network more robust to spatial variations. There are two main types: Max Pooling, which selects the maximum value from each region, and Average Pooling, which computes the average value. By downsampling the feature map, pooling helps in feature generalization and prevents overfitting. The figure below illustrates an example of Max Pooling, where a 2×2 filter is applied to the feature map, selecting the maximum value in each region during the operation.

The output dimensions after pooling can be computed as:

pooling layer formula

For example, applying a 2×2 Max Pooling filter with a stride of 2 to a 4×4 feature map will produce a 2×2 output. The figure below demonstrates this by selecting the maximum value from each 2×2 region.

Illustration of Max Pooling
Title: Illustration of Max Pooling: Applying a 2×2 Filter on a Feature Map
Source: Deep Learning Course in Computer Vision by Stanford

Fully Connected Layer (FC)

The Fully Connected (FC) Layer serves as the final stage in a neural network, where extracted features are combined to make predictions. Before reaching the fully connected layer, the network takes the high-dimensional representations from previous layers and flattens them into a 1D vector, transforming spatial information into a format suitable for classification. This vector is then passed through dense layers, where each neuron is connected to every neuron in the next layer, enabling the network to learn complex patterns and output probabilities or classifications based on the extracted features.

Fully Connected Layer
Title: Visualization of the Fully Connected Layer
Source: TensorFlow for Deep Learning Book (Chapter 4)

Dropout 

Dropout is a regularization technique introduced to reduce overfitting in neural networks, especially in fully connected layers. During each training iteration, a random subset of neurons is “dropped out” (i.e., temporarily removed), meaning their contribution to both forward and backward propagation is ignored. This prevents the network from becoming too reliant on specific neurons and encourages redundancy and robustness in the learned features. At test time, all neurons are used, but their outputs are scaled to account for the dropout applied during training. This simple yet effective method has been widely adopted in deep learning models to improve generalization.

Structure of a Typical CNN (AlexNet)

 structure of AlexNet
Title: Overview of the structure of AlexNet
Source: ImageNet Classification with Deep Convolutional Neural Networks by Alex et al.

As shown in the Figure, AlexNet, a pioneering deep convolutional neural network, significantly advanced image classification by introducing deeper architectures and effective regularization techniques. It employed multiple convolutional layers with large receptive fields, where each filter (or kernel) is shared across the spatial dimensions of the input, enabling the network to detect the same feature in different locations, a key idea known as parameter sharing. This drastically reduces the number of learnable parameters compared to fully connected networks. AlexNet also used ReLU activations to speed up training and max pooling to reduce spatial dimensions while preserving important features. Additionally, AlexNet incorporated dropout regularization in fully connected layers to mitigate overfitting and GPU parallelism to efficiently handle large-scale datasets like ImageNet. These innovations set the foundation for modern deep learning architectures, greatly improving classification accuracy compared to traditional methods.

Let’s dive deeper into the AlexNet and do a step-by-step walkthrough. 

Step-by-Step Walkthrough of AlexNet

Let’s take a step by step walkthrough on the layer structure of AlexNet

  • Input:

AlexNet takes a 224×224 RGB image (3 channels) as input.

  • Layer 1: Convolution + ReLU + Max Pooling

Applies 96 filters of size 11×11 with stride 4, followed by ReLU activation and max pooling (3×3, stride 2) This aggressively reduces spatial size while capturing low-level features.

  • Layer 2: Convolution + ReLU + Max Pooling

Uses 256 filters of size 5×5, with padding 2, followed by ReLU and max pooling. Extracts more detailed spatial features while further downsampling.

  • Layers 3–5: Convolution + ReLU

Three consecutive convolutional layers (384, 384, 256 filters of size 3×3, padding 1), all followed by ReLU. These deepen the network’s capacity to learn complex patterns.

  • Pooling Layer

Another 3×3 max pooling reduces output to 6×6×256, which is flattened for the fully connected layers.

  • Fully Connected Layers

Two dense layers with 4096 neurons, each followed by dropout (50%), help prevent overfitting. The final layer is a 1000-class softmax for classification.

To summarize, AlexNet introduced several key innovations: 

  • parameter sharing via convolution (same filter scans across spatial dimensions), 
  • ReLU activation for faster training, 
  • dropout for regularization, and 

These advances enabled AlexNet to achieve a major leap in accuracy over traditional methods. In fact, AlexNet was the first deep learning based model that could beat the traditional vision models in the ImageNet challenge in 2012 that too by a huge margin thereby ushering in a new era of vision models.

Code Example: Simple CNN in PyTorch

The code snippet defines a simple Convolutional Neural Network (CNN) using PyTorch. The model consists of a convolutional layer (Conv2d) with 16 filters, followed by a ReLU activation and a max pooling layer (MaxPool2d) that reduces the spatial dimensions. The output is then flattened and passed through a fully connected layer (Linear) to classify images into 10 categories, assuming a **32×32 input size**. 

Python
import torch
import torch.nn as nn
import torch.optim as optim

# Define a simple CNN
class SimpleCNN(nn.Module):
    def __init__(self):
        super(SimpleCNN, self).__init__()
        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
        self.fc1 = nn.Linear(16 * 16 * 16, 10)  # Assuming 32x32 input and 10 classes
    def forward(self, x):
        x = self.pool(torch.relu(self.conv1(x)))
        x = x.view(-1, 16 * 16 * 16)  # Flatten
        x = self.fc1(x)
        return x

# Instantiate and train
model = SimpleCNN()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.9)

# Summary
print(model)

Other Resources

Video Explanation

  • The Stanford lecture provides an in-depth overview of common CNN architectures, highlighting their exceptional performance in ImageNet challenges.
YouTube video
In-depth overview of common CNN architectures by Stanford
  • In C4W1L08 – Simple Convolutional Network Example, Professor Andrew Ng presents a step-by-step illustration of a basic convolutional network, detailing the dimension calculations involved in each layer.
YouTube video
Simple Convolutional Network Example by Andrew Ng

Useful Animation

Related Articles:

Author

  • Brown University CS

    Machine Learning Content Writer

Help us improve this post by suggesting in comments below:

– modifications to the text, and infographics
– video resources that offer clear explanations for this question
– code snippets and case studies relevant to this concept
– online blogs, and research publications that are a “must read” on this topic

Leave the first comment

Partner Ad
Find out all the ways that you can
Contribute