재활용할 블록

class ConvolutionalBlock(nn.Module) :
    def __init__(self, in_channel, out_channel) :
        self.in_channel = in_channel
        self.out_channel = out_channel
        
        super().__init__()
        
        self.layer = nn.Sequential(
            nn.Conv2d(in_channel, out_channel, (3,3), padding = 1),
            nn.ReLU(),
            nn.BatchNorm2d(out_channel),
            nn.Conv2d(out_channel, out_channel, (3,3), stride = 2, padding =2),
            nn.ReLU(),
            nn.BatchNorm2d(out_channel)
            
        )
        def forward() :
            y = self.layer(x)
            
            return y

블록을 재활용한 모습

class ConvolutionalClassifier(nn.Module) :

    def __init__(self, output_size) :
        self.output_size = output_size
        
        super().__init__()
        
        self.block = nn.Sequential( # 입력사이즈 (n,1,28,28)
            ConvolutionalBlock(1,32), # 28+2x1-(3-1)-1 / 2 +1 → 14.5 → 14 (n,32,14,14)
            ConvolutionalBlock(32,64), # (n,64,7,7)
            ConvolutionalBlock(64,128), # (n, 128, 4,4)
            ConvolutionalBlock(128,256), #(n,256,2,2)
            ConvolutionalBlock(256,512), # (n, 512, 1, 1)
        )
        self.layers = nn.Sequential(
            nn.Linear(512,50),
            nn.ReLU(),
            nn.BatchNorm1d(50), 
            nn.Linear(50,output_size),
            nn.LogSoftmax(dim = -1)
        )
        def forward() :
            assert x.dim() >2
            if x.dim() == 3 :
                x = x.view(-1,1,x.size(-2), x.size(-1))
                z = self.block(x)
                y = self.layers(z.squeeze())
                
                return y

train.py 변경하기

  1. 라이브러리 변경