AI Logic

Architectures

Convolutional Neural Network (CNN)

Updated:

Structure of a CNN. Left: the overall flow of image classification (convolutional layer, activation function, and pooling layer stacked N times, then fully connected layers and softmax output the class). Right: an example computation of a convolution with a 3×3 kernel and 2×2 max pooling

Background and overview

A CNN (Convolutional Neural Network) is a neural network built around "convolutional layers" that slide small filters (kernels) over an image and multiply them with it. It is widely used as the basic form of models that handle images, such as image classification, object detection, and segmentation.

When an MLP (a fully connected network) handles images, it flattens the pixels into a single row, so it cannot use the property of images that "neighboring pixels are closely related," and the number of weights becomes enormous for large inputs. A CNN solves this with the following three ideas (as summarized in the 1998 paper by LeCun et al.).

  • Local receptive fields: each unit looks only at a small region of the input (for example, 5×5).
  • Weight sharing: the same weights (kernel) are reused at every location in the image.
  • Subsampling (pooling): reduces the height and width of feature maps, making the network robust to small shifts in position.

The CNN was not proposed in a single paper; it is a general name for networks built on these ideas. Fukushima's Neocognitron, inspired by studies of cells in the visual cortex, first realized the combination of convolution and subsampling, and in 1989 LeCun et al. trained such a network with backpropagation and used it to recognize handwritten digits in zip codes. LeNet-5 of 1998 is the representative example. After AlexNet won the ImageNet image recognition competition in 2012, deeper and deeper CNNs followed one after another: VGG, GoogLeNet, and ResNet.

Overall architecture

The basic form of a CNN is to stack many sets of "convolution → activation function → pooling" and produce the answer with fully connected layers at the end. The left side of the figure at the top of the article shows the overall flow, and the right side shows an example computation of convolution and pooling.

For image classification, data flows in the following order.

  1. The image is input as a tensor of height × width × channels (3 channels, red, green, and blue, for a color image).
  2. A convolutional layer applies several kernels over the whole image, producing one "feature map" per kernel.
    • The kernels of the first layer come to respond to simple patterns such as vertical and horizontal lines and color edges.
  3. An activation function such as ReLU is applied to each value of the feature maps.
  4. A pooling layer reduces the height and width of the feature maps (for example, by taking the maximum of each 2×2 region).
  5. Steps 2–4 are repeated many times. In later stages, the height and width become smaller and the channels (kinds of features) become more numerous, representing more complex features (corners, textures, object parts, etc.) that combine the features of earlier stages.
  6. The last feature maps are flattened into a single row, or turned into a vector by taking the mean of each channel with global average pooling, and fully connected layers and a softmax function output the class probabilities.

LeNet-5 processes a 32×32 handwritten digit image in the order convolution (6 maps of 28×28) → subsampling (6 maps of 14×14) → convolution (16 maps of 10×10) → subsampling (16 maps of 5×5) → convolution (120) → fully connected (84) → output (10 classes).

Textbooks count "layers" differently. Some call the three steps "convolution, activation, pooling" together one convolutional layer, while others call each a separate layer (Section 9.3 of Deep Learning by Goodfellow et al.). When comparing the number of layers of models, pay attention to what is being counted.

Computation in a convolutional layer

A convolutional layer slides a kernel little by little over the input, multiplying the overlapping values and summing them.

When a kernel KK of size k×kk \times k is applied to a single-channel input II, the value of the output (feature map) SS at position (i,j)(i, j) is as follows.

S(i,j)=∑m=0k−1∑n=0k−1I(i+m, j+n) K(m,n)+bS(i, j) = \sum_{m=0}^{k-1} \sum_{n=0}^{k-1} I(i+m,\, j+n)\, K(m, n) + b

bb is the bias. In the example at the top right of the figure at the top of the article, a kernel that detects vertical edges (1 in the left column and −1 in the right column) is applied. When the kernel overlaps an edge that is bright on the left and dark on the right, the output becomes large (9), and where the brightness is uniform, it is 0. The kernel values are not set by hand but determined by training.

Real inputs have multiple channels, so a kernel also has as many layers as the number of input channels CinC_{\text{in}}, and the results of all channels are summed into one feature map. Since there are as many such kernels as the number of output channels CoutC_{\text{out}}, the number of weights in one convolutional layer is as follows.

number of weights=k×k×Cin×Cout  (+  Cout biases)\text{number of weights} = k \times k \times C_{\text{in}} \times C_{\text{out}} \;(+\; C_{\text{out}} \text{ biases})

The output height and width are determined by the input size ii, kernel size kk, padding pp, and stride ss, with the following formula.

o=⌊i+2p−ks⌋+1o = \left\lfloor \frac{i + 2p - k}{s} \right\rfloor + 1
  • Padding pp: fills the border of the input with 0s or other values. Without padding, every k×kk \times k convolution shrinks the height and width by k−1k-1. With k=3k = 3, p=1p = 1 gives an output of the same size as the input.
  • Stride ss: the step by which the kernel is shifted. With s=2s = 2, the output height and width are roughly halved. Some models reduce the height and width with stride-2 convolutions instead of pooling (such as ResNet).

For example, applying a 5×5 kernel to a 32×32 input with p=0p = 0 and s=1s = 1 gives o=(32−5)/1+1=28o = (32 - 5)/1 + 1 = 28, which matches the 28×28 of the first layer of LeNet-5.

Convolution in mathematics flips the kernel before multiplying, but many libraries, including PyTorch, compute the unflipped "cross-correlation" and call it convolution (the formula above does not flip either). Since the kernel is learned, what can be learned is the same either way.

Computation in a pooling layer

A pooling layer summarizes small regions of a feature map into single values, reducing the height and width. It has no weights and is computed separately for each channel.

TypeHow values are summarizedMain use
Max poolingTakes the maximum in the regionHalves the height and width between convolution stages (2×2 with stride 2 is common)
Average poolingTakes the mean in the regionLeNet-5's subsampling layers (the mean is multiplied by a weight, a bias is added, and the result goes through a sigmoid)
Global average poolingTakes the mean of the whole feature mapTurns the feature maps into a vector at the last stage

Pooling plays the following roles.

  • Robustness to small shifts: even if the input shifts slightly, the maximum within a region often stays the same, so the output hardly changes. This helps in classification, where "whether something is there" matters more than "where". For example, to judge whether there is a face, there is no need to know the positions of the eyes to the pixel; it is enough to know that there are eyes on the left and right.
  • Less computation and a wider view: halving the height and width reduces the computation in the next layer to about 1/4. Also, a single value in a later layer comes to look at a wider region of the original image.

Other kinds of pooling include stochastic pooling, spatial pyramid pooling, which divides the input into bins of various sizes and summarizes them, and RoI pooling, used for each candidate region in object detection.

Why CNNs are good at images

CNNs are well suited to images because they build the properties of images, "nearby pixels are more closely related" and "the same pattern can appear anywhere in the image," into the architecture itself.

1. Local receptive fields keep only the necessary connections

In a fully connected layer, each output value is connected to every input value. In a CNN, each value looks only at the region covered by the kernel (its receptive field). In images, nearby pixels are strongly related, so this is enough to extract local features such as lines and corners. As layers are stacked, the receptive field grows, and values in deep layers indirectly look at wide regions of the image.

2. Weight sharing greatly reduces the number of parameters

Because the same kernel is used at every location in the image, the number of weights does not depend on the image size. For example, when producing 32 feature maps of 28×28 from a 28×28 grayscale image,

  • a fully connected layer needs 784×(28×28×32)≈19.67784 \times (28 \times 28 \times 32) \approx 19.67 million weights.
  • a 3×3 convolution needs only 3×3×1×32=2883 \times 3 \times 1 \times 32 = 288 weights (plus 32 biases).

LeNet-5 has about 340,000 connections, but thanks to weight sharing it has only about 60,000 trainable parameters. With fewer parameters, the gap between training error and test error (overfitting) tends to be smaller.

3. Equivariance to translation

Because the weights are shared, if a pattern in the input shifts one pixel to the right, the response in the feature map also just shifts one pixel to the right, and the values themselves do not change. This property is called translation equivariance. The same kernel responds wherever a cat appears, so there is no need to learn "a cat in the upper left" and "a cat in the lower right" separately. Stacking pooling on top yields representations whose outputs hardly change (are nearly invariant) under small shifts.

As an everyday analogy, it is like scanning a photo from edge to edge with a magnifying glass and taking notes such as "there is a vertical line" and "there is a circle." The same magnifying glass (kernel) is used everywhere, many sheets of notes (feature maps) are piled up, and finally the decision "this is a cat" is made.

Experimental results

As a classic example of the effect of CNNs, the 1998 paper by LeCun et al. compares various classifiers on the same data, the handwritten digit dataset MNIST (60,000 training and 10,000 test images).

ClassifierTest error rate (%)
Fully connected network (1 hidden layer, 300 units)4.7
Fully connected network (1 hidden layer, 1000 units)4.5
Fully connected network (2 hidden layers, 300 and 100 units)3.05
LeNet-5 (CNN)0.95
LeNet-5 (training data augmented with distorted images)0.8

The fully connected network's error rate stays at 4.5% even with 1000 units, whereas LeNet-5, with about 60,000 parameters, reached 0.95%. This clearly shows the effect of building the structure of images into the network.

On datasets of large images, it has been shown that making CNNs deeper improves accuracy. For example, in the ResNet paper, the top-5 error rate on the ImageNet validation data (10-crop testing) was 9.33% for VGG-16, 7.46% for the 34-layer ResNet (option B), and 5.71% for the 152-layer ResNet. The techniques for going deeper are explained in the ResNet article.

Caveats when using it

When using CNNs, keep the following points in mind.

  • They are not inherently robust to scaling or rotation: convolution is equivariant only to translation. For objects whose size or orientation changes, other measures are needed, such as adding scaled or rotated images to the training data (data augmentation, e.g. RandAugment).
  • Pooling can get in the way in tasks where position matters: pooling discards fine positional information, so in tasks that require precise positions (such as segmentation or locating corners), even the training error can go up. Architectures like U-Net, which pass the feature maps from before downsampling to later layers, are used.
  • Relations between distant locations can only be captured by stacking layers: a single convolution sees only the kernel's region. To use relations across the whole image from early stages, consider widening the receptive field with dilated convolution or using attention-based models such as ViT.
  • Input size: if the last stage "flattens into a row and feeds fully connected layers," only images of the same size as in training can be input. With global average pooling, the vector length stays constant even when the input size changes.

The output size of a convolutional layer changes with padding and stride. When building a model by hand, it is common to get an error because the input length of the fully connected layer does not match. Compute the size of each layer with o=⌊(i+2p−k)/s⌋+1o = \lfloor (i + 2p - k)/s \rfloor + 1, or pass a dummy input through the model to check the shapes.

Types of convolution, representative models, and comparison with other networks

Many kinds of CNN components have been proposed for different purposes. The main types of convolution are as follows.

TypeWhat changesMain purpose
Standard convolution—Mixes space and channels together
Depthwise separable convolutionComputes the spatial and channel directions separatelyReduces computation and parameters (MobileNet, etc.)
Grouped convolutionSplits channels into groups and computes each separatelyReduces computation (ResNeXt, etc.)
Dilated convolutionSpaces out the kernel to see a wider regionWidens the receptive field without reducing height and width
Transposed convolutionIncreases the output height and widthRestores height and width in segmentation and image generation
Deformable convolutionLearns offsets for where the kernel looksAdapts to objects whose shape varies

Representative CNN models have developed as follows.

ModelYearMain idea
LeNet-51998The basic form of alternating convolution and subsampling
AlexNet2012Training a deep CNN with large-scale image data and GPUs
VGG2014A simple design stacking only 3×3 convolutions
GoogLeNet2014Inception modules placing convolutions of different sizes side by side
ResNet2015Training depths beyond 100 layers with shortcut connections
DenseNet2016Concatenating the outputs of all previous layers
MobileNet2017Lightweight design with depthwise separable convolutions
EfficientNet2019Scaling depth, width, and resolution together
ConvNeXt2022A CNN that adopts Transformer design choices

Finally, CNNs are compared with other networks from the same viewpoints.

ViewpointMLPCNNViT (Transformer)
How the input is handledFlattened into a rowKeeps the 2D arrangementSplit into patches and arranged in sequence
Range seen by one layerThe whole inputThe kernel's region (local)All patches (attention)
Number of weights vs. input sizeGrows with the input sizeIndependent of the input sizeIndependent of the input size
Assumptions about imagesNoneLocality matters; the same pattern appears anywhereFew
Suited toSmall tabular dataImages in general; easy to train even with limited dataTraining on large amounts of data

As a rule of thumb, the standard approach for images is to try a CNN first (fine-tuning a pre-trained model such as ResNet-50). With limited computational resources, MobileNet or EfficientNet are candidates, and with very large amounts of data, so is ViT. To see the grounds for a CNN's decision, Grad-CAM can visualize where the model looked to make its decision.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from tqdm import tqdm

'''
Image classification on MNIST (a small CNN with two stages of convolution → ReLU → max pooling)
'''

# Hyperparameters
batch_size = 64       # Batch size
epochs = 5            # Number of epochs
learning_rate = 1e-3  # Learning rate

# 'cuda' if CUDA is available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

# Datasets and loaders
transform = transforms.Compose([
  transforms.ToTensor(),
  transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)


class SimpleCNN(nn.Module):
  def __init__(self, num_classes=10):
    super().__init__()
    self.features = nn.Sequential(
      # nn.Conv2d(input channels, output channels (number of kernels), kernel size, stride, padding)
      # With padding=1, a 3×3 convolution keeps the height and width: o = (28 + 2*1 - 3) / 1 + 1 = 28
      nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1),   # [B, 1, 28, 28] -> [B, 32, 28, 28]
      nn.ReLU(),
      nn.MaxPool2d(kernel_size=2, stride=2),                   # -> [B, 32, 14, 14]
      nn.Conv2d(32, 64, kernel_size=3, padding=1),             # -> [B, 64, 14, 14]
      nn.ReLU(),
      nn.MaxPool2d(2),                                         # -> [B, 64, 7, 7]
    )
    self.classifier = nn.Sequential(
      nn.Flatten(),                                            # -> [B, 64*7*7]
      nn.Linear(64 * 7 * 7, 128),
      nn.ReLU(),
      nn.Dropout(0.5),                                         # Active only in model.train()
      nn.Linear(128, num_classes),                             # Softmax is computed inside the loss function
    )

  def forward(self, x):
    return self.classifier(self.features(x))


model = SimpleCNN().to(device)
# Check the number of weights (first convolution: 3*3*1*32 + 32 = 320)
print(sum(p.numel() for p in model.features[0].parameters()))

criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)

# Training loop
for epoch in tqdm(range(epochs)):
  model.train()     # Enable dropout
  for images, labels in train_loader:
    images, labels = images.to(device), labels.to(device)
    optimizer.zero_grad()
    loss = criterion(model(images), labels)
    loss.backward()
    optimizer.step()

# Evaluation
model.eval()        # Disable dropout
correct = 0
total = 0
with torch.no_grad():
  for images, labels in test_loader:
    images, labels = images.to(device), labels.to(device)
    predicted = model(images).argmax(1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()

accuracy = 100 * correct / total
print(f"Test Accuracy: {accuracy:.2f}%")

FAQ

Q. Can CNNs be used for things other than images?
A.

Yes. One-dimensional convolutions are used for sequential data such as audio, time series, and text (the paper by LeCun et al. also mentions networks that share weights only along the time axis being used for tasks such as phoneme recognition). Three-dimensional convolutions are used for video and 3D medical images. The ideas behind CNNs help with any data in which nearby elements are strongly related and the same patterns appear in many places.

Q. How should the kernel size and number of channels be chosen?
A.

Recent models commonly use 3×3 kernels. Stacking two 3×3 convolutions covers the same region as one 5×5 convolution with fewer weights. For the number of channels, a common design doubles it each time the height and width are halved (32 → 64 → 128 …). A practical approach is to start by copying the settings of an existing model (such as ResNet) and adjust while watching accuracy and computation.

Q. Are CNNs still used now that Transformers (ViT) have appeared?
A.

Yes. Because CNNs build the assumptions "locality matters" and "the same pattern appears anywhere" into their structure, they are easier to train with limited data and are computationally lighter. They are still widely used in lightweight models for smartphones and as backbones for object detection and segmentation, and CNNs that adopt Transformer design choices, such as ConvNeXt, have also been proposed.

References

  1. LeCun, Y., Bottou, L., Bengio, Y., & Haffner, P. (1998). Gradient-Based Learning Applied to Document Recognition. Proceedings of the IEEE, 86(11), 2278–2324.
  2. LeCun, Y., Boser, B., Denker, J. S., Henderson, D., Howard, R. E., Hubbard, W., & Jackel, L. D. (1989). Backpropagation Applied to Handwritten Zip Code Recognition. Neural Computation, 1(4), 541–551.
  3. Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, Chapter 9: Convolutional Networks. MIT Press.
  4. Dumoulin, V., & Visin, F. (2016). A guide to convolution arithmetic for deep learning. arXiv:1603.07285.
  5. Fukushima, K. (1980). Neocognitron: A self-organizing neural network model for a mechanism of pattern recognition unaffected by shift in position. Biological Cybernetics, 36, 193–202.
  6. He, K., Zhang, X., Ren, S., & Sun, J. (2016). Deep Residual Learning for Image Recognition. CVPR 2016. arXiv:1512.03385.
  7. PyTorch. torch.nn.Conv2d.