[코세라 딥러닝 정리] C4W4 - Special Applications: Face recognition & Neural Style Transfer

딥러닝 특화 과정을 수강하고 러닝을 정리합니다.

Objective

  • Differentiate between face recognition and face verification

    • One-shot learning to solve a face recognition problem
    • Triplet loss function to learn a network's parameters in the context of face recognition
    • Face recognition as a binary classification problem
    • Map face images into 128-dimensional encodings using a pretrained model
      • Perform face verification and face recognition with these encodings
  • Implement the Neural Style Transfer algorithm

    • style cost function
    • content cost function

1 - Face Recognition

1-1. What is Face Recognition?

Face recognition system 얼굴인식시스템은 사람의 얼굴을 식별하고, image나 video에도 작동한다. Liveness detection within a video face recognition system prevents the network from identifying a face in an image.
It can be learned by supervised deep learning using a dataset for live human and in-live human and sequence learning.

Face verification vs face recognition

Face Recognition system 은 verification 검증, recognition인식으로 분류할 수 있다.

  • Verification
    • Input: image, name/ID. (1 : 1)
    • Output: whether the input image is that of the claimed person. "is this the claimed person?"
  • Recognition:
    • Has a database of K persons
    • Get an input image
    • Output ID if the image is any of the K persons (or not recognized) "who is this person?"

얼굴인식시스템을 구현하기 위해서 face verification을 사용하는데, face verificaiton의 정확도가 높아야(around 99.9% or more) 얼굴인식시스템이 정확하게 작동한다. K명의 사람에 대해서 face recognition이 verification보다 덜 정확하기 때문이다.

1-2. One Shot Learning

one shot learning은 각각의 class에 하나의 훈련 데이터만으로도 이미지를 인식하고 분류하는 모델을 학습시키는 것을 말한다.

  • Face Recognition 얼굴인식시스템에서 자주 활용되고, 하나의 이미지만을 학습해 한 사람만 인식할 수 있다. 원래 딥러닝은 작은 데이터에서 잘 작동하지 않지만, similarity function 유사도 함수를 학습해 작동 가능하게 만들었다.
    • Similarity function
      $d(\textrm{image 1}, \textrm{image 2})$ = degree of difference between images
      • 두개의 이미지에 적용
      • 동일한 이미지의 경우 $d$가 작아진다.
      • Threshold for $d$인 $\tau$ 를 지정한다.
      • $If$ $d( img1, img2 )$ <= $\tau$ $Then$ 두 얼굴은 동일하다."same"
      • robust to new inputs 새로운 사람에 대한 데이터 추가될 때 신경망을 재 훈련 시킬 필요가 없다.

1-3. Siamese Network

DeepFace
Siamese Networks 샴 네트워크는 이미지들을 인코딩을 통해 수치화하고 두 이미지가 얼마나 다른지를 학습하는 것을 목표로한다. 즉, 두 개의 입력에 대해 독립적으로 두 개의 동일한 합성곱 신경망을 실행한 뒤 비교하는 아이디어이다.

  • 기본 ConvNet (일련의 Convolution layers, Pooling, FC..)

    • 입력 이미지 Input image $x^{(i)}$
    • 합성곱신경망 FC layer 결과 encoded output $f(x^{(i)})$
  • Similarity function
    여러 개의 입력을 동일한 구조와 파라미터를 가지는 두 개 이상의 신경망에 독립적으로(각각) 집어넣는 Siamease Network 샴 네트워크 신경망을 사용해 Similarity Function 유사도 함수를 구현한다.

  • Siamese network architecture
    입력 이미지를 벡터로 인코딩하는 2개의 동일한 합성곱 신경망 convnets

    • image ⇒ vector shape (128, )
  • Loss function of Siamese network
    $d(x1, x2) = || f(x1) - f(x2) ||^2$

    • (인코딩 벡터 사이의 거리)
    • X1, X2가 동일인물이면, $d$는 작아지고, 다른사람이면 $d$는 커진다.

1-4.Triplet Loss


Triplet Loss 삼중항 손실은 Siamese network 샴네트워크의 Objective Function 목적함수이다.

  • Triplet loss function 훈련 목표는 Anchor image와 positive or negative image 간의 거리를 구하는 것이다. get the distance between an Anchor image and a positive or a negative image

    • "triplet"은 anchor A, positive P, negative N을 비교한다는 뜻에서 붙여진 이름이다.
      Given 3 images (A, P, N)
      • A Anchor image의 인코딩 벡터 (기준)
      • P Positive image: same 동일한 사람의 인코딩 벡터
      • N Negative : different 다른 사람의 인코딩 벡터
  • 기본적으로 알고리즘의 결과가 다음과 같게 만들고자한다.

    • Positive distance to be less than negative distance : $d( A, P ) ≤ d(A, N)$
      동일한 사람과의 거리가 다른 사람과의 거리보다 작다.
      • $||f(A) - f(P)||^2 <= ||f(A) - f(N)||^2$
      • $||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 ≤ 0$
      • 신경망이 0이라는 결과를 출력하지 못하게 하기 위해 small margin $\alpha$를 사용해 표현한다.
        $||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 ≤ - \ \alpha$
      • 정리하면,
        $||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 + \ \alpha ≤ 0$
  • Final Triplet Loss Function 최종 삼중항 비용함수

    • Loss Function 손실 함수
      $L(A, P, N) = max (||f(A) - f(P)||^2 - ||f(A) - f(N)||^2 + \alpha , 0)$

      • 0보다 작으면, 동일한 사람으로 판단하고 0으로 설정한다.
    • $J =$ $\sum_{i=1}^m L(A^{[i]}, P^{[i]}, N^{[i]})$ for all triplets of images.

      • $J$ 비용함수를 최소화하기 위해 경사하강법을 적용해 $d(A, P)$ 최소, $d (A, N)$ 최대가 되도록 최적화 과정을 통해 학습한다.
  • Choosing the triplets A,P,N

    • 실제 훈련 세트를 구성할 때, 다수의 동일한 인물의 이미지가 필요하고, 수집된 이미지 데이터를 triplets로 나눈다.
      • Choosing the triplets A, P, N : $(A,P)$ 동일한 대상, $N$ 동일하지 않은 대상 pair를 랜덤으로 선택한다.
    • $(A,N)$ 데이터가 뽑힐 확률이 훨씬 높기 때문에, choose triplets that are hard to train on 훈련하기 어려운 triplets을 선택하는 것이 좋다.
      • $d(A, P) + \alpha ≤ d (A, N)$를 만족하되,
      • 동일한 대상이지만 $d(A, P)$ 값이 낮고, 다른 대상이지만 $d(A, N)$ 값이 큰 triplets으로 훈련 세트를 구성하면 학습에 도움이 된다.

FaceNet

1-5.Face Verification and Binary Classification

Triplet Loss는 얼굴인식시스템을 위한 ConvNet 파라미터 학습에 좋은 방법이지만, 얼굴인식문제를 straight binary classification problem 이진 분류 문제로 변형해 학습시킬 수 있는 방법도 있다.

  • Learning the similarity function another way

    • Identical ConvNet Siamese Network with same parameters
    • Input : pair of images $X$ ($x^{(i)},x^{(j)}$)
    • Final layer : Sigmoid layer
      인코딩 벡터의 차이를 로지스틱 회귀 유닛에 입력해서 예측(동일한 대상여부에 따라 label 1,0)한다.
      $\hat Y = w_i * \sigma ( f(x^{(i)}) - f(x^{(j)}) ) + b$
      • Similarity Function (인코딩 벡터의 차이 계산 방법)
        • Manhattan distance $f(x^{(i)}) - f(x^{(j)})$
        • Euclidean
        • Ki square similarity $\frac{(f(x^{(i)})_k - f(x^{(j)})_k)^2}{f(x^{(i)})_k - f(x^{(j)})_k}$
  • A good performance/deployment trick for Face Recognition system with Convnet

    1. Pre-compute all the images that you are using as a comparison to the vector $f(x^{(j)})$ 벡터
      모든 이미지에 대해 인코딩 벡터로 변환해 저장한다.
    2. 비교할 새로운 이미지가 입력되면 인코딩 벡터로 변환 후 1의 연산을 하고 Sigmoid 함수에 적용한다.
    3. 이진문제로 변형하는 방법, 삼중항 손실 함수를 사용하는 방법 모두 잘 작동한다.

DeepFace

2 - Neural Style Transfer

2-1. What is Neural Style Transfer?

Neural Style Transfer NST는 ConvNet의 적용 사례 중 하나다.

  • Neural style transfer : $C+S = G$

    1. Content image $C$ (Image A)
    2. Style image $S$ (Image B)
    3. Generated image $G$ (final result)
  • NST를 구현함에 있어 shallower/deeper 레이어에서 Convnet으로 추출한 특성들을 파악해야한다.

    • VGG와 같은 미리 훈련된 합성곱 신경망을 사용해 그 위에 레이어를 쌓아 구현할 수 있다. (Transfer learning)
  • Transfer learning 전이학습은 다른 task에 훈련된 신경망모델을 사용해 새로운 task에 적용하는 것을 의미한다.

  • 텐서플로우로 Neural style transfer를 구현하는 방법

    1. Create an Interactive Session.
    2. Load the content image.
    3. Load the style image
    4. Randomly initialize the image to be generated
    5. Load the VGG16 model
    6. Build the TensorFlow graph
      • Run the content image through the VGG16 model and compute the content cost
      • Run the style image through the VGG16 model and compute the style cost
      • Compute the total cost
      • Define the optimizer and the learning rate
    7. Initialize the TensorFlow graph and run it for a large number of iterations, updating the generated image at every step.

2-2. What are deep ConvNets learning?

심층 합성곱 신경망에 대해서 먼저 살펴보자.

  • Visualizing what a deep network is learning
    AlexNet의 경우를 예로 보자.
    ))))

    • Pick a unit in layer l. Find the nine image patches that maximize the unit's activation. 각 layer의 unit을 최대로 활성화하는 특징들을 파악할 수 있다.

      • 하나의 레이어의 은닉노드로는 신경망에서 작은(상대적으로) 부분을 확인할 수 있다. 즉, 시각화를 통해서 얕은 레이어인 경우 단순한 feature(색감, 테두리)에 해당하는 부분을, 깊은 레이어의 경우 복잡한 feature를 확인할 수 있다.
    • 첫번째 레이어는 첫번째 레이어의 가중치만을 사용해서 생성되는 반면, 다른 레이어(이미지)의 경우 뉴런을 최대로 활성화할 수 있는 이미지에서 "receptive field"를 사용해 생성된다. Other images are generated using the receptive field in the image that triggered the neuron to be max.

  • receptive field given a layer

Visualizing and understanding convolutional networks

2-3. Cost Function

NST 구현을 위해 비용함수를 정의해보자.

  • Neural Style Transfer Cost Function
    (content image $C$, style image $S$, generated image $G$)

    $J(G) = \alpha * J_{content}(C,G) + \beta * J_{style}(S,G)$

    • hyperparameter : $\alpha, \beta$ 상대적 가중치

    • Content Cost $J_{content}(C, G)$ : $G$가 $C$와 얼마나 유사한지

    • Style Cost $J_{style}(S, G)$ : $G$가 $S$와 얼마나 유사한지

  • Example

    • $Content, Style$
    • Find the generated image $G$
      1. Initiate $G$ randomly
        G를 무작위로 초기화해서 white noise image with each pixel value chosen at random 를 얻는다.
        ex. G: 100 X 100 X 3(RGB)
    1. Use gradient descent to minimize J(G)
      $G = G - dG$
      경사하강법을 통해 비용함수를 최소화하고 $G$의 픽셀 값을 업데이트 한다.
      • Compute Gradient descent
      • Minimize the cost function J of G through the pixel value (so then you get slowly an image that looks more and more like content image rendered in the style of your style image)

2-4. Content Cost Function

  • Content Cost

    $J_{content}(C, G)$ at a layer l = $1\over 2$ $|| a^{l} - a^{l} ||^2$

    • Hidden layer $l$ to compute content cost.

      • $l$이 작은 경우 (like layer 1), $G$가 원래 content 이미지와 유사한 픽셀 값을 가질 것이다. 반대로 너무 큰 경우, 너무 다른 픽셀 값(이미지)를 생성할 것이다.
      • $l$이 너무 작지도, 크지도 않은 중간정도의 크기를 선택해야한다.
    • Use pre-trained ConvNet. (E.g., VGG network)
      이미 훈련된 합성곱신경망을 사용해, $C$ontent, $G$enerated 이미지가 얼마나 유사한 지 측정할 수 있다.

      • 레이어 $l$의 활성화 값을 $a^{l}$, $a^{l}$라고 할 때, 두 값이 유사한 경우, $C$ontent, $G$enerated 두 이미지가 유사함을 의미한다.

2-5. Style Cost Function

  • Style as correlation between activations across channels
    이미지 "style"을 측정하기 위해, 각 레이어에서 style은 서로 다른 channels의 활성화 값 간의 상관관계라고 정의한다. Correlation 상관관계는 동일한 이미지에서 동시에 나타나는 지 여부를 말해준다. how a components might occur or not occur together in the same image.

  • 서로 다른 Channel간의 상관관계를 구하기 위해, 두 채널의 모든 $n_H,n_W$ 위치 값들이 한쌍pair를 이루어 어떻게 연관되어있는 지 살펴본다.

    • $a_{i,j,k}^{[l]}$ = activation at $(i=H,j=W,k=C)$

    • Style Matrix : Style 이미지에 대한 상관관계 행렬
      $G^{l}=n_c^{[l]}\times n_c^{[l]}$

  • $kk'$ 위치에서 상관관계 값
    $G_{kk'}^{l} = \displaystyle \sum_{i=1}^{n_H^{[l]}} \sum_{j=1}^{n_W^{[l]}} a_{ijk}^{l} a_{ijk'}^{l}$
    (As it appears its the sum of the multiplication of each member in the matrix)

  • Gram matrix at $l$ layer
    $l$레이어에서 $G$enerated 이미지 대한 상관관계행렬 (비정규화 교차 공분산)
    $G^{l} \displaystyle \sum_{i=1}^{n_H^{[l]}} \sum_{j=1}^{n_W^{[l]}} a_{ijk}^{l} a_{ijk'}^{l}$
    $k$와$k'$의 상관관계 정도를 의미한다. ($k$ 는 1 ~ $n_c^{[l]}$)

    • Gram Matrix detail
    1. Reshape activation from $n_H$ x $n_W$ x $n_C$ to $n_Hn_W$ X $n_C$
    2. Name the reshaped activation Matrix $F$
    3. $G^{[l]} = F* F^T$
  • Style Cost Function

    • Style Cost at $l$ layer
      $l$ 레이어에서 스타일 비용함수는 $G^{l},G^{l}$ 두 상관관계의 차이를 프로베니우스 제곱한 값이다. ($\frac{1}{b}$ 정규화상수)

    $J_{\text{style}}^{[l]} (S, G) = \frac{1}{b} \vert \vert G^{l} - G^{l} \vert \vert_F^2$
    $= \frac{1}{(2 n_H^{[l]} n_W^{[l]} n_C^{[l]})^2} \displaystyle \sum_{k} \sum_{k'} (G_{kk'}^{l} - G_{kk'}^{l} )^2$

    $\frac{1}{b}$ (정규화상수)

    • Style Cost for all layers

      $J_{\text{style}} (S, G) = \displaystyle \sum_l \lambda^{[l]} J_{\text{style}}^{[l]}(S, G)$
      $\lambda$ : hyperparameter (정규화 상수) : NST 모델의 비용함수 계산에서 style 비용함수에 대한 가중치$\beta$가 곱해지기 때문에 중요한 변수는 아니다.

2-6. 1D and 3D Generalizations

지금까지 우리가 살펴본 Convnet은 2차원의 이미지를 위한 것이었다. ConvNet은 1차원, 3차원에도 적용될 수 있다.

  • 1D Convolution

    • 1차원 합성곱 예시
      • Input shape (14, 1)
      • Applying 16 filters with F = 5 , S = 1
      • Output shape will be 10 X 16
      • Applying 32 filters with F = 5, S = 1
      • Output shape will be 6 X 32
    • 일반적인 공식 (N - F)/S + 1이 적용될 수 있지만, 2차원 행렬 대신 벡터를 출력한다.
    • 1차원의 데이터는 waves, sounds, heartbeat signals 와 같은 많은리소스에서 얻을 수 있다.
    • 1차원 데이터를 활용한 케이스들에서는 대부분 순환신경망 RNN을 사용한다.
  • 3D Convolution

    • 3차원 합성곱 예시

      • Input shape (14, 14,14, 1)
      • Applying 16 filters with F = 5 , S = 1
      • Output shape (10, 10, 10, 16)
      • Applying 32 filters with F = 5, S = 1
      • Output shape will be (6, 6, 6, 32)
    • CT scan이 3차원을 활용한 케이스이다.