Track II · DL Fundamentals · 04/07

합성곱 신경망Convolutional neural networks

합성곱을 "가중치를 공유하는 국소 연결"로 이해하고, 출력 크기 공식·수용 영역·채널·pooling을 계산할 수 있게 된다. 합성곱을 im2col로 행렬곱 하나로 바꾸는 구현까지 NumPy로 직접 확인한다.Understand convolution as "local connectivity with shared weights", and be able to compute output sizes, receptive fields, channels and pooling. You will also check in NumPy an implementation that turns convolution into a single matrix product with im2col.

30 분min CNN · convolution · receptive field · im2col · pooling · equivariance 먼저 볼 것:Before this: 역전파와 autogradBackpropagation and autograd

Flattened, a 224×224 RGB image is a 150,528-dimensional vector. Attach a fully connected layer of 4096 hidden units and that one layer needs about 600 million weights. Worse, this layer treats “a cat in the top left” and “a cat in the bottom right” as completely different inputs that must be learned separately. Images have two kinds of structure: locality (meaningful patterns are made of nearby pixels) and translation symmetry (the same pattern can appear anywhere). A convolutional neural network (CNN) is an MLP with these two assumptions carved directly into its architecture.

Convolution = local connectivity + weight sharing

In a fully connected layer, output unit (i,j)(i, j) is connected to every input pixel, with its own weight per connection. We change two things.

  1. Local connectivity: output (i,j)(i,j) connects only to a K×KK\times K neighbourhood of the input.
  2. Weight sharing: every position (i,j)(i,j) uses the same K×KK \times K weights.

The result is a 2-D convolution.

yi,j=b+∑u=0K−1∑v=0K−1wu,v  xi+u,  j+vy_{i,j} = b + \sum_{u=0}^{K-1}\sum_{v=0}^{K-1} w_{u,v}\; x_{i+u,\; j+v}

Strictly, since the kernel is not flipped, this is cross-correlation, but because the kernel is learned it makes no difference whether it is flipped, so deep learning simply calls it convolution. The number of parameters is K2+1K^2 + 1, independent of the number of positions. Each output pixel is an inner product measuring “how much of the kernel-shaped pattern is at this position”, and the whole output is called a feature map.

224×224 RGB 이미지를 펼치면 150,528차원 벡터다. 여기에 은닉 유닛 4096개짜리 완전연결층을 붙이면 그 층 하나에 약 6억 개의 가중치가 필요하다. 게다가 이 층은 “왼쪽 위의 고양이”와 “오른쪽 아래의 고양이”를 완전히 다른 입력으로 보고 따로 배워야 한다. 이미지에는 두 가지 구조가 있다. 국소성(의미 있는 패턴은 가까운 픽셀들로 이루어진다)과 이동 대칭(같은 패턴이 어디에나 나타날 수 있다). 합성곱 신경망(convolutional neural network, CNN)은 이 두 가정을 아키텍처에 그대로 새긴 MLP다.

합성곱 = 국소 연결 + 가중치 공유

완전연결층에서 출력 유닛 (i,j)(i, j)는 모든 입력 픽셀과 연결되고, 연결마다 고유한 가중치를 가진다. 여기서 두 가지를 바꾼다.

  1. 국소 연결: 출력 (i,j)(i,j)는 입력의 K×KK\times K 이웃에만 연결된다.
  2. 가중치 공유: 그 K×KK \times K 가중치를 모든 위치 (i,j)(i,j)가 같이 쓴다.

결과가 2-D 합성곱이다.

yi,j=b+∑u=0K−1∑v=0K−1wu,v  xi+u,  j+vy_{i,j} = b + \sum_{u=0}^{K-1}\sum_{v=0}^{K-1} w_{u,v}\; x_{i+u,\; j+v}

엄밀히는 커널을 뒤집지 않으므로 상호상관(cross-correlation)이지만, 커널이 학습되는 값이라 뒤집든 말든 차이가 없어서 딥러닝에서는 그냥 합성곱이라 부른다. 매개변수는 위치 수와 무관하게 K2+1K^2 + 1개다. 출력의 각 픽셀은 “이 위치에 커널 모양의 패턴이 얼마나 있는가”를 재는 내적이고, 출력 전체를 특징맵(feature map) 이라 한다.

입력input (96×96)
커널kernel 3×3
출력 특징맵output feature map
출력 위에 마우스를 올리면 그 픽셀을 만든 3×3 입력 영역과 계산이 나온다.Hover over the output to see the 3×3 input patch and the computation that produced that pixel.
Press a preset or edit the numbers directly. Each output pixel is the dot product of the kernel with a 3×3 neighbourhood of the input, and the same 9 weights are reused at every position (weight sharing). Vertical edge responds to left–right brightness differences, horizontal edge to top–bottom ones. Signed outputs are drawn blue (negative) to red (positive). Turn on ReLU and only edges of one polarity survive. The filters a CNN's first layer learns mostly look like these. 프리셋을 누르거나 숫자를 직접 고쳐 보세요. 출력의 각 픽셀은 입력의 3×3 이웃과 커널의 내적이고, 같은 9개 가중치가 모든 위치에서 재사용된다(weight sharing). 세로 경계는 왼쪽–오른쪽 밝기 차이에, 가로 경계는 위–아래 차이에 반응한다. 부호 있는 출력은 파랑(음)–빨강(양)으로 그린다. ReLU를 켜면 한쪽 방향의 경계만 남는다. CNN의 첫 층이 학습하는 필터들이 대체로 이런 모양이다.

Look at the edge-detection kernel (Sobel). The vertical-edge kernel has ++ weights in its right column and −- in its left, so it is strongly positive where the right is brighter than the left, strongly negative in the opposite case, and 0 where brightness is uniform. It is a discrete approximation of the derivative ∂/∂x\partial/\partial x, with a 2 in the middle row for a little vertical smoothing. Classical image processing had humans design such kernels. A CNN learns the kernel’s numbers by backpropagation. That learned first-layer filters look like oriented edge and colour-contrast detectors has been observed again and again since AlexNet.

Channels

Real inputs have channels (3 for RGB), and a layer has many filters. With input Cin×H×WC_{\text{in}} \times H \times W and CoutC_{\text{out}} output channels, the kernel is a Cout×Cin×K×KC_{\text{out}} \times C_{\text{in}} \times K \times K tensor.

yo,i,j=bo+∑c=1Cin∑u,vwo,c,u,v  xc, i+u, j+vy_{o,i,j} = b_o + \sum_{c=1}^{C_{\text{in}}}\sum_{u,v} w_{o,c,u,v}\; x_{c,\,i+u,\,j+v}

One filter sums across all input channels. So a second-layer filter becomes a pattern detector asking “did the first layer’s edge detectors fire in this arrangement?”. The parameter count is Cout(CinK2+1)C_{\text{out}}(C_{\text{in}}K^2 + 1), and a 1×11\times 1 convolution (K=1K = 1) is a fully connected layer that mixes channels at each position. This “same MLP at every position” is exactly the structure of the Transformer’s FFN.

Output size: stride and padding

Move the kernel SS cells at a time (stride) and pad the input border with PP cells of zeros (padding); the output size along one axis is

Nout=⌊N+2P−KS⌋+1N_{\text{out}} = \left\lfloor \frac{N + 2P - K}{S} \right\rfloor + 1

The derivation is simple. Within the padded length N+2PN + 2P, the window starts at 0,S,2S,…0, S, 2S, \dots, and the last start may not exceed N+2P−KN + 2P - K. If it does not divide evenly, the leftover cells are dropped.

엣지 검출 커널(Sobel)을 보자. 세로 경계 커널은 오른쪽 열에 ++, 왼쪽 열에 −- 가중치를 가지므로, 왼쪽보다 오른쪽이 밝은 곳에서 크게 양수, 반대면 크게 음수, 밝기가 고른 곳에서 0이다. 미분 연산 ∂/∂x\partial/\partial x의 이산 근사이고, 가운데 행에 2를 줘서 세로 방향으로 약간 평활화했다. 고전 영상처리는 이런 커널을 사람이 설계했다. CNN은 커널의 숫자를 역전파로 학습 한다. 학습된 첫 층 필터가 방향별 경계·색 대비 검출기처럼 생긴다는 것은 AlexNet 이후 반복해서 관찰된 사실이다.

채널

실제 입력은 채널이 있고(RGB는 3), 한 층은 여러 개의 필터를 가진다. 입력이 Cin×H×WC_{\text{in}} \times H \times W, 출력 채널이 CoutC_{\text{out}}이면 커널은 Cout×Cin×K×KC_{\text{out}} \times C_{\text{in}} \times K \times K 텐서다.

yo,i,j=bo+∑c=1Cin∑u,vwo,c,u,v  xc, i+u, j+vy_{o,i,j} = b_o + \sum_{c=1}^{C_{\text{in}}}\sum_{u,v} w_{o,c,u,v}\; x_{c,\,i+u,\,j+v}

필터 하나는 입력의 모든 채널을 가로질러 합한다. 그러니 2층의 필터는 “1층의 경계 검출기들이 이런 배치로 켜졌는가”를 보는 패턴 검출기가 된다. 매개변수 수는 Cout(CinK2+1)C_{\text{out}}(C_{\text{in}}K^2 + 1)이고, 1×11\times 1 합성곱(K=1K = 1)은 위치마다 채널을 섞는 완전연결층이다. 이 “위치마다 같은 MLP”는 Transformer의 FFN과 정확히 같은 구조다.

출력 크기: stride와 padding

커널을 한 번에 SS칸씩 옮기고(stride), 입력 가장자리에 0을 PP칸 덧대면(padding), 한 축의 출력 크기는

Nout=⌊N+2P−KS⌋+1N_{\text{out}} = \left\lfloor \frac{N + 2P - K}{S} \right\rfloor + 1

이다. 유도는 간단하다. 덧댄 입력 길이 N+2PN + 2P 안에서 창의 시작 위치는 0,S,2S,…0, S, 2S, \dots이고, 마지막 시작 위치가 N+2P−KN + 2P - K를 넘으면 안 된다. 나누어떨어지지 않으면 남는 칸은 버려진다.

매개변수(1채널)parameters (1 channel)
On the left, the grey-bordered cells are padding (0), the orange box is the current kernel window, and the right side is the output. Set N = 7, P = 0, S = 2, K = 4: the windows start at 0 and 2 and cover cells 0–5, so the last row and column are never covered by any window (hatched): the remainder (7 − 4) mod 2 = 1 thrown away by the floor ⌊·⌋. With the default N = 6 the same S and K fit exactly and nothing is hatched. With P = (K − 1)/2 (K odd, S = 1) the output has the same size as the input ("same" padding). 왼쪽 회색 테두리 칸이 padding(0), 주황 상자가 현재 커널 창, 오른쪽이 출력이다. N = 7, P = 0, S = 2, K = 4로 두면 창이 0과 2에서 시작해 0–5번 칸만 덮으므로 마지막 행·열이 어떤 창에도 걸리지 않는다(빗금). 바닥 함수 ⌊·⌋가 버린 나머지 (7 − 4) mod 2 = 1이다. 기본값 N = 6에서는 같은 S, K가 딱 맞아떨어져 빗금이 생기지 않는다. P = (K − 1)/2 (K 홀수, S = 1)이면 출력 크기가 입력과 같다("same" padding).

The common cases are worth memorising.

  • S=1S = 1, P=(K−1)/2P = (K-1)/2: size preserved (“same”). 3×3 + padding 1 is the default.
  • S=2S = 2: size halved. Used at stages that reduce resolution while increasing channels.
  • P=0P = 0: shrinks by K−1K - 1 per layer (“valid”).

Receptive field

The region of the input that one output pixel ultimately sees is its receptive field. Stacking LL stride-1 K×KK\times K convolutions gives a receptive field of 1+L(K−1)1 + L(K-1). Two 3×3 layers give 5×5, three give 7×7. This is the design logic of VGG: two 3×3 layers see the same range as one 5×5 layer, with fewer parameters, 2⋅9C2=18C22\cdot 9C^2 = 18C^2 vs 25C225C^2, and one more nonlinearity in between. Once stride or pooling is involved, one cell of a later layer corresponds to several input cells, so the receptive field grows multiplicatively fast.

Equivariance and pooling

Convolution is translation equivariant: shifting the input and then convolving equals convolving and then shifting (ignoring boundary effects). This follows directly from weight sharing — since every position uses the same kernel, wherever the cat is, the same response appears at that position.

Classification needs invariance (the same answer wherever it is) rather than equivariance. Pooling bridges the two. 2×2 max pooling keeps only the maximum of each non-overlapping 2×2 cell, halving the resolution and making the output unchanged when a feature moves slightly within the cell. Local invariance accumulates layer after layer, and the final global average pooling (the mean over everything, per channel) throws positional information away entirely. Note, however, that downsampling by stride and pooling breaks exact translation invariance (a 1-pixel shift can change the output). Check how much in the code below.

Implementing it: loops and im2col

Implementing convolution literally does a small inner product at each output position. A fast implementation turns it into a single matrix product: build a matrix that unrolls every window into a column (im2col, CinK2×H′W′C_{\text{in}}K^2 \times H'W') and multiply it by the matrix of filters laid out as rows (Cout×CinK2C_{\text{out}} \times C_{\text{in}}K^2). It uses K2K^2 times more memory, in exchange for access to highly optimised GEMM (cuDNN also picks the fastest of several other algorithms, such as FFT and Winograd).

NumPy conv2d: loops vs im2col, checking the output-size formula
import numpy as np, time
rng = np.random.default_rng(0)

def out_size(n, k, s=1, p=0):
    return (n + 2 * p - k) // s + 1

def conv2d_loops(x, w, b, stride=1, pad=0):
    """x: (C_in, H, W), w: (C_out, C_in, K, K), b: (C_out,) → (C_out, H', W')"""
    C_out, C_in, K, _ = w.shape
    x = np.pad(x, ((0, 0), (pad, pad), (pad, pad)))
    H2 = (x.shape[1] - K) // stride + 1
    W2 = (x.shape[2] - K) // stride + 1
    y = np.zeros((C_out, H2, W2))
    for o in range(C_out):
        for i in range(H2):
            for j in range(W2):
                patch = x[:, i*stride:i*stride+K, j*stride:j*stride+K]   # (C_in, K, K)
                y[o, i, j] = np.sum(patch * w[o]) + b[o]                # one inner product
    return y

def im2col(x, K, stride=1, pad=0):
    """Unroll every window into a (C_in*K*K, H'*W') matrix. One column = one window."""
    C, H, W = x.shape
    x = np.pad(x, ((0, 0), (pad, pad), (pad, pad)))
    H2, W2 = out_size(H, K, stride, pad), out_size(W, K, stride, pad)
    cols = np.empty((C, K, K, H2, W2))
    for di in range(K):              # only K*K iterations (independent of the number of positions)
        for dj in range(K):
            cols[:, di, dj] = x[:, di:di + stride*H2:stride, dj:dj + stride*W2:stride]
    return cols.reshape(C * K * K, H2 * W2), (H2, W2)

def conv2d_im2col(x, w, b, stride=1, pad=0):
    C_out, C_in, K, _ = w.shape
    cols, (H2, W2) = im2col(x, K, stride, pad)
    y = w.reshape(C_out, -1) @ cols + b[:, None]   # convolution = one matrix product
    return y.reshape(C_out, H2, W2)

x = rng.normal(size=(3, 32, 32))          # RGB 32×32
w = rng.normal(size=(8, 3, 3, 3))         # 3→8 channels, 3×3
b = rng.normal(size=8)
for stride, pad in [(1, 1), (2, 0), (2, 1)]:
    t0 = time.perf_counter(); y1 = conv2d_loops(x, w, b, stride, pad); t1 = time.perf_counter()
    y2 = conv2d_im2col(x, w, b, stride, pad); t2 = time.perf_counter()
    print(f"S={stride} P={pad}: output {y1.shape}, formula {out_size(32, 3, stride, pad)}, "
          f"max diff {np.abs(y1 - y2).max():.1e}, loops {1e3*(t1-t0):6.1f} ms, im2col {1e3*(t2-t1):5.2f} ms")

print("\nparameters: conv 3→8, 3×3 =", w.size + b.size,
      "  vs fully connected with the same input/output size =", (3*32*32) * (8*32*32) + 8*32*32)
 

The Python loop on the im2col side runs only K2=9K^2 = 9 times; the rest is slicing and a matrix product. Backprop has the same structure. For the output gradient GG (Cout×H′W′C_{\text{out}} \times H'W'), ∂L/∂W=G cols⊤\partial L/\partial W = G\,\text{cols}^\top and ∂L/∂ cols=W⊤G\partial L/\partial\,\text{cols} = W^\top G, and folding the latter back into image shape adds the contributions of overlapping windows (col2im) — because one input pixel used by several windows is a fan-out.

NumPy Checking equivariance, pooling and receptive fields
# translation equivariance: shift the input and the output shifts the same way (ignoring boundaries)
img = np.zeros((1, 24, 24)); img[0, 5:9, 4:10] = 1.0          # a small rectangle
shifted = np.roll(img, shift=(6, 7), axis=(1, 2))              # 6 down, 7 right
edge = np.array([[[[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]]], dtype=float)   # vertical-edge filter
f = lambda z: conv2d_im2col(z, edge, np.zeros(1), 1, 1)
lhs = f(shifted)                                   # shift, then convolve
rhs = np.roll(f(img), shift=(6, 7), axis=(1, 2))   # convolve, then shift
print("conv(shift(x)) == shift(conv(x)) ?", np.allclose(lhs, rhs))

# max pooling is partly invariant to small shifts
def maxpool(z, k=2):
    C, H, W = z.shape
    return z[:, :H//k*k, :W//k*k].reshape(C, H//k, k, W//k, k).max(axis=(2, 4))
fm, fm1 = np.abs(f(img)), np.abs(f(np.roll(img, 1, axis=2)))   # 1-pixel shift
act = lambda u, v: (u > 0) | (v > 0)          # compare only cells active in either one
a, c = maxpool(fm), maxpool(fm1)
print(f"cells with the same value after a 1-pixel shift: before pooling {np.mean(np.isclose(fm, fm1)[act(fm, fm1)]):.0%}"
      f", after 2×2 max pooling {np.mean(np.isclose(a, c)[act(a, c)]):.0%}")

# receptive field: the input range one output pixel sees after stacking L 3×3 convs
for L in [1, 2, 3, 5]:
    probe = np.zeros((1, 21, 21)); probe[0, 10, 10] = 1.0
    z = probe
    box = np.ones((1, 1, 3, 3))
    for _ in range(L):
        z = conv2d_im2col(z, box, np.zeros(1), 1, 1)
    print(f"3×3 conv, {L} layers → receptive field {int(np.sqrt((z[0] > 0).sum()))}×{int(np.sqrt((z[0] > 0).sum()))}"
          f"  (formula 1 + L(K−1) = {1 + 2*L})")
 

You can see that pooling raises invariance “somewhat”, not “perfectly”. The translation robustness of real CNNs owes much to this local invariance accumulating over many layers, and to what is learned from data augmentation (random crops and shifts).

확인 문제Check yourself

What is the output size of a convolution with a 224×224 input, a 7×7 kernel, stride 2 and padding 3? (ResNet's first layer)

⌊(224+6−7)/2⌋+1=⌊223/2⌋+1=111+1=112\lfloor (224 + 6 - 7)/2 \rfloor + 1 = \lfloor 223/2 \rfloor + 1 = 111 + 1 = 112. ResNet follows it with a 3×3 stride-2 max pooling to get 56×56.

PyTorch PyTorch: nn.Conv2d and unfold (im2col) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

conv = nn.Conv2d(in_channels=3, out_channels=8, kernel_size=3, stride=2, padding=1)
x = torch.randn(4, 3, 32, 32)                    # (batch, channels, H, W)
y = conv(x)
print(y.shape)                                   # torch.Size([4, 8, 16, 16])
print(sum(p.numel() for p in conv.parameters())) # 8*3*3*3 + 8 = 224

# the same computation as im2col (F.unfold) + a matrix product
cols = F.unfold(x, kernel_size=3, stride=2, padding=1)       # (4, 3*3*3, 16*16)
y2 = conv.weight.view(8, -1) @ cols + conv.bias.view(1, 8, 1) # (4, 8, 256)
print(torch.allclose(y, y2.view(4, 8, 16, 16), atol=1e-5))    # True

# a typical block: conv → norm → nonlinearity → downsample
block = nn.Sequential(
    nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
    nn.Conv2d(32, 64, 3, padding=1, stride=2), nn.BatchNorm2d(64), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10),
)
print(block(x).shape)                            # torch.Size([4, 10])
 

Summary

  • Convolution = local connectivity + weight sharing. The parameter count is independent of the number of positions (Cout(CinK2+1)C_{\text{out}}(C_{\text{in}}K^2+1)).
  • Output size ⌊(N+2P−K)/S⌋+1\lfloor (N + 2P - K)/S \rfloor + 1. 3×3 with padding 1 and stride 1 preserves the size; stride 2 halves it.
  • Stacking LL 3×3 layers gives a receptive field of 1+L(K−1)1 + L(K-1). Stacking small kernels deep is cheaper and more nonlinear than one large kernel.
  • Convolution is translation equivariant; pooling is only locally invariant. Downsampling breaks exact invariance.
  • im2col turns convolution into a single matrix product. In backprop, the gradients of overlapping windows add up.

자주 쓰는 경우는 외워 둘 만하다.

  • S=1S = 1, P=(K−1)/2P = (K-1)/2: 크기 유지(“same”). 3×3 + padding 1이 기본형이다.
  • S=2S = 2: 크기 절반. 해상도를 줄이며 채널을 늘리는 단계에서 쓴다.
  • P=0P = 0: 층마다 K−1K - 1씩 줄어든다(“valid”).

수용 영역

출력의 한 픽셀이 결과적으로 보는 입력 영역을 수용 영역(receptive field) 이라 한다. stride 1인 K×KK\times K 합성곱을 LL번 쌓으면 수용 영역은 1+L(K−1)1 + L(K-1)이다. 3×3을 두 번 쌓으면 5×5, 세 번이면 7×7. VGG의 설계 논리가 이것이다. 3×3 두 층은 5×5 한 층과 같은 범위를 보면서 매개변수는 2⋅9C2=18C22\cdot 9C^2 = 18C^2 대 25C225C^2로 적고, 사이에 비선형이 하나 더 들어간다. stride나 pooling이 끼면 그 뒤 층의 한 칸이 입력에서 여러 칸에 해당하므로 수용 영역이 곱셈적으로 빨리 자란다.

등변성과 pooling

합성곱은 이동 등변(translation equivariant) 이다. 입력을 옮긴 뒤 합성곱한 것과 합성곱한 뒤 옮긴 것이 같다(경계 효과 제외). 가중치 공유에서 바로 나오는 성질이다. 모든 위치에서 같은 커널을 쓰니 고양이가 어디 있든 같은 반응이 그 위치에 나타난다.

분류에는 등변성보다 불변성(어디 있든 같은 답)이 필요하다. pooling 이 그 다리를 놓는다. 2×2 max pooling은 겹치지 않는 2×2 칸마다 최댓값만 남겨 해상도를 절반으로 줄이고, 그 칸 안에서 특징이 조금 움직여도 출력이 같게 만든다. 층을 거듭하며 국소 불변성이 쌓이고, 마지막의 global average pooling(채널마다 전체 평균)은 위치 정보를 완전히 버린다. 다만 stride와 pooling의 다운샘플링은 엄밀한 이동 불변성을 깨뜨린다(1픽셀 이동이 출력을 바꿀 수 있다). 아래 코드에서 정도를 확인해 보자.

직접 구현: 루프와 im2col

합성곱을 문자 그대로 구현하면 출력 위치마다 작은 내적을 한다. 빠른 구현은 이것을 행렬곱 하나 로 바꾼다. 모든 창을 펼쳐 열로 늘어놓은 행렬(im2col, CinK2×H′W′C_{\text{in}}K^2 \times H'W')을 만들고, 필터를 행으로 늘어놓은 행렬(Cout×CinK2C_{\text{out}} \times C_{\text{in}}K^2)과 곱한다. 메모리를 K2K^2배 더 쓰는 대신 고도로 최적화된 GEMM을 쓸 수 있다(cuDNN은 이 외에도 FFT, Winograd 등 여러 알고리즘 중 빠른 것을 고른다).

NumPy conv2d: 루프 vs im2col, 출력 크기 공식 확인
import numpy as np, time
rng = np.random.default_rng(0)

def out_size(n, k, s=1, p=0):
    return (n + 2 * p - k) // s + 1

def conv2d_loops(x, w, b, stride=1, pad=0):
    """x: (C_in, H, W), w: (C_out, C_in, K, K), b: (C_out,) → (C_out, H', W')"""
    C_out, C_in, K, _ = w.shape
    x = np.pad(x, ((0, 0), (pad, pad), (pad, pad)))
    H2 = (x.shape[1] - K) // stride + 1
    W2 = (x.shape[2] - K) // stride + 1
    y = np.zeros((C_out, H2, W2))
    for o in range(C_out):
        for i in range(H2):
            for j in range(W2):
                patch = x[:, i*stride:i*stride+K, j*stride:j*stride+K]   # (C_in, K, K)
                y[o, i, j] = np.sum(patch * w[o]) + b[o]                # 내적 하나
    return y

def im2col(x, K, stride=1, pad=0):
    """모든 창을 펼쳐 (C_in*K*K, H'*W') 행렬로. 열 하나 = 창 하나."""
    C, H, W = x.shape
    x = np.pad(x, ((0, 0), (pad, pad), (pad, pad)))
    H2, W2 = out_size(H, K, stride, pad), out_size(W, K, stride, pad)
    cols = np.empty((C, K, K, H2, W2))
    for di in range(K):              # K*K 번만 반복 (위치 수와 무관)
        for dj in range(K):
            cols[:, di, dj] = x[:, di:di + stride*H2:stride, dj:dj + stride*W2:stride]
    return cols.reshape(C * K * K, H2 * W2), (H2, W2)

def conv2d_im2col(x, w, b, stride=1, pad=0):
    C_out, C_in, K, _ = w.shape
    cols, (H2, W2) = im2col(x, K, stride, pad)
    y = w.reshape(C_out, -1) @ cols + b[:, None]   # 합성곱 = 행렬곱 하나
    return y.reshape(C_out, H2, W2)

x = rng.normal(size=(3, 32, 32))          # RGB 32×32
w = rng.normal(size=(8, 3, 3, 3))         # 3→8 채널, 3×3
b = rng.normal(size=8)
for stride, pad in [(1, 1), (2, 0), (2, 1)]:
    t0 = time.perf_counter(); y1 = conv2d_loops(x, w, b, stride, pad); t1 = time.perf_counter()
    y2 = conv2d_im2col(x, w, b, stride, pad); t2 = time.perf_counter()
    print(f"S={stride} P={pad}: 출력 {y1.shape}, 공식 {out_size(32, 3, stride, pad)}, "
          f"최대차 {np.abs(y1 - y2).max():.1e}, 루프 {1e3*(t1-t0):6.1f} ms, im2col {1e3*(t2-t1):5.2f} ms")

print("\n매개변수: conv 3→8, 3×3 =", w.size + b.size,
      "  vs 같은 입출력 크기의 완전연결 =", (3*32*32) * (8*32*32) + 8*32*32)
 

im2col 쪽의 파이썬 루프는 K2=9K^2 = 9번뿐이고, 나머지는 슬라이싱과 행렬곱이다. 역전파도 같은 구조다. 출력 기울기 GG(Cout×H′W′C_{\text{out}} \times H'W')에 대해 ∂L/∂W=G cols⊤\partial L/\partial W = G\,\text{cols}^\top, ∂L/∂ cols=W⊤G\partial L/\partial\,\text{cols} = W^\top G이고, 이것을 다시 이미지 모양으로 접으면서 겹치는 창의 기여를 더한다(col2im). 한 입력 픽셀이 여러 창에 쓰이는 fan-out이기 때문이다.

NumPy 등변성, pooling, 수용 영역 확인
# 이동 등변성: 입력을 옮기면 출력도 똑같이 옮겨진다 (경계 효과 제외)
img = np.zeros((1, 24, 24)); img[0, 5:9, 4:10] = 1.0          # 작은 직사각형
shifted = np.roll(img, shift=(6, 7), axis=(1, 2))              # 아래로 6, 오른쪽으로 7
edge = np.array([[[[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]]], dtype=float)   # 세로 경계 필터
f = lambda z: conv2d_im2col(z, edge, np.zeros(1), 1, 1)
lhs = f(shifted)                                   # 옮긴 뒤 합성곱
rhs = np.roll(f(img), shift=(6, 7), axis=(1, 2))   # 합성곱 뒤 옮김
print("conv(shift(x)) == shift(conv(x)) ?", np.allclose(lhs, rhs))

# max pooling은 작은 이동에 부분적으로 불변
def maxpool(z, k=2):
    C, H, W = z.shape
    return z[:, :H//k*k, :W//k*k].reshape(C, H//k, k, W//k, k).max(axis=(2, 4))
fm, fm1 = np.abs(f(img)), np.abs(f(np.roll(img, 1, axis=2)))   # 1픽셀 이동
act = lambda u, v: (u > 0) | (v > 0)          # 둘 중 하나라도 켜진 칸만 비교
a, c = maxpool(fm), maxpool(fm1)
print(f"1픽셀 이동 후 같은 값인 칸: pooling 전 {np.mean(np.isclose(fm, fm1)[act(fm, fm1)]):.0%}"
      f", 2×2 max pooling 후 {np.mean(np.isclose(a, c)[act(a, c)]):.0%}")

# 수용 영역: 3×3 conv를 L번 쌓으면 출력 한 픽셀이 보는 입력 범위
for L in [1, 2, 3, 5]:
    probe = np.zeros((1, 21, 21)); probe[0, 10, 10] = 1.0
    z = probe
    box = np.ones((1, 1, 3, 3))
    for _ in range(L):
        z = conv2d_im2col(z, box, np.zeros(1), 1, 1)
    print(f"3×3 conv {L}층 → 수용 영역 {int(np.sqrt((z[0] > 0).sum()))}×{int(np.sqrt((z[0] > 0).sum()))}"
          f"  (공식 1 + L(K−1) = {1 + 2*L})")
 

pooling이 불변성을 “완벽히”가 아니라 “조금” 높인다는 것이 보인다. 실제 CNN의 이동 강건성은 이런 국소 불변성이 여러 층에 걸쳐 쌓이고, 데이터 증강(무작위 자르기·이동)으로 학습되는 몫이 크다.

확인 문제Check yourself

입력 224×224, 커널 7×7, stride 2, padding 3인 합성곱의 출력 크기는? (ResNet의 첫 층)

⌊(224+6−7)/2⌋+1=⌊223/2⌋+1=111+1=112\lfloor (224 + 6 - 7)/2 \rfloor + 1 = \lfloor 223/2 \rfloor + 1 = 111 + 1 = 112. ResNet은 이 뒤에 3×3 stride 2 max pooling을 붙여 56×56으로 만든다.

PyTorch PyTorch: nn.Conv2d와 unfold(im2col) 로컬에서 실행run locally (pip install torch)
import torch
import torch.nn as nn
import torch.nn.functional as F

conv = nn.Conv2d(in_channels=3, out_channels=8, kernel_size=3, stride=2, padding=1)
x = torch.randn(4, 3, 32, 32)                    # (배치, 채널, H, W)
y = conv(x)
print(y.shape)                                   # torch.Size([4, 8, 16, 16])
print(sum(p.numel() for p in conv.parameters())) # 8*3*3*3 + 8 = 224

# 같은 계산을 im2col(F.unfold) + 행렬곱으로
cols = F.unfold(x, kernel_size=3, stride=2, padding=1)       # (4, 3*3*3, 16*16)
y2 = conv.weight.view(8, -1) @ cols + conv.bias.view(1, 8, 1) # (4, 8, 256)
print(torch.allclose(y, y2.view(4, 8, 16, 16), atol=1e-5))    # True

# 전형적인 블록: conv → norm → 비선형 → 다운샘플
block = nn.Sequential(
    nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
    nn.Conv2d(32, 64, 3, padding=1, stride=2), nn.BatchNorm2d(64), nn.ReLU(),
    nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(64, 10),
)
print(block(x).shape)                            # torch.Size([4, 10])
 

정리

  • 합성곱 = 국소 연결 + 가중치 공유. 매개변수 수가 위치 수와 무관하다(Cout(CinK2+1)C_{\text{out}}(C_{\text{in}}K^2+1)).
  • 출력 크기 ⌊(N+2P−K)/S⌋+1\lfloor (N + 2P - K)/S \rfloor + 1. 3×3·padding 1·stride 1은 크기 유지, stride 2는 절반.
  • 3×3을 LL번 쌓으면 수용 영역 1+L(K−1)1 + L(K-1). 작은 커널을 깊게 쌓는 것이 큰 커널 하나보다 싸고 비선형적이다.
  • 합성곱은 이동 등변, pooling은 국소적으로만 불변. 다운샘플링은 엄밀한 불변성을 깬다.
  • im2col은 합성곱을 행렬곱 하나로 바꾼다. 역전파에서 겹치는 창의 기울기는 더해진다.

더 읽을거리Further reading