Skip to main content

Convolutional Neural Networks

Updated 11 min readMarkdown
Part of seriesAI, One Experiment at a Time
Convolutional Neural Networks

1. Convolution - Introduction

In the previous blog, we saw how convolution works and how it helps identify spatial features in images. In fact, convolution is not limited to images. It can be applied to any two-dimensional data.

In short, we have an input (a two-dimensional array) and a filter to extract features. We call these filters kernels.

When we convolve the input with a kernel, we get feature maps.

$$\text{Input} * \text{Kernel} = \text{Feature Maps}$$

In image processing, we used pre-existing kernels to extract features such as vertical edges, horizontal edges and outlines.

But what if we don't know which features (kernels) are important for identifying a particular image?

2. Why?

Convolution is one of the building blocks of a CNN. In a complete architecture, we want to achieve a few things.

  1. Learn features automatically: Instead of choosing pre-existing kernels, we allow the machine to learn the kernel values using training data. These kernels helps to identify features like vertical edges, horizontal edges, objects etc.
  2. Reduce the number of parameters: Instead of connecting every input pixel to every neuron, convolution uses shared filters across the image. This significantly reduces the number of parameters required to extract spatial features.
  3. Build higher-level features: We combine the extracted features through multiple layers. Earlier layers may learn simple patterns, while deeper layers can learn more complex combinations.

3. Architecture

Thus, the below architecture shows a basic CNN implementation to accomplish our digit identification problem.1

There are two broad sections in our MNIST example.

  • Feature Learning: Convolution + Feature Maps + Non-linear Activation + Max Pooling.
  • Classification: Flatten + Fully connected layers (Activation and layer stacking) + Soft maxed Output (Cross-Entropy Loss as loss function).

Let's quickly cover the individual components. We have already seen a few of these concepts in previous blogs.

4. Components

Feature Maps

We already saw this in our convolution example.

When we apply a kernel over an input image, we get a feature map. In a CNN, instead of manually defining kernels, we let the network learn them during training.

We can have multiple kernels in a single convolution layer. Each kernel learns a different pattern and produces its own feature map.

One important thing here is that these kernels are shared across the image. The same learned weights are used at different spatial positions.[^1]

Non-Linearity (ReLU)

We already discussed non-linearity in our first neural network experiment.

ReLU is simply:

$$ReLU(x) = max(0,x)$$

It replaces negative values with zero and keeps positive values as they are.

But why do we need non-linearity?

If we stack multiple linear operations without any activation function, the overall result is still just another linear operation. Adding more layers alone doesn't increase the types of relationships the network can learn.

Non-linearity allows the network to learn more complex relationships between inputs and outputs.

This is what helps us move beyond simple linear classification.

Max Pooling

We have multiple feature maps, each containing spatial information about the image.

Do we need to preserve every single value? Not necessarily.

Max pooling reduces the spatial dimensions of a feature map by selecting the maximum value from a small region.

For example, a 2 × 2 max pooling operation takes four values and keeps only the maximum.

So, an 8 × 8 feature map can be reduced to 4 × 4.

This reduces the amount of data passed to subsequent layers and provides some tolerance to small changes in the location of features.

Flatten

Now, we have multiple feature maps from convolution layers.

In PyTorch, the shape of these feature maps is represented as:

$$(B,C,H,W)$$

Where:

  • B - Batch size (number of images processed together).
  • C - Channels (number of feature maps).
  • H - Height.
  • W - Width.

That's where Flatten comes in.2

$$(B,C,H,W) \rightarrow (B,C \times H \times W)$$

For our example:

$$(B,32,7,7) \rightarrow (B,1568)$$

Notice that batch size remains unchanged. We flatten the remaining dimensions for each image independently.

Linear Layer

We already saw this in our first neural network experiment.

A linear layer connects inputs and outputs using weights and biases.

$$z = Wx + b$$

In our example, we have 1568 values from the flattened feature maps. We connect these to 128 neurons.

We can also stack multiple linear layers with non-linear activation functions to learn more complex relationships.

Softmax

Our final layer produces scores for each of the ten possible digits3.

These scores are called logits. Softmax converts these scores into values between 0 and 1, with their sum equal to 1.

$$Softmax(z_i) = \frac{e^{z_i}}{\sum_j e^{z_j}}$$

This makes the output intuitive to interpret as a probability distribution over the ten classes.

For example, the output might look like this:

One implementation detail: PyTorch's CrossEntropyLoss already applies the required log-softmax operation internally. So we can directly pass the logits to the loss function during training.

Cross-Entropy Loss

This is one of the basic loss functions suited for classification problems.

It measures how far our predicted probability distribution is from the expected class.

The loss becomes higher when the model assigns a low probability to the correct class.

For continuous prediction problems, we have other loss functions. Mean Squared Error (MSE) is one common example.

5. Connecting things in code

Now, let's connect these components in our MNIST implementation.

We are using the same dataset and training approach from our previous experiment of digit identification. The main difference is the model architecture.

import pickle
from pathlib import Path

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset


path = Path("data/MNIST_dataset.pkl") # https://github.com/mnielsen/neural-networks-and-deep-learning/tree/master/data

with path.open("rb") as f:
    data = pickle.load(f, encoding="latin1")

(X_train, y_train), (X_val, y_val), (X_test, y_test) = data

def prepare_images(X):
    return torch.tensor(
        X, dtype=torch.float32
    ).reshape(-1, 1, 28, 28)

X_train_t = prepare_images(X_train)
y_train_t = torch.tensor(y_train, dtype=torch.long)

X_val_t = prepare_images(X_val)
y_val_t = torch.tensor(y_val, dtype=torch.long)

X_test_t = prepare_images(X_test)
y_test_t = torch.tensor(y_test, dtype=torch.long)


# 3. Define the CNN
class MNIST_CNN(nn.Module):
    def __init__(self):
        super().__init__()

        self.conv1 = nn.Conv2d(
            in_channels=1,
            out_channels=16,
            kernel_size=3,
            padding=1,
        )

        self.conv2 = nn.Conv2d(
            in_channels=16,
            out_channels=32,
            kernel_size=3,
            padding=1,
        )

        self.relu = nn.ReLU()
        self.pool = nn.MaxPool2d(kernel_size=2)

        self.flatten = nn.Flatten()
        self.fc1 = nn.Linear(32 * 7 * 7, 128)
        self.output = nn.Linear(128, 10)

    def forward(self, x):
        x = self.relu(self.conv1(x))  # 1 x 28 x 28 -> 16 x 28 x 28
        x = self.pool(x)              # 16 x 14 x 14

        x = self.relu(self.conv2(x))  # 32 x 14 x 14
        x = self.pool(x)              # 32 x 7 x 7

        x = self.flatten(x)           # 1568 values
        x = self.relu(self.fc1(x))    # 1568 -> 128
        x = self.output(x)            # 128 -> 10

        return x


model = MNIST_CNN()

# 4. Loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)

# 5. Prepare mini-batches
batch_size = 128

train_loader = DataLoader(
    TensorDataset(X_train_t, y_train_t),
    batch_size=batch_size,
    shuffle=True,
)

# 6. Train and validate
epochs = 30

for epoch in range(epochs):
    model.train()
    total_loss = 0.0

    for images, labels in train_loader:
        logits = model(images)
        loss = loss_fn(logits, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_loss += loss.item() * len(labels)

    avg_train_loss = total_loss / len(X_train_t)

    model.eval()
    with torch.no_grad():
        train_predictions = model(X_train_t).argmax(dim=1)
        val_logits = model(X_val_t)

        val_loss = loss_fn(val_logits, y_val_t).item()
        val_predictions = val_logits.argmax(dim=1)

        train_acc = (
            train_predictions == y_train_t
        ).float().mean().item()

        val_acc = (
            val_predictions == y_val_t
        ).float().mean().item()

    print(
        f"Epoch {epoch + 1:2d} | "
        f"Train loss: {avg_train_loss:.4f} | "
        f"Val loss: {val_loss:.4f} | "
        f"Train accuracy: {train_acc:.2%} | "
        f"Val accuracy: {val_acc:.2%}"
    )

# 7. Evaluate once on the held-out test set
model.eval()
with torch.no_grad():
    test_predictions = model(X_test_t).argmax(dim=1)
    test_acc = (
        test_predictions == y_test_t
    ).float().mean().item()

print(f"\nFinal test accuracy: {test_acc:.2%}")

A couple of things to notice:

  • We start with one input channel because MNIST images are grayscale.
  • The first convolution produces 16 feature maps.
  • The second convolution takes those 16 feature maps and produces 32 more.
  • Both convolution layers use 3 × 3 kernels.
  • Max pooling reduces the spatial dimensions by half at each stage.
  • Finally, we flatten the feature maps and pass them through linear layers.

Our input image starts with 28 × 28 pixels.

The dimensions change as follows:

Operation Output shape (excluding batch)
Input 1 × 28 × 28
Conv1 + ReLU 16 × 28 × 28
Max Pool 16 × 14 × 14
Conv2 + ReLU 32 × 14 × 14
Max Pool 32 × 7 × 7
Flatten 1568
Linear + ReLU 128
Output 10

The training process remains almost the same as our previous experiment. We still use CrossEntropyLoss, backpropagation and an optimizer to update the model parameters.

The difference is how we extract features before classification.

6. Let's compare the improvements

In our first experiment, we started with a simple linear neural network and gradually introduced hidden layers and non-linearity.

Now, we have introduced convolution and pooling.

Let's compare the model parameters and accuracy for epoch 30.

Model Parameters Val accuracy Test accuracy
Plain NN (two hidden layers) 269,322 98.08 97.94
Plain NN (three hidden layers) 300,938 98.07 97.99
CNN 206,922 98.55 98.68

That's approximately 23% fewer parameters in our CNN two layer version.

Interestingly, the convolution layers together have only 4,800 parameters.

Why so few?

Because the same kernel weights are reused across different spatial positions. We don't need a separate set of weights for every pixel position.

The fully connected layers still account for most of the parameters in our CNN.

But the important improvement is not just the parameter count.

We now have a network that learns spatial features from images. It can identify patterns such as edges and combine them into more complex features without us manually defining the kernels.

7. CNN Use Cases

We saw image classification using CNNs. But the same feature-learning idea can be used for other computer vision tasks 4.

1. Image Classification

This is what we implemented. We take an image and predict its class. In our case, the output is one of the digits from 0 to 9.

2. Object Detection

Here, we identify objects in an image along with their locations.

For example, a photograph may contain multiple cars, people and traffic signals. The model identifies each object and its bounding box.

The feature extraction part can still use convolution layers. But the classification output is extended with object locations and other required information.

3. Semantic Segmentation

Instead of predicting one class for the entire image, we predict a class for every pixel.

For example, in an autonomous driving image, we may classify individual pixels as road, vehicle, pedestrian, building or sky.

The feature-learning section still extracts spatial features. But the classification part is changed to produce pixel-level predictions instead of a single class.

In short, the first part of the architecture can remain similar, while the second part changes depending on the problem we want to solve.

Note: In CNN (CNets), there are numerous advancements went through. In fact each CNet architecture has its own names 5.

8. Conclusion

Let's wrap up.

We started with convolution as an image-processing operation, where we manually selected kernels to extract features.

Now, we have seen how CNNs use the same concept but learn the kernels themselves through training data.

We also saw how feature maps, ReLU, max pooling and linear layers work together to solve the digit classification problem.

Compared to our earlier plain neural network, we have fewer parameters and a more suitable architecture for learning spatial features.

There is still a lot more to explore in CNNs, such as deeper architectures, different pooling strategies and how these feature maps are combined.

Thanks for reading.

References

[^1] : https://dennybritz.com/posts/wildml/understanding-convolutional-neural-networks-for-nlp/

Footnotes

  1. https://in.mathworks.com/videos/introduction-to-deep-learning-what-are-convolutional-neural-networks--1489512765771.html ↩︎

  2. https://bnaskrecki.faculty.wmi.amu.edu.pl/nnets/_build/html/part7_cnn/ch23_cnn_architecture.html ↩︎

  3. https://medium.com/@sue_nlp/what-is-the-softmax-function-used-in-deep-learning-illustrated-in-an-easy-to-understand-way-8b937fe13d49 ↩︎

  4. https://www.youtube.com/watch?v=pqIcoskUuWs&list=PLtBw6njQRU-rwp5__7C0oIVt26ZgjG9NI&index=7 ↩︎

  5. https://cs231n.github.io/convolutional-networks/#case ↩︎

About the author

No comments yet. Be the first to comment.