CNN: Convolutional Neural Network

Convolutional Neural Network (CNN, convolutional neural network) is a type of neural network that uses convolution operations to process data with spatial or local structure.

CNN is most commonly used in computer vision (Computer Vision), such as image classification, target detection, semantic segmentation and image feature extraction, and can also be applied to audio, time series and other data.

The core idea of CNN is: efficiently extracts local features from data through local connections (Local Connectivity) and parameter sharing (Parameter Sharing), and builds more complex representations layer by layer.

This article focuses on:

  • Convolution、Kernel、Feature Map。
  • Stride、Padding、Dilation、Receptive Field。
  • Pooling、Downsampling、Normalization。
  • Residual Connection、ResNet。
  • Depthwise Separable Convolution。
  • Hyundai CNN: ConvNeXt.
  • PyTorch implementation and the difference between CNN and Vision Transformer.

1. The difference between CNN and traditional fully connected networks

Assume the input is a RGB picture:

X∈R3×224×224X\in\mathbb{R}^{3\times224\times224}

Among them:

  • 3:Channels。
  • 224:Height。
  • 224:Width。

If you flatten the image into a vector:

3×224×224=1505283\times224\times224=150528

Then to connect a Linear Layer with 1024 output units, the weights alone are needed:

150528×1024≈154M150528\times1024\approx154M

That’s about 154 million weights.

In contrast, convolutional layers do not require every output unit to be connected to all input locations.

CNN mainly uses two features to reduce computational and parameter costs.

Local Connectivity: Partial connection

A convolution kernel only processes a local area in the input.

For example, 3×3 Kernel only observes a local 3×3 spatial position at a time (but usually covers all input channels).

Parameter Sharing: parameter sharing

The same convolution kernel can be reused at different locations in the image.

Therefore, the number of parameters of the convolutional layer mainly depends on:

  • Kernel Size。
  • Input Channels。
  • Output Channels。

Rather than being directly proportional to the width and height of the image.

This structure provides an important inductive bias of CNN (Inductive Bias): the same local features can appear at different spatial locations.

2. Convolution: convolution operation

Convolution is the most basic computational operation of CNN.

For a 2D input, a Kernel slides across the image, each time performing element-wise multiplication and summation over the corresponding region, producing an output value.

For example:

Input(4×4)          Kernel(2×2)

1  2  3  4             1  0
5  6  7  8             0 -1
9 10 11 12
13 14 15 16

Results for the upper left corner position:

1(1)+2(0)+5(0)+6(−1)=−51(1)+2(0)+5(0)+6(-1)=-5

Kernel continues calculation after moving to the next position, and finally forms a new feature map.

Convolution and cross-correlation in CNN

Strictly speaking, Conv2d of PyTorch performs Cross-Correlation (cross-correlation), that is, Kernel does not perform flipping in the mathematical convolution definition.

But the deep learning community usually still refers to it as Convolution because the Kernel parameters are learned through training.

multi-channel convolution

The actual RGB image contains three input channels.

Assumptions:

Input Shape: [32, 3, 224, 224]

If 64 3×3 convolution kernels are used, each output convolution kernel will process all 3 input channels, resulting in:

Output Shape: [32, 64, 224, 224]

It is assumed here that Stride is 1 and Padding is 1.

PyTorch implementation

import torch
import torch.nn as nn

conv = nn.Conv2d(
    in_channels=3,
    out_channels=64,
    kernel_size=3,
    stride=1,
    padding=1,
)

x = torch.randn(32, 3, 224, 224)

y = conv(x)

print(y.shape)
# torch.Size([32, 64, 224, 224])

Number of parameters

The number of parameters of ordinary two-dimensional convolution:

Parameters=Cout×Cin×Kh×Kw+CoutParameters=C_{out}\times C_{in}\times K_h\times K_w+C_{out}

The last entry is Bias, assuming bias=True is enabled.

For example:

64×3×3×3+64=179264\times3\times3\times3+64=1792

There are only 1792 parameters.

Compared with the previous fully connected layer, the number of parameters is greatly reduced.

3. Feature Map: Feature map

Feature Map is Tensor output by the convolutional layer.

Different Kernel can learn different feature detection methods, such as:

  • Edge and direction changes.
  • Color and texture.
  • local shape.
  • More complex visual patterns.

It should be noted that these are intuitive explanations of the learning results, and not each convolution kernel strictly corresponds to a human-understandable feature.

Multi-layer feature extraction

A typical CNN will gradually build the representation through multiple convolutional layers:

Input Image
    ↓
Early Convolution Layers
    ↓
Edges / Textures
    ↓
Intermediate Layers
    ↓
Shapes / Parts
    ↓
Deep Layers
    ↓
High-level Features
    ↓
Prediction

This process is called Hierarchical Feature Learning (hierarchical feature learning).

Deep networks can combine simple features extracted by previous layers to represent more complex visual structures.

4. Stride, Padding and Dilation

These three parameters determine how Kernel handles the input space.

Stride: step size

Stride refers to the distance moved by Kernel each time.

nn.Conv2d(
    3,
    64,
    kernel_size=3,
    stride=2,
    padding=1,
)

stride=2 usually reduces the spatial size of the output Feature Map.

For example:

224 × 224 → 112 × 112

Therefore, Strided Convolution can be used for Downsampling (downsampling).

Padding: padding

Padding adds an extra numeric value to the input boundary, usually 0.

Its function:

  • Control the size of the output space.
  • Allows Kernel processing near the edges of the image.
  • Avoid shrinking the feature map with each convolution.

For example:

nn.Conv2d(
    3,
    64,
    kernel_size=3,
    padding=1,
)

When Stride is 1 and Dilation is 1, the input and output width and height can usually be kept consistent.

Dilation: dilated convolution

Dilation introduces spacing between Kernel elements to expand the spatial range they cover.

nn.Conv2d(
    64,
    64,
    kernel_size=3,
    dilation=2,
    padding=2,
)

When Dilation is 2, the effective spatial coverage of 3×3 Kernel is equivalent to 5×5, but there are still only 9 spatial weight positions.

It is often used for tasks that require a larger receptive field but want to retain a certain spatial resolution, such as semantic segmentation.

Output size formula

The output size for a single spatial dimension is:

O=⌊I+2P−D(K−1)−1S+1⌋O= \left\lfloor \frac{I+2P-D(K-1)-1}{S}+1 \right\rfloor

Among them:

  • II: Enter the size.
  • KK:Kernel Size。
  • PP:Padding。
  • SS:Stride。
  • DD:Dilation。

For example:

I=224, K=3, P=1, S=2, D=1I=224,\ K=3,\ P=1,\ S=2,\ D=1

Get:

O=112O=112

Height and Width are calculated according to the corresponding parameters.

5. Receptive Field: Feeling field

Receptive Field (receptive field) refers to the input area that can be affected by a certain output position of the network.

A single 3×3 convolutional layer can typically only directly observe a local 3×3 range.

But by stacking multiple layers of convolutions, the output of deep layers can be affected by a wider range of inputs.

For example, in a simple convolution stack with Stride of 1:

1 Layer of 3×3 Conv  → 3×3 Receptive Field
2 Layers             → 5×5
3 Layers             → 7×7

It is assumed here that there are no additional Downsampling, Dilation, etc. operations.

Why is receptive field important?

Image classification requires not only identifying local textures but also understanding larger spatial structures.

For example to identify an animal:

  • Local area: hair texture.
  • Larger areas: ears, eyes, body parts.
  • Global area: overall shape and context.

As the network deepens, the receptive field usually gradually expands.

Theoretical vs Effective Receptive Field

Need to distinguish:

  • Theoretical Receptive Field: All input areas that may theoretically affect the output.
  • Effective Receptive Field: The area that actually has a significant impact on the output.

The two are not necessarily the same.

The modern CNN expands its receptive field through larger Kernel, Dilation, Downsampling and multi-layer construction.

6. Pooling and Downsampling

Pooling is used to aggregate information in local spatial regions and is often used to reduce spatial resolution.

Max Pooling

Take the maximum value in the local area.

1  3
2  4

Max = 4

PyTorch:

pool = nn.MaxPool2d(
    kernel_size=2,
    stride=2,
)

For example:

[32, 64, 112, 112]
          ↓
[32, 64, 56, 56]

Average Pooling

Take the average of the local area.

nn.AvgPool2d(
    kernel_size=2,
    stride=2,
)

Global Average Pooling

Aggregate the entire spatial region of each Channel into a single value.

nn.AdaptiveAvgPool2d((1, 1))

For example:

[32, 512, 7, 7]
        ↓
[32, 512, 1, 1]

Then:

x = torch.flatten(x, 1)

Get:

[32, 512]

This is often used for CNN Classification Head.

Pooling and Strided Convolution

Modern CNN does not necessarily rely on Pooling to complete all Downsampling, Convolution can also use stride=2.

methodFeatures
Max PoolingPreserve local maximum response
Average PoolingAggregate local average information
Strided ConvolutionDownsampling using learnable parameters
Global Average PoolingSummarize spatial features into channel vectors

Downsampling can reduce computational costs and expand the effective sensing range of subsequent layers, but it will also lose some spatial details.

7. Typical architecture of CNN

A basis CNN can be expressed as:

Input Image
    ↓
Conv2d
    ↓
Normalization
    ↓
Activation
    ↓
Conv2d / Downsampling
    ↓
Conv Blocks
    ↓
Global Average Pooling
    ↓
Linear Classifier
    ↓
Logits

Generally it can be divided into two main parts.

Backbone: Feature extraction network

Used to extract representations from images.

For example ResNet, ConvNeXt.

Head: task output layer

Depending on the task, Head can be:

  • Classification Head: Predict image category.
  • Detection Head: Predict target category and location.
  • Segmentation Head: Predict pixel-level categories.

The separation of Backbone and Head is an important design method for modern computer vision models.

The same Backbone can be used for different downstream tasks.

8. Residual Connection: Residual connection

As the neural network becomes deeper, the difficulty of optimization may increase.

ResNet (Residual Network) introduces Residual Connection to make the network easier to train.

core idea

General online learning:

H(x)=F(x)H(x)=F(x)

Residual Block changes to:

H(x)=F(x)+xH(x)=F(x)+x

Among them:

  • F(x)F(x): Transformation consisting of convolutional layers, etc.
  • xx:Shortcut / Skip Connection。

Intuitively, the network learns supplements or modifications to the input rather than completely regenerating a representation.

Why is it helpful?

Residual Connection provides additional propagation paths for signals and gradients, which can alleviate some optimization difficulties in deep networks.

It is also an important common idea in architectures such as modern Transformer.

PyTorch implementation

import torch.nn as nn

class ResidualBlock(nn.Module):
    def __init__(self, channels):
        super().__init__()

        self.block = nn.Sequential(
            nn.Conv2d(
                channels,
                channels,
                kernel_size=3,
                padding=1,
                bias=False,
            ),
            nn.BatchNorm2d(channels),
            nn.ReLU(),

            nn.Conv2d(
                channels,
                channels,
                kernel_size=3,
                padding=1,
                bias=False,
            ),
            nn.BatchNorm2d(channels),
        )

        self.activation = nn.ReLU()

    def forward(self, x):
        return self.activation(
            self.block(x) + x
        )

This example assumes that the input and output have the same Shape.

If the Channel quantity or space size is different, the dimensions need to be matched through Projection Shortcut and other methods.

ResNet

ResNet is very important in the development of CNN because it demonstrates the value of Residual Connections for deep network training.

Common models include:

  • ResNet-18。
  • ResNet-34。
  • ResNet-50。
  • ResNet-101。

These models are still often used as Baseline or Pretrained Backbone for vision tasks.

There is no need to memorize the complete layer structure of each ResNet version one by one, just focus on understanding the design ideas of Residual Block and Bottleneck Block.

9. Depthwise Separable Convolution: Depthwise separable convolution

Ordinary convolution needs to be performed simultaneously:

  1. Spatial feature extraction.
  2. A mix of input and output channels.

Depthwise Separable Convolution separates these two steps.

Depthwise Convolution

Perform spatial convolution on each input Channel separately.

depthwise = nn.Conv2d(
    in_channels=64,
    out_channels=64,
    kernel_size=3,
    padding=1,
    groups=64,
)

Here groups=64, that is, each input channel corresponds to an independent convolution operation.

Pointwise Convolution

Mix Channel information by 1×1 Convolution.

pointwise = nn.Conv2d(
    in_channels=64,
    out_channels=128,
    kernel_size=1,
)

combination

block = nn.Sequential(
    nn.Conv2d(
        64, 64,
        kernel_size=3,
        padding=1,
        groups=64,
        bias=False,
    ),
    nn.Conv2d(
        64, 128,
        kernel_size=1,
        bias=False,
    ),
)

Parameter number comparison

Normal 3×3 Convolution:

Pstandard=K2CinCoutP_{\text{standard}}=K^2C_{in}C_{out}

Depthwise Separable Convolution:

Pseparable=K2Cin+CinCoutP_{\text{separable}}=K^2C_{in}+C_{in}C_{out}

Bias is not counted here.

For example:

K=3,Cin=64,Cout=128K=3,\quad C_{in}=64,\quad C_{out}=128

Ordinary convolution:

Pstandard=73728P_{\text{standard}}=73728

Depthwise separable convolution:

Pseparable=8768P_{\text{separable}}=8768

The number of parameters is significantly reduced.

However, the actual inference speed is also affected by factors such as hardware, memory access, Kernel implementation, etc. Fewer parameters do not guarantee faster operation.

Typical applications

Depthwise Separable Convolution is widely used in lightweight CNN, such as the MobileNet family, and is also adopted by the modern CNN architecture.

10. Hyundai CNN: ConvNeXt

After the rise of Vision Transformer, researchers re-examined the architectural design of CNN.

ConvNeXt is an important modern CNN family that draws on some design experience from modern visual architectures, but the core calculations are still dominated by convolutions.

The main design ideas of ConvNeXt

Compared with traditional ResNet, ConvNeXt introduces or emphasizes:

  • More modern Stage Design.
  • Larger Depthwise Convolution Kernel.
  • Layer Normalization。
  • GELU。
  • Inverted Bottleneck。
  • A more reasonable Downsampling.
  • Residual Connections。

A typical ConvNeXt Block can be summarized as:

Input
   ↓
Depthwise Convolution(7×7)
   ↓
LayerNorm
   ↓
Channel Expansion
   ↓
GELU
   ↓
Channel Projection
   ↓
Residual Addition
   ↓
Output

This is a simplified structural representation.

Inverted Bottleneck

Traditional Bottleneck usually first reduces the number of Channel, then performs spatial operations, and finally restores the dimensions.

Inverted Bottleneck usually expands Channel first, then transforms it, and finally projects it back to the target dimension.

This design is commonly used in modern high-efficiency network modules.

ConvNeXt V2

ConvNeXt V2 further combines the self-supervised pre-training method and introduces mechanisms such as Global Response Normalization (GRN).

It is not necessary to go into the implementation details of each new version here. The point is to understand:

Modern CNN is no longer limited to the early Conv → Pool → Conv → Pool mode, but pays more attention to residual structure, normalization, channel transformation, computational efficiency and pre-training methods.

11. CNN and Vision Transformer

CNN and Vision Transformer (ViT) are two important types of visual Backbone.

CNN

The local spatial structure is mainly processed through Convolution.

Typical features:

  • Local connection.
  • Parameter sharing.
  • The spatial induction bias is strong.
  • Extract local to global features hierarchically.

Vision Transformer

Usually the picture is converted to Patch Tokens, and the relationship between features is established through modules such as Self-Attention.

For example:

Image
   ↓
Patch Embedding
   ↓
Transformer Blocks
   ↓
Visual Representation

main difference

FeaturesCNNVision Transformer
core operationsConvolutionSelf-Attention
typical inductive biasLocality, translational variabilityRely more on architecture and training design
feature interactionGradually expand the range through convolutional layersStandard global Attention can interact directly across Token
Common BackboneResNet、ConvNeXtViT、Swin Transformer
Typical applicationsImage classification, detection, segmentationImage classification, visual basic model, multi-modal model

It cannot simply be understood that ViT has completely eliminated CNN.

The actual choice also depends on:

  • Data size.
  • Pre-trained model.
  • inference delays.
  • Equipment performance.
  • Model size.
  • Downstream tasks.

CNN and Transformer can also be combined to form Hybrid Architectures.

12. PyTorch: Construct a CNN

Let's build a simple image classification network.

The input is a RGB image, and the output is Logits in 10 categories.

import torch
import torch.nn as nn

class SimpleCNN(nn.Module):
    def __init__(self, num_classes=10):
        super().__init__()

        self.features = nn.Sequential(
            nn.Conv2d(3, 32, 3, padding=1),
            nn.BatchNorm2d(32),
            nn.ReLU(),

            nn.MaxPool2d(2),

            nn.Conv2d(32, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),

            nn.MaxPool2d(2),

            nn.Conv2d(64, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(),
        )

        self.pool = nn.AdaptiveAvgPool2d((1, 1))

        self.classifier = nn.Linear(
            128,
            num_classes,
        )

    def forward(self, x):
        x = self.features(x)
        x = self.pool(x)

        x = torch.flatten(x, 1)

        return self.classifier(x)

Test:

model = SimpleCNN(num_classes=10)

x = torch.randn(8, 3, 64, 64)

logits = model(x)

print(logits.shape)
# torch.Size([8, 10])

Shape changes

Input             [8, 3, 64, 64]
Conv 3→32         [8, 32, 64, 64]
MaxPool           [8, 32, 32, 32]
Conv 32→64        [8, 64, 32, 32]
MaxPool           [8, 64, 16, 16]
Conv 64→128       [8, 128, 16, 16]
AdaptiveAvgPool   [8, 128, 1, 1]
Flatten           [8, 128]
Linear            [8, 10]

Understanding each layer of Tensor Shape is one of the most important engineering skills when working with CNN.

13. Training of CNN

CNN uses the same basic training process as other neural networks:

Image Dataset
      ↓
DataLoader
      ↓
CNN Forward
      ↓
Classification Loss
      ↓
Backward
      ↓
Optimizer Step

For example:

model = SimpleCNN(num_classes=10).to(device)

criterion = nn.CrossEntropyLoss()

optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=1e-4,
)

for images, labels in train_loader:
    images = images.to(device)
    labels = labels.to(device)

    optimizer.zero_grad(set_to_none=True)

    logits = model(images)
    loss = criterion(logits, labels)

    loss.backward()
    optimizer.step()

The device and train_loader used here assume that they have been prepared.

The model output of CNN is Logits, so there is no need to execute Softmax in advance when using CrossEntropyLoss.

Data Augmentation

Data Augmentation is often used in image training to improve the model's adaptability to input changes.

Common methods:

  • Random Crop。
  • Horizontal Flip。
  • Random Rotation。
  • Color Jitter。
  • Random Resized Crop。

For example:

from torchvision import transforms

train_transform = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
])

Data augmentation needs to be consistent with the real semantics of the task. For example, some medical images, text images, or direction-sensitive recognition tasks are not suitable for random flipping or rotation.

Transfer Learning

Modern computer vision development typically does not require training a large CNN from scratch.

The more common way is to use pre-training Backbone and then replace or fine-tune Classification Head.

For example TorchVision:

from torchvision.models import (
    resnet18,
    ResNet18_Weights,
)

model = resnet18(
    weights=ResNet18_Weights.DEFAULT,
)

model.fc = nn.Linear(
    model.fc.in_features,
    10,
)

This takes advantage of the visual representations that the pre-trained model has learned.

In actual use, it is also necessary to adopt an image preprocessing configuration that matches the pre-trained weights:

weights = ResNet18_Weights.DEFAULT
preprocess = weights.transforms()

For tasks with smaller data sizes, Transfer Learning is often more practical than training completely from scratch.

14. Main visual tasks of CNN

CNN is useful for more than just Image Classification.

Image Classification

Input a picture and output category:

Image → Backbone → Classification Head → Class

Object Detection

Identify multiple objects in an image and predict their location and category:

Image → Backbone → Detection Head
                         ↓
                Bounding Boxes + Classes

Common model families include YOLO, etc.

Semantic Segmentation

Predict the class for each pixel in the image:

Image → Encoder → Decoder → Pixel-level Labels

For example, U-Net is a very representative Encoder–Decoder structure.

Feature Extraction

Convert the image into a feature vector:

Image → CNN Backbone → Embedding

Available for:

  • Image retrieval.
  • Similar image matching.
  • clustering.
  • Downstream classifier training.

Among them, Detection, Segmentation, etc. can be used as independent Computer Vision task topics, and there is no need to go into the in-depth implementation of each model in the CNN basics chapter.

15. Frequently Asked Questions and Notes

CNN Do I have to enter a fixed size image?

uncertain.

The purely convolutional part can usually handle inputs of different spatial sizes, but there may be size requirements for the Head, position-dependent modules or implementation of the specific model.

Using Adaptive Pooling allows some classification models to support inputs of different sizes.

Does CNN necessarily require Pooling?

unnecessary.

Strided Convolution can also be done with Downsampling.

Hyundai CNN will choose different methods depending on the architectural design.

Kernel Size Is bigger better?

uncertain.

A larger Kernel can expand the local coverage, but may increase the computational cost and affect the optimization and representation capabilities of the model.

Need to combine Depthwise Convolution, network depth and actual hardware efficiency analysis.

CNN Is standardization required?

Reasonable input preprocessing is usually required.

Common standardized forms of image input:

x′=x−μσx'=\frac{x-\mu}{\sigma}

But Input Normalization here is not the same concept as BatchNorm and LayerNorm inside the network.

The pre-trained model should give priority to the pre-processing methods required by the corresponding weights.

Does CNN have fewer parameters and is necessarily faster?

uncertain.

Actual performance depends on:

  • FLOPs。
  • Memory Bandwidth。
  • Tensor Shape。
  • Operator implementation.
  • GPU / CPU architecture.
  • Batch Size。

The amount of model parameters, the amount of computation, and the actual inference latency are three different metrics.


Summary

Knowledge pointsimportance
Convolution / Kernelcore
Feature Map / Channelscore
Local Connectivity / Parameter Sharingcore
Stride / Paddingcore
Dilationimportant
Receptive Fieldcore
Pooling / Downsamplingcore
Global Average Poolingimportant
Residual Connection / ResNetcore
Depthwise Separable Convolutioncore
BatchNorm / LayerNormimportant
ConvNeXt / Modern CNNimportant
CNN vs Vision Transformerimportant
Image Data Augmentationimportant
Transfer Learningcore

CNN The five most important concepts:

  1. Convolution: Efficiently extract features from images using local connections and parameter sharing.
  2. Feature Hierarchy: Multi-layer convolutions progressively combine low-level visual features into complex representations.
  3. Receptive Field & Downsampling: Control the spatial range and feature map resolution that the model can observe.
  4. Residual Connection: Improved optimization and gradient propagation of deep neural networks via Shortcut.
  5. Modern CNN Design: The modern CNN combines Depthwise Convolution, Normalization, Residual Blocks and the efficient Channel Mixing, no longer limited to the traditional Conv + Pool structure.

Reference documentation

Back to top