VGG모델 정의
1. 모델 정의
- 출력텐서 7X7 → AdaptiveAvgPool2d출력텐서
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계층 정의
- config(모델구조)를 c로 불러옴
- 그리고 이 c가 M이거나 정수형일 수만 있음
- 그리고 batchnorm을 어떻게 할건지도 정의
- 배치놈이 TRUE면 렐루랑 배치정규화를
- False면 렐루만 적용
- 그리고 최종적으로 layers전부 반환
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)