Q1. 아래의 코드에서 정의된 함수
get_features
의 기능과 동작방법?
def get_features(image, model, layers=None):
""" Run an image forward through a model and get the features for
a set of layers. Default layers are for VGGNet matching Gatys et al (2016)
"""
## TODO: Complete mapping layer names of PyTorch's VGGNet to names from the paper
## Need the layers for the content and style representations of an image
if layers is None:
layers = {'0': 'conv1_1',
'5': 'conv2_1',
'10': 'conv3_1',
'19': 'conv4_1',
'21': 'conv4_2', ## content representation
'28': 'conv5_1'}
features = {}
x = image
# model._modules is a dictionary holding each module in the model
for name, layer in model._modules.items():
x = layer(x)
if name in layers:
features[layers[name]] = x
return features
[+] 위 코드에서 나오는 Variable들 설명
image
: 가로 size를 최대 400 pixel로 만든 Normalized Tensor (일단 그냥 이미지라고 생각하면 됨) ex) 최종 size는 1x3x500x400
= Batch size x Depth(=Color channel) x Height x Width
model
: VGG19 모델을 미리 받아서 할당함 (classifier부분은 제외하고 features부분, 즉 Convolutional layer부분만 받음)
layers
: Style Transfer paper에서 알려주는 content & style feature를 추출할 수 있는 Layer 목록 (Dictionary형태로 매핑 및 네이밍시켜줌)
[+] 위 코드 get_features()
함수 설명
if문 : 그냥 사용자가 임의의 layers
를 Function argument로 넣어주지 않으면 이와 같은 layers
를 사용한다 이런느낌
features
: 입력 이미지 모델로 feedforward 할 때, 내가 원하는 층에서의 feature, 즉 output들을 추출하여 담아둘 바구니
for문 : model._modules
는 해당 모델의 각 모듈들 (모델의 layer들이라고 보면됨)을 {Name : Layer}
형태의 Dictionary로 반환해줌
ex) 0 : Conv2D(16,128,padding = 1, ...)
따라서 각 for loop당 1개 층의 name과 layer를 받음
x = layer(x)
: 자 for loop를 통해 x = image
이므로 x
를 각 Layer에 넣어주면서 feedforward를 진행하는거임!if name in layers:
: 말그대로 layers
우리가 임의로 해당 함수에 넣어준 argument, 즉 추출을 원하는 Layer 목록 속에 name
이 포함된다면 = 우리가 추출을 원하는 Layer가 feedforward 되는중인거지! 딱 이때features[layers[name]] = x
: 미리 선언해둔 빈 바구니 features
에 layers[name]
, 즉 우리가 미리 만들었던 layers
의 키값들, ex) conv1_1
, conv2_1
등 을 키값으로 주고 속성값으로는 feedforward된 값, x
를 넣어준다.get_features(image, model, layers)
we can get features/output of any layer mentioned in argument layers
, using an given image
after processing it using the given trained model
.get_features(image, model, layers) 함수는 'model'에 'image'를 넣었을 때, 'layers'에서 언급한 특정 layer에서의 output값을 추출할 수 있게끔해준다.