PyTorch ์์ ์ ๊ณตํ๋ convolution ํจ์์ ์ค์ ๊ฐ๋ฅํ parameter ์คpadding
๊ณผ padding_mode
๋ผ๋ ๊ฒ์ด ์๋ค.
padding
์ ๊ฒฝ์ฐ padding์ ํฌ๊ธฐ๋ฅผ ์ง์ ํ ์ ์๋ parameter์ธ๋ฐ (int
ํน์ tuple
), PyTorch 1.9.0๋ถํฐ string
์ผ๋ก ์ง์ ํ ์ ์๋ ์ต์
์ด ์ถ๊ฐ๋์๋ค.
์ด๋ Tensorflow์์๋ ์๋ ์๋ ์ต์
์ธ๋ฐ, padding์ ํฌ๊ธฐ๋ฅผ ์ง์ ์ง์ ํ๋ ๋์ same
ํน์ valid
์ต์
์ ์ฃผ๋ฉด input size์ ๋ง๊ฒ ์๋์ผ๋ก padding ํฌ๊ธฐ๊ฐ ์ค์ ๋๋ค.
- valid๋ padding์ ๋ฐ๋ก ์ฃผ์ง ์๊ณ input image ์์ฒด๋ง์ ์ด์ฉํด convolution ์ฐ์ฐ์ ์ํํ๋ค.
- same์ output size๊ฐ input size์ ๋์ผํ๊ฒ ๋๋๋ก padding์ ์กฐ์ ํ๋ค. ๋ง์ฝ stride=1, dilation=1์ธ ๊ฒฝ์ฐ padding=(kernel_size-1)/2๋ก ์ค์ ๋๋ค.
padding_mode
๋ padding์ ๋ญ๋ก ์ฑ์ธ ์ง ์ค์ ํ ์ ์๋ค. zeros
, reflect
, replicate
, circular
์ด ์์ผ๋ฉฐ, ๊ธฐ๋ณธ ๊ฐ์ zeros
๋ก, padding์ ๋ชจ๋ 0์ผ๋ก ์ฑ์ด๋ค. ๋๋ถ๋ถ zero-filling์ ์ฌ์ฉํ์ง๋ง ๋ค์ํ ์ ํ์ง๊ฐ ์์ด ์๊ฐํด ๋ณด๊ณ ์ ํ๋ค.
* ์์๋ฅผ ์ํด [1, 2, 3, 4, 5] ๋ชจ์์ 1D tensor์ padding์ 4๋ก ์ค์ ํ 1D identity Conv ์ฐ์ฐ์ ์ด์ฉํ๋ค.
- zeros: zero-filling์ ์ด์ฉํ๋ค.
x = torch.tensor([[[1, 2, 3, 4, 5]]]).float()
conv = nn.Conv1d(1, 1, 3, padding=4, padding_mode='zeros', bias=False)
conv.weight = torch.nn.Parameter(torch.tensor([[[0., 1., 0.]]]))
y = conv(x)
print(y)
>> tensor([[[0., 0., 0., 1., 2., 3., 4., 5., 0., 0., 0.]]])
- reflect: ์ ๋์ ๊ฑฐ์ธ์ฒ๋ผ ๋ฐ์ฌ๋ ๊ฐ์ ์ฌ์ฉํ๋ค. ๋จ, ์ด ๊ฒฝ์ฐ input ํฌ๊ธฐ๋ณด๋ค ๋ ํฐ ๊ฐ์ padding์ ์ฌ์ฉํ ์ ์๋ค.
x = torch.tensor([[[1, 2, 3, 4, 5]]]).float()
conv = nn.Conv1d(1, 1, 3, padding=4, padding_mode='reflect', bias=False)
conv.weight = torch.nn.Parameter(torch.tensor([[[0., 1., 0.]]]))
y = conv(x)
print(y)
>> tensor([[[4., 3., 2., 1., 2., 3., 4., 5., 4., 3., 2.]]])
- replicate: ์ ๋๋จ์ ๊ฐ์ padding ๊ฐ์ผ๋ก ์ด์ฉํ๋ค.
import torch
import torch.nn as nn
x = torch.tensor([[[1, 2, 3, 4, 5]]]).float()
conv = nn.Conv1d(1, 1, 3, padding=4, padding_mode='replicate', bias=False)
conv.weight = torch.nn.Parameter(torch.tensor([[[0., 1., 0.]]]))
y = conv(x)
print(y)
>> tensor([[[1., 1., 1., 1., 2., 3., 4., 5., 5., 5., 5.]]])
- circular: input ๊ฐ์ ์ํํ์ฌ ์ฌ์ฉํ๋ค.
import torch
import torch.nn as nn
x = torch.tensor([[[1, 2, 3, 4, 5]]]).float()
conv = nn.Conv1d(1, 1, 3, padding=4, padding_mode='circular', bias=False)
conv.weight = torch.nn.Parameter(torch.tensor([[[0., 1., 0.]]]))
y = conv(x)
print(y)
>> tensor([[[3., 4., 5., 1., 2., 3., 4., 5., 1., 2., 3.]]])