VGG모델 정의

1. 모델 정의

class VGG(nn.Module) :
    def __init__(self, in_features,out_features, features, output_dim) :
        super().__init__()
        self.features = features
        self.avgpool = nn.AdaptiveAvgPool2d(7)
        self.classifier = nn.Sequential(
            nn.Conv2d(in_features, out_features), #512*7*7, 4096
            nn.ReLU(inplace = True),
            nn.Dropout(0.5),
            nn.Linear(out_features,out_features), #4096
            nn.ReLU(inplace = True), 
            nn.Dropout(0.5),
            nn.Linear(out_features, output_dim),
        )
        
    def forward(self, x) :
        x = self.features(x)
        x = self.avgpool(x)
        h = x.view(x.shape[0],-1) # 행만큼 세로로 쭉 세우기
        x = self.classifier(h)
        return x, h

2. VGG계층 정의

def get_vgg_layers(config, batch_norm):
    layers = []
    in_channels = 3

    for c in config: 
        assert c == 'M' or isinstance(c, int) 
        if c == 'M': 
            layers += [nn.MaxPool2d(kernel_size = 2)]
        else: 
            conv2d = nn.Conv2d(in_channels, c, kernel_size=3, padding=1)
            if batch_norm: #배치 정규화(batch normalization)를 적용할지에 대한 코드
                layers += [conv2d, nn.BatchNorm2d(c), nn.ReLU(inplace=True)] #배치 정규화가 적용될 경우 배치 정규화+ReLU 적용       
            else:
                layers += [conv2d, nn.ReLU(inplace=True)] # 배치 정규화가 적용되지 않을 경우 ReLU만 적용
            in_channels = c

    return nn.Sequential(*layers) # 네트워크의 모든 계층을 반환

3. VGG 레이어 생성

vgg11_layers = get_vgg_layers(vgg11_config, batch_norm=True)