[Q&A] CNN : Lesson 7. Style Transfer

olxtar·2022년 5월 27일
0
post-thumbnail

Question 1

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 : 입력 이미지 \rightarrow 모델로 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를 통해 (VGG) 모델의 모든 Layer의 이름과 Layer를 받음, 그리고 x = image이므로 x를 각 Layer에 넣어주면서 feedforward를 진행하는거임!
    • if name in layers: : 말그대로 layers 우리가 임의로 해당 함수에 넣어준 argument, 즉 추출을 원하는 Layer 목록 속에 name이 포함된다면 = 우리가 추출을 원하는 Layer가 feedforward 되는중인거지! 딱 이때
    • features[layers[name]] = x : 미리 선언해둔 빈 바구니 featureslayers[name], 즉 우리가 미리 만들었던 layers의 키값들, ex) conv1_1, conv2_1 등 을 키값으로 주고 속성값으로는 feedforward된 값, x를 넣어준다.
      \rightarrow 우리가 추출을 원하는 Layer에서의 Feature, 즉 output을 골라서 담아둔다





Answer 1


  • Yes, with 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값을 추출할 수 있게끔해준다.
profile
예술과 기술

0개의 댓글