Convolution?
이미지 위에서 stride 만큼 filter(kernel)을 이동시키며 겹쳐지는 각 부분을 element-wise multiply하여 모두 더한 값을 출력하는 연산이다.
Stride and Padding
stride : filter를 한번에 얼마나 이동하는가
padding : zero - padding한다.
Pytorch nn.Conv2d
torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, bias=True)
ex) input channel 1, output channel 1, kernel size (3, 3)
→ conv = nn.Conv2d(1, 1, 3)
입력 형태
input type : torch.Tensor
input shape : (N x C x H x W)
N : batch_size
C : channel
H : height
W : width
Convolution의 output
ex 1) input size : 227x227, filter size : 11x11, stride=4, padding = 0 일 때를 생각해보자.
ex 2) input size : 64x64, filter size : 7x7, stride=2, padding = 0 일 때를 생각해보자. (소수점 아래는 버린다)
Code를 통한 확인
import torch
import torch.nn as nn
inputs = torch.Tensor(1, 1, 227, 227)
inputs.shape # torch.Size([1, 1, 227, 227])
conv = nn.Conv2d(1, 1, kernel_size=(11, 11), stride=(4, 4))
out = conv(inputs)
out.shape
# torch.Size([1, 1, 55, 55])
Pooling?
이미지 사이즈를 줄이기 위한 연산으로 Max Pooling과 Average Pooling이 있다.
Max Pooling
size = 2x2이고 각 영역에서 최대 값을 가져온다.
Average Pooling
size = 2x2이고 각 영역의 평균값을 가져온다.
Pytorch nn.MaxPool2d
torch.nn.MaxPool2d(kernel_size, ...)
아래 그림과 같은 CNN을 Code로 구성해보자.
input = torch.Tensor(1, 1, 28, 28)
conv1 = nn.Conv2d(1, 5, 5)
pool = nn.MaxPool2d(2)
out = conv1(input)
out2 = pool(out)
print('out1 : ', out.size())
print('out2 : ', out2.size())
'''
out1 : torch.Size([1, 5, 24, 24])
out2 : torch.Size([1, 5, 12, 12])
'''