[PyTorch] Lab10.1 - Convolution

Yun Geonil·2021년 3월 6일
1

📌 학습 목표


  • Convolution
  • Pooling
  • CNN implementation

Convolution

  • 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

    Output size=input sizefilter size+(2padding)Stride+1Output\space size = \frac{input\space size-filter\space size+(2*padding)}{Stride}+1

    ex 1) input size : 227x227, filter size : 11x11, stride=4, padding = 0 일 때를 생각해보자.

    Output size=22711+(20)4+1=55Output\space size = \frac{227-11+(2*0)}{4}+1=55

    ex 2) input size : 64x64, filter size : 7x7, stride=2, padding = 0 일 때를 생각해보자. (소수점 아래는 버린다)

    Output size=647+(20)2+1=28.5+1=29Output\space size = \frac{64-7+(2*0)}{2}+1=28.5+1=29

  • 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

  • Pooling?

    이미지 사이즈를 줄이기 위한 연산으로 Max PoolingAverage Pooling이 있다.

  1. Max Pooling

    size = 2x2이고 각 영역에서 최대 값을 가져온다.

  2. Average Pooling

    size = 2x2이고 각 영역의 평균값을 가져온다.

  • Pytorch nn.MaxPool2d

    torch.nn.MaxPool2d(kernel_size, ...)

CNN implementation

아래 그림과 같은 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])
'''

0개의 댓글