import torch
import torch.nn as nn
# in_channels=1 -> 흑백 이미지 입력
# out_channels=4 -> filter 4개
# kernel_size=3 -> (3, 3) filter
conv = nn.Conv2d(in_channels=1, out_channels=4, kernel_size=3)
input_ = torch.randn(1, 10, 20) # (10, 20)의 흑백 이미지
print(f"input shape: {input_.shape}\n")
print("Parameter Shape:")
print(f"weight: {conv.weight.shape}") # (4, 3, 3)
print(f"bias: {conv.bias.shape}\n") # (4,)
output = conv(input_)
# H' = H - F + 1 = 10 - 3 + 1 = 8
# W' = W - F + 1 = 20 - 3 + 1 = 18
print(f"output shape: {output.shape}")
import torch
import torch.nn as nn
conv = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
input_ = torch.randn(1, 32, 32) # (1, 32, 32)
print(f"input shape: {input_.shape}\n")
print("Parameter Shape:")
print(f"weight: {conv.weight.shape}")
print(f"bias: {conv.bias.shape}\n")
output = conv(input_)
print(f"output shape: {output.shape}") # (6, 28, 28)
import torch
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
self.conv1_act = nn.Tanh()
def forward(self, x):
print(f"input: {x.shape}")
x = self.conv1_act(self.conv1(x))
print(f"after conv1: {x.shape}")
return x
model = LeNet5()
test_input = torch.randn(1, 32, 32)
output = model(test_input)
입력 채널이 여러개인 경우(예. 컬러 이미지가 들어올 경우)
import torch
import torch.nn as nn
conv = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
input_ = torch.randn(6, 32, 32)
print(f"input shape: {input_.shape}\n")
print("Parameter Shape:")
print(f"weight: {conv.weight.shape}") # [16, 6, 5, 5]
print(f"bias: {conv.bias.shape}\n") # [16]
output = conv(input_)
print(f"output shape: {output.shape}") # [16, 28, 28]
import torch
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
self.conv1_act = nn.Tanh()
self.conv2 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=5)
self.conv2_act = nn.Tanh()
self.conv3 = nn.Conv2d(in_channels=16, out_channels=120, kernel_size=5)
self.conv3_act = nn.Tanh()
def forward(self, x):
print(f"input: {x.shape}")
x = self.conv1_act(self.conv1(x))
print(f"after conv1: {x.shape}")
x = self.conv2_act(self.conv2(x))
print(f"after conv2: {x.shape}")
x = self.conv3_act(self.conv3(x))
print(f"after conv3: {x.shape}")
return x
model = LeNet5()
test_input = torch.randn(1, 32, 32)
output = model(test_input)
항상 좋은 글 감사합니다.