[Pytorch] 이미지 분류기 구현 - PyTorch Sequential API

윤형준·2022년 9월 4일
0
post-thumbnail

PyTorch Sequential API

Feed forward layers가 여러개 쌓여져 있는 간단한 모델의 경우에도 다음과 같이 3가지 step을 따라야 합니다: subclass nn.Module, assign layers to class attributes in init, and call each layer one by one in forward(). 본 파트에서는 이보다 더 간단한 방법을 제공합니다.

PyTorch 는 nn.Sequential라는 container Module을 제공하고, 이는 위의 3가지 step을 하나로 합쳐 줍니다.

Sequential API: Two-Layer Network
먼저 nn.Sequential를 사용하여 two-layer 네트워크를 다시 정의하고, 앞서 정의한 학습 loop로 학습시켜 봅니다.

별도로 hyperparameters를 수정하지 않고도 한 에폭 이후 40% 이상의 분류 정확도를 보이면 성공입니다.

# We need to wrap `flatten` function in a module in order to stack it
# in nn.Sequential
class Flatten(nn.Module):
    def forward(self, x):
        return flatten(x)

hidden_layer_size = 4000
learning_rate = 1e-2

model = nn.Sequential(
    Flatten(),
    nn.Linear(3 * 32 * 32, hidden_layer_size),
    nn.ReLU(),
    nn.Linear(hidden_layer_size, 10),
)

# you can use Nesterov momentum in optim.SGD
optimizer = optim.SGD(model.parameters(), lr=learning_rate,
                     momentum=0.9, nesterov=True)

train_part34(model, optimizer)

Sequential API: Three-Layer ConvNet

이제 nn.Sequential를 활용하여 Part III와 동일한 구조의 three-layer ConvNet를 직접 정의하고 학습시켜 봅니다:

Convolutional layer (with bias) with 32 5x5 filters, with zero-padding of 2
ReLU
Convolutional layer (with bias) with 16 3x3 filters, with zero-padding of 1
ReLU
Fully-connected layer (with bias) to compute scores for 10 classes
Weight matrices는 앞서 정의한 random_weight 함수로 초기화 하고 bias vectors zero_weight 함수로 초기화 합니다.

Optimizer로는 Nesterov momentum 0.9를 갖는 stochastic gradient descent를 사용합니다.

별도로 hyperparameters를 수정하지 않고도 한 에폭 이후 55% 이상의 분류 정확도를 보이면 성공입니다.

# Req. 1-8	ThreeLayerConvNet을 Sequential API로 구현하기

channel_1 = 32
channel_2 = 16
learning_rate = 1e-2

model = None
optimizer = None

################################################################################
# TODO: Rewrite the 3-layer ConvNet with bias from Part III with the           #
# Sequential API.                                                              #
################################################################################
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

model=nn.Sequential(
    nn.Conv2d(3,channel_1,5,padding=2),
    nn.ReLU(),
    nn.Conv2d(channel_1,channel_2,3,padding=1),
    nn.ReLU(),
    Flatten(),
    nn.Linear(channel_2*32*32,10)
)
# for i in model.parameters():
    # nn.init.kaiming_normal_(i)
for i in model.modules():
    if isinstance(i,nn.Conv2d):
        i.weight=nn.Parameter(random_weight(i.weight.shape))
        i.bias=nn.Parameter(zero_weight(i.bias.shape))
optimizer=optim.SGD(model.parameters(),lr=learning_rate,momentum=0.9)

# *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
################################################################################
#                                 END OF YOUR CODE                             
################################################################################

train_part34(model, optimizer)

profile
매일 조금씩 성장하는 개발자

0개의 댓글