🤖 AI/ML

Convolution

Convolution

An operation that applies a filter in image processing. A core component of CNNs, used for feature extraction.

📖 Detailed Explanation

Convolution is a mathematical operation that extracts features by sliding a filter (kernel) over input data. In deep learning, it is the core operation of the CNN (Convolutional Neural Network), automatically learning hierarchical features such as edges, textures, and patterns in images.

The convolution operation has long been used in the field of signal processing, but the innovation in deep learning began in 1989 with Yann LeCun's LeNet. In 2012, AlexNet showed overwhelming performance at the ImageNet competition and set off the deep learning revolution, and afterward various CNN architectures such as VGGNet, ResNet, and EfficientNet developed. Today, CNNs compete with the Vision Transformer (ViT), but there are still many areas where CNNs are preferred in terms of efficiency and interpretability.

The core principles of convolution are parameter sharing and local connectivity. Because the same filter scans the entire image, the number of parameters is greatly reduced, and a learned filter detects the same pattern regardless of its position (translation invariance). The filter size (e.g., 3x3, 5x5), stride (step interval), padding, and number of channels are the main hyperparameters. Through multi-layer convolution, features are extracted hierarchically from low-level (edges) to high-level (objects).

In practice, convolution is a foundational technology of computer vision, including image classification, Object Detection, semantic segmentation, and medical image analysis. As of 2025, modern CNNs such as ConvNeXt and EfficientNetV2 achieve performance comparable to ViT with less data and computation. 1D convolution is used for time series and speech processing, and Graph Convolution is used for molecular structure and social network analysis.

💻 Code Example

CNN image classification implementation using PyTorch:

# CNN 이미지 분류 모델 (PyTorch)
import torch
import torch.nn as nn
import torch.nn.functional as F

class SimpleCNN(nn.Module):
    """
    CIFAR-10 분류를 위한 CNN 모델
    입력: 32x32x3 이미지
    """
    def __init__(self, num_classes=10):
        super().__init__()

        # Conv Block 1: 3 -> 32 채널
        self.conv1 = nn.Conv2d(
            in_channels=3,
            out_channels=32,
            kernel_size=3,      # 3x3 필터
            padding=1,          # same padding
            stride=1
        )
        self.bn1 = nn.BatchNorm2d(32)

        # Conv Block 2: 32 -> 64 채널
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(64)

        # Conv Block 3: 64 -> 128 채널
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
        self.bn3 = nn.BatchNorm2d(128)

        # Pooling
        self.pool = nn.MaxPool2d(kernel_size=2, stride=2)

        # Fully Connected Layers
        # 32 -> 16 -> 8 -> 4 (3번의 pooling 후)
        self.fc1 = nn.Linear(128 * 4 * 4, 256)
        self.fc2 = nn.Linear(256, num_classes)

        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
        # Block 1: Conv -> BN -> ReLU -> Pool
        x = self.pool(F.relu(self.bn1(self.conv1(x))))  # 32x32 -> 16x16

        # Block 2
        x = self.pool(F.relu(self.bn2(self.conv2(x))))  # 16x16 -> 8x8

        # Block 3
        x = self.pool(F.relu(self.bn3(self.conv3(x))))  # 8x8 -> 4x4

        # Flatten
        x = x.view(x.size(0), -1)  # (batch, 128*4*4)

        # FC Layers
        x = self.dropout(F.relu(self.fc1(x)))
        x = self.fc2(x)

        return x

# 모델 생성 및 구조 확인
model = SimpleCNN(num_classes=10)
print(model)

# 입력 테스트
dummy_input = torch.randn(1, 3, 32, 32)
output = model(dummy_input)
print(f"\n입력: {dummy_input.shape} -> 출력: {output.shape}")

Visual understanding of the convolution operation:

# 컨볼루션 연산 시각화
import torch
import torch.nn.functional as F
import numpy as np

# 5x5 입력 이미지 (1채널)
input_image = torch.tensor([
    [1, 2, 3, 4, 5],
    [2, 3, 4, 5, 6],
    [3, 4, 5, 6, 7],
    [4, 5, 6, 7, 8],
    [5, 6, 7, 8, 9]
], dtype=torch.float32).unsqueeze(0).unsqueeze(0)  # (1, 1, 5, 5)

# 3x3 에지 탐지 필터 (소벨 필터)
sobel_x = torch.tensor([
    [-1, 0, 1],
    [-2, 0, 2],
    [-1, 0, 1]
], dtype=torch.float32).unsqueeze(0).unsqueeze(0)  # (1, 1, 3, 3)

# 컨볼루션 적용
output = F.conv2d(input_image, sobel_x, padding=1)

print("입력 이미지 (5x5):")
print(input_image.squeeze().numpy())

print("\n소벨 필터 (3x3):")
print(sobel_x.squeeze().numpy())

print("\n컨볼루션 결과:")
print(output.squeeze().numpy())

# 다양한 설정 비교
print("\n=== 컨볼루션 설정별 출력 크기 ===")
for padding in [0, 1]:
    for stride in [1, 2]:
        out = F.conv2d(input_image, sobel_x, padding=padding, stride=stride)
        print(f"padding={padding}, stride={stride} -> 출력 크기: {out.shape[-2:]})")

# 출력 크기 공식: (W - K + 2P) / S + 1
# W=5, K=3 -> padding=1, stride=1: (5-3+2)/1+1 = 5
# W=5, K=3 -> padding=0, stride=2: (5-3+0)/2+1 = 2

📊 CNN Architecture Comparison

Performance comparison of major CNN architectures (ImageNet basis):

Model Year Parameter Top-1 Accuracy Features
AlexNet 2012 60M 57.1% Start of the deep learning revolution
VGG-16 2014 138M 71.5% Repeated use of 3x3 filters
ResNet-50 2015 25M 76.1% Introduction of Skip Connection
EfficientNet-B7 2019 66M 84.4% Compound scaling
ConvNeXt-L 2022 198M 87.5% Modernized CNN

* Vision Transformer (ViT-L) is at the 86.4% level, proving that ConvNeXt can compete with ViT

🗣️ Say It Like This in Practice

💬 In a Meeting
"For image classification tasks, EfficientNet-B3 is enough. If you scale up to B7, accuracy rises by 1-2%, but inference time increases fourfold. For mobile deployment, MobileNetV3 is also a good choice."
💬 In an Interview
"The reason ResNet's Skip Connection is important is that it solves the gradient vanishing problem. By adding the input directly to the output, the gradient propagates to deep layers, making it possible to train networks of more than 100 layers."
💬 In a Technical Discussion
"ViT is strong on large-scale data, but on small and medium-sized data, the CNN's inductive bias (locality, translation invariance) is more efficient. ConvNeXt applies the strengths of Transformer to CNN, combining the strengths of both worlds."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌

Using deep networks indiscriminately

A network that is too deep for the task overfits and increases inference time. Choose an architecture that fits the dataset size and complexity. For CIFAR-10, ResNet-18 is enough.

❌

Input size mismatch

If the input size of a pretrained model (e.g., 224x224) differs from the actual data size, performance degrades. Appropriate resizing and preprocessing (such as normalization) are essential.

✅

The right approach

Start with an ImageNet pretrained model and apply Transfer Learning. For small datasets, we recommend only Feature Extraction, and for large datasets, full fine-tuning. Data Augmentation is also essential.

🔗 Related Terms

📚 Learn More