Convolutional Neural Networks (CNNs)

1. What is Convolution operation?

This layer is the first layer that is used to extract the various features from the input images. It involves sliding a small matrix (called a kernel or filter) over the image and performing mathematical calculations (weighted sum) at each step to create a new, transformed representation called a feature map.

45×0+12×(1)+5×0+22×(1)+10×5+35×(1)+88×0+26×(1)+51×0=45

ML_AI/images/conv-1.png

Why Use Convolutions?

Before CNNs, standard neural networks flattened images into 1D arrays immediately, which destroyed the spatial relationships between pixels. Convolutions solve this problem while providing several key advantages.

Convolutions with Padding!

ML_AI/images/conv-2.png

2. Benefits of Using Convolutions in deep learning

Convolutional Neural Networks (CNNs) is being used for many computer vision task. It is default neural network architecture when it comes to image classifications, object detection, image style transfer etc.

1. Supports Transfer Learning
MAIN
Early layers of CNNs learn universal visual features (like edges and textures), which remain more or less the same irrespective of the task or image dataset used. So In Transfer learning, we can take a pretrained CNNs (e.g., VGG, ResNet, EfficientNet) and reuse its foundation for your own project. You only need to retrain the very last layers on your specific dataset. This allows you to achieve world-class accuracy with only a few hundred images instead of millions. **Note**: The number of layers that can be reused from existing CNN to a new one is directly proportional to the similarity between the dataset used to train the initial network and the dataset of the new task.

Advantages:

2. Parameter Sharing (Weight Reuse)
MAIN
Convolution layers share weights across spatial locations, reducing the number of learnable parameters, especially for high-dimensional inputs like images. In CNN, a each kernel is "swept" across the entire image. Because the same weights are used to process every part of the image, the number of learned parameters is drastically reduced, making the model faster to train and much less prone to overfitting.

Example
If your image of size is 28×28 and if you have 40 kernels in the first convolutional layer, each of weights of size 5×5, the total number of weights that you have to train is 5×5×40=1000.
Compare this to a standard dense layer, having 100 neurons, total number of parameters here is 28×28×100=78400. This is a gigantic difference.

Advantages:

3. Translation Invariance
MAIN
CNNs are translation invariant, meaning they can recognize patterns regardless of their position in the image. CNNs achieve **translation invariance** through the combination of convolution and pooling operations. Because the filters sweep across the entire image CNNs highly effective in recognizing objects at different locations, unlike traditional fully connected networks.

Example
A cat is still a cat regardless of whether it appears in the top half or the bottom half of the image. If a cat feature exists anywhere in the frame, the filter will activate.

Visual Example
In the below figure, the CNN filter is trained to detect the letter ‘C’ in the input image.
So lets input an image of letter ‘C’.
ML_AI/images/conv-6.png

Now lets shift the letter ‘C’ down in the image by 1 pixel length.

ML_AI/images/conv-7.png

4. Automatic, Hierarchical Feature Extraction
MAIN
CNNs automatically learn to engineer their own features from the raw pixel data, operating in a hierarchy of complexity, eliminating the need for manual feature engineering. - **Early Layers:** Learn basic, low-level features like straight lines, edges, and simple color gradients. - **Middle Layers:** Combine those edges to learn textures, curves, and simple shapes (like circles or corners). - **Deep Layers:** Combine shapes to recognize highly complex, high-level objects (like a dog's face, a car wheel, or a stop sign).

Advantages:

5. Preservation of Spatial Relationships (Local Connectivity)
MAIN
In images, pixels that are close together are heavily related (forming objects), while pixels far apart are usually unrelated. Traditional networks flatten an image into a single 1D line of pixels immediately, completely destroying this 2D spatial relationship. CNNs process the image in its original 2D (or 3D, with color channels) volume, using **local receptive fields** to ensure that neighboring pixels are processed together, preserving the structural context of the image.

Advantages:

6. Reduced Overfitting

The shared weights and hierarchical feature extraction reduce model complexity compared to fully connected layers, thereby lowering the risk of overfitting.

Advantages:

7. Efficient with Large Inputs

CNNs are optimized to handle large high-dimensional inputs (e.g., 1024x1024 pixel images) without overwhelming computational resources.

Advantages:

8. Wide Range of Architectures

Variants of CNN architectures exist for specific applications, such as object detection, semantic segmentation, or generative modeling.

Advantages:

9. Improved Robustness with Regularization

CNNs often integrate regularization techniques like dropout, batch normalization, and L2 regularization to stabilize training.

Advantages:

10. Versatility Across Domains

CNNs are versatile models that have revolutionized various industries beyond computer vision.

Advantages:

11. Ease of Deployment

CNN models can be deployed conveniently using frameworks like TensorFlow, PyTorch, Keras, and ONNX for inference on edge devices (e.g., smartphones or IoT systems).

Advantages:

12. Handles Rotation and Translation

CNNs are robust to certain transformations (e.g., rotation, translation). This property stems from pooling and feature normalization layers.

Advantages:

13. Supports Multi-Channel Data

CNNs can process multi-channel inputs efficiently (e.g., RGB images, video with temporal frames, etc.).

Advantages:


3. Stride

Variations of Stride

  1. Stride of 1 (Standard Convolution): Extracting highly detailed, dense features without losing spatial resolution.
  2. Stride Greater Than 1 (Strided Convolution): In this the filter jumps by 2, 3, or more pixels at a time. Reducing the spatial dimensions of the feature map (downsampling).
  3. Asymmetric Stride: Using different stride values for the horizontal and vertical axes.

Advantages of Larger Strides (Stride > 1)

Disadvantages of Larger Strides

Note

In many modern architectures (like ResNet), a convolution layer with a stride of 2 is used instead of a max-pooling layer to reduce the image size while letting the network learn the best way to summarize the data.

Usecase

Example: 2D Convolution with Stride

ML_AI/images/stride-1.png


4. Pooling

Types of Pooling

  1. Max Pooling: Extracting the most prominent or dominant features, such as sharp edges, lines, and corners. It is the most widely used pooling method in modern CNNs.

  2. Average Pooling: It calculates the average of all the values in the region covered by the filter. Retaining background information and smoothing out the image. It is often used when the exact feature strength is less important than the overall presence of the feature.
    ML_AI/images/pooling-1.png

  3. Global Pooling (Global Average or Global Max): Instead of sliding a small window, global pooling takes the entire feature map (e.g., a 7x7 matrix) and reduces it to a single value (either the maximum or the average of the whole matrix). Best for: Drastically reducing dimensions right before the final classification layer, often replacing the need for traditional fully connected "flattening" layers.

Advantages

  1. Reduces Computational Cost: Pooling significantly reduces the number of parameters and helps to make the learned features more robust to small spatial variations and reduces computational complexity.
  2. Controls Overfitting: Because pooling removes detailed, pixel-perfect information and extracts only the broader summary of features, it helps prevent the model from memorizing the training data.
  3. Translation Invariance: Pooling makes the network robust to small shifts or translations in the input image. For example, if a cat's ear shifts a few pixels to the left, max pooling will still detect the "edge" of the ear within its window, allowing the network to recognize the object regardless of its exact position.

Disadvantages of Pooling

What are advantages can also be disadvantages like

  1. Loss of Spatial Information: By downsampling, the network loses spatial relation between different features. While it knows a feature exists, it loses the exact coordinates, which can be detrimental for tasks requiring pixel-perfect accuracy (like image segmentation).

    This happens because the max pooling layer is applied to the outputs of each filter from previous convolution layer separately. Due to separately applying max pooling on each filter, much of the relative positional information between features is lost. So next layer can only give output based on the presence of features. As we go to subsequent layers, more and more of the spatial information is lost, as max pooling layer compunds the effect of translation invariance. In the end it detects a face even when the eye is present in the place of the mouth.
    ML_AI/images/conv-8.png

  2. Destroys Fine Details: Max pooling, in particular, throws away up to 75% of the data (in a standard 2x2 stride 2 setup) simply by ignoring non-maximum values. In complex images, vital subtle details might be discarded entirely.

Where is Pooling Applied?


5. Flatten

In a CNN, flattening is the process of converting a multi-dimensional feature map into a single, one-dimensional (1D) array or vector. The flattened acts as a bridge between the ➀ feature extraction part of the network (the convolutional and pooling layers) and ➁ the classification part of the network (the fully connected or dense layers).

Pros


6. Dropout

Dropout is a powerful regularization technique used in neural networks, including Convolutional Neural Networks (CNNs), to prevent the model from memorizing the training data (overfitting).
Because the network cannot rely on any single neuron being active, it forces the model to distribute its learning across the entire network. I. The Dropout layer is a mask that nullifies the contribution of some neurons toward the next layer and leaves all others.

Press enter or click to view image in full size

ML_AI/images/conv-5.png

Why is Dropout Important?

Types of Dropout

1. Standard Dropout:
2. Spatial Dropout (Channel Dropout)
3. DropBlock
4. Alpha Dropout

7. Activation Function

Refer 👉 Activation Function


8. Filters

Refer 👉 Computer Vision - Filters


Note

As we move along the network of CNN, we loose spatial information But we are able to gain global (high level) information of image, which make its very useful in classification. In classification you don't need to know where in the image, object of interest lies, but only need to know what that object is.


🤔💭 Questions and Answers

1. Parameters vs. Hyperparameters in CNNs

In any neural network, including CNNs, there is a strict dividing line between what the model learns on its own (parameters) and what can be programmed (hyperparameters).

Feature Parameters Hyperparameters
Definition Internal variables that the model learns and adjusts automatically during training. External configurations set manually by the architect before training begins.
How they change Continuously updated via backpropagation and gradient descent to minimize error. Static during a training run. They are only changed manually between runs to find a better configuration.
CNN Examples The weights inside a convolutional filter, the biases added to a feature map, the weights in fully connected layers. Learning rate, batch size, number of epochs, filter size (e.g., 3x3), stride size, pooling type (max/average).

2. Pooling vs. Strides

Both pooling layers and strided convolutions (using a stride >1) are used to downsample the image — i.e reduce the spatial dimensions (width and height) of the feature maps as data moves deeper into the network.

While the end result—a smaller feature map—is similar, the mechanics and implications are different:

3. When to Choose Which?

Choose Pooling when:

Choose Strided Convolutions when:

4. Flattening vs. Global Pooling

In older, classic CNN architectures (like VGG16 or AlexNet), flattening was the standard way to transition to the final classification layers. However, modern architectures often replace the Flatten layer with Global Average Pooling (GAP).

Feature Flatten Global Average Pooling (GAP)
Mechanics Convert all the resultant 2D or 3D arrays from pooled feature maps into a single long continuous linear vector. Averages the entire spatial dimensions of each channel into a single number.
Output Size Usually massive (e.g., 7x7x512 becomes an array of 25,088 values). Much smaller (e.g., 7x7x512 becomes an array of just 512 values).
Pros Retains all extracted feature data for the Dense layer to analyze. Drastically reduces parameters, saving computational power and preventing overfitting.
Cons Leads to millions of parameters in the Dense layers, making the model prone to overfitting and heavy to run. Destroys all spatial layout information, though usually acceptable at the very end of the network.

5. What is the typical workflow of CNN and when and how are weights in kernel updated?

Here is how the flow works in reality.

Step 1: The Forward Pass (Predicting)

During training, the network takes an image and pushes it through all the layers. At the very end, it makes a prediction (e.g., "I am 80% sure this is a dog").
The network then calculates the Loss (how wrong that prediction was compared to the actual label).
At this exact moment, the weights have not been updated yet. The network just holds onto the math of "how wrong" it was.

Step 2: The Backward Pass (Calculating the Fixes)

The network works backward from the end to the beginning (Backpropagation), calculating exactly how much each kernel and filter needs to change to make a better prediction next time. It calculates these "fixes" (gradients), but again, it does not apply them yet.

Step 3: The Weight Update (When it actually happens)

When those fixes are actually applied to the kernels is dictated by the Batch Size you set for your Optimizer.
Here are the three scenarios for when the updates happen:

Scenario A: Batch Size = 1 (Stochastic Gradient Descent)
Scenario B: Batch Size = Total N Images (Batch Gradient Descent)
Scenario C: Batch Size = 32 (Mini-Batch SGD — The Standard)