개요 

Face recognition 발전 방향중 Loss function변화를 통한 성능향상, 그중에서도  Classification loss 에 해당.

 

설명

본 블로그 글중 'Open set/Closed set...'에서도 언급했었는데, Face Recognition은 위 사진처럼 Separable하게 할건지 Discriminative 하게 할건지중 open set을 위해서 단순히 class 별로 분리하는 hyper plane을 찾는것(classification)을 넘어서 추가 클래스를 데비해 같은 클래스끼리 가까이 하고 다른클래스는 멀리 위치 시키는 mapping을 수행해야한다.

center loss는 그것을 수행하기 위한 방법중 하나이다.

 

 

Classification은 다음 사진과 같은 문제가 있다.

같은 클래스내에서도 variation이 있기 때문에 Separable 하더라도 충분히 discrimnative 하지 않다면 Face Recognition 성능 저하를 일으킨다.

-> Center loss 를 이용해 discriminative 하게 만들자.  식은 다음과 같다.

mini batch 안에서 각 class 마다 class center를 정한후 class에 속하는 sample들을 class center와 가깝게 위치하도록 loss 로 잡아준다. 이때 center는 feature가 바뀌게 되면 새롭게 업데이트 된다. 

원래는 모든 데이터셋을 가지고 class 별로 center 를 구하는것이 맞으나 inefficient, impractical 하므로 

1. mini-batch 내에서 center 구함.

2. 매 iteration 마다 각 클래스 내의 feature들을 averaging 하여 center loss 를 구하고 이를 사용하여 center를 업데이트함.

위 두가지 공식을 가지고 구하게 된다. 정리된 식은 다음과 같다. 

적용되는 loss = classification loss + lamda * Center loss

최종 Loss는 inter class간 떨어뜨리기 위한 Classification Loss, intra class내에서 뭉쳐있게 하기 위한 Center loss를 더한값으로 사용하여 Inter는 separate 하면서 동시에 intra는 compact하게 만든다.

 

위 내용들을 적용시킨 최종 러닝 알고리듬은 다음과 같다.

 

 

lambda(intra를 inter에 비해 얼마나 중요시 여길거냐) 에 따른 분류되는 embedding된 data들

 

출처 : Yandong Wen, et al. , "A Discriminative Feature Learning Approach for Deep Face Recognition" 2016, ECCV

출처 : www.slideshare.net/JisungDavidKim/center-loss-for-face-recognition

Triplet Loss

 

개요

Triplet Loss는 앞에 설명한 Contrastive loss 와 같이 Deep learning based Face recognition에서 두가지 기술 발전방향중 Loss function에의한 발전에 속하고 그 중에서 verification loss function에 해당. 간단히 말하면 무작위 데이터셋을 뽑은후 positive pair와 negative 를 sample한후 positive는 가까이, negative는 멀리 배치하는 방법.

 

설명

-Distance based loss function

- Anchor(a), Positive(p), Negative(n) 세가지 input 사용

- 식 

   L=max(d(a,p)−d(a,n)+margin,0).

-> positive sample은 가까이, negative sample 은 멀리배치하도록 학습하게됨. 이때 margin 이 더해져 있기 때문에  negative를 멀리 보내게 됨.

Triplet Mining

개요

Triplet Loss 에 따라 dataset의 카테고리를 나눌 수 있음. 종류는 Easy, Hard, Semi-hard

설명

-Easy triplets = loss 가 0 일때 = Max안의 함수가 음수 일때= n은 멀리, a는 가까이 충분히 분리가 잘 되어있을때

=d(a,p)+margin<d(a,n)

 

-hard triplets = negative가 positive보다 anchor에 가까울때 

=d(a,n)<d(a,p)

 

-Semi-hard triplets = negative가 positive보단 멀리 떨어져 있지만 충분한 margin을 넘진 못해서 Loss가 양수일때

=d(a,p)<d(a,n)<d(a,p)+margin

 

실질적으로 max(~~,0)인 함수이므로 anchor와 positive + margin을 기준으로 negative값에 따라 좌우되게 된다.

그러므로 hard negative, easy negative, semi-hard negative라고도 표현한다. 

위 설명을 그림으로 표기하면 다음과 같다.

 

Training

-Offline Triplet mining : manually triplet 을 만든다음 network에 적용시킨다(positve, anchor, negative pair를 일일히 만든다)

-Onling Triplet mining : training data를 batch 형식으로 주어 batch 내에서 triplet을 생성하게 된다. 이렇게하면 triplet을 random하게 뽑게 하므로 high loss를 가지는 triplet(학습에 영향을 많이 끼치는 중요한 triplet)을 찾는 기회가 생긴다.

batch size가 N이면 최대 N^3의 triplet을 생성 할 수 있다. 한번에 모든 data에 대해 triplet 을 만드는것보다 학습속도가 빨라진다.

 

-실제 구현 코드 

  -offline : github.com/eroj333/learning-cv-ml/blob/master/SNN/Offline%20Triplet%20Mining.ipynb

  -online : github.com/eroj333/learning-cv-ml/blob/master/SNN/Online%20Triplet%20Mining.ipynb

 

eroj333/learning-cv-ml

Contribute to eroj333/learning-cv-ml development by creating an account on GitHub.

github.com

Embedding Space for train data using PCA in Tensorboard.

 

출처 : medium.com/@enoshshr/triplet-loss-and-siamese-neural-networks-5d363fdeba9b

 

Closed-set

- 일반적으로 생각하는 classification problem 이다 = input 을 넣으면 정해진 N class 의 output으로 mapping 해준다.

- 학습한 후에는 학습하기전 정해놓은 class에 포함되지 않은 새로운 사람을 추가하거나 있는 사람을 없앨 수 없다.

-> 사람은 굉장히 많고 수시로 관찰하는 clalss가 추가/제외되므로 실제 Face Verification/Identification에 사용하기 어렵다.

-model은 학습하면서 주어진 class를 space안에서 구별할 수 있는 hyper plane을 찾게된다.

 

Open-set

-아예 처음보는 클래스에 대한 데이터도 처리해야 하므로 model은 모든 데이터에 대해 generalize해야한다.

-model은 학습하면서 metric-learning problem을 풀게된다.

      *metric-learning problem = 일종의 similarity metric을 배우는것으로, 서로 구별되는 discriminative features를 뽑기위해 학습한다. 

-hyperplane으로 image를 separate하기 보다는 input space를 재정렬 하게되는데. 비슷한 이미지는 가까이 붙이고 다른 이미지는 멀리 떨어뜨리는, 일종의 clustering problem을 풀게된다.

-그러므로 학습된 model은 data간의 distance matrix를 만드는데 사용 할 수 있고, metric learning이라고 불리는 이유가 된다. (distance metric 자체를 learning을 통해 학습하므로) 

 

Contrastive Loss 

-2005, Yann Le cunn이 처음 소개

-처음목적은 Dimensionality Reduction = inforamtion을 최대한 보존하면서 dimension을 줄이는 mapping 찾기.

-> unseen data에도 generalize 해야하고, 주변간의 관계도 유지하면서 dimension을 줄여야한다.

-> 같은사람이면 사진속 이미지에서 비슷할것이다+ 다른사람이면 이미지간 다를것이다.

->사진마다 찍히는 환경(포즈,조명,크기등)이 모두 다르므로 generalize 하기 위해선 point wise 비교하는것보다는 좀더 높은차원(=추상화가 더많이 된)의 feature 차원에서 비교하는것이 좋을것이다 (코가높다, 눈이크다 등등)

-> feature embedding 한 후에 둘간의 유사도를 비교(Siameses Network 내용 참조)해서 가까우면 같은 사람, 먼사람이면 다른사람이라 구분하자.

물론 같다 다르다의 기준은 threshold를 놓고 비교해서 결정하는데, 이것또한 학습한다.

 

->그럼 어떻게 학습하지?

Contrastive Loss의 Generalized 된 식

위식은 class 가 같은경우 Y=0 이어야 Ls를 줄이는 방향으로, 다를경우, Y=1이어야 Ld를 줄이는 방식으로 작동되게 되어 있습니다. 일반적으로  같은경우 Y=1, 틀린경우 Y=0을 택할것 같은데 다르게 되어있네요...  

1-Y, Y가 반대로 된것같은데.. 아시는분 있으면 댓글 달아주세요!

 

(1-Y,Y) 던 ,(Y,1-Y)던 컨셉은 달라지지 않으니 계속 설명하겠습니다.

where, G=embedding mapping function.

 처음에 나올때는 위 두번째 D 식처럼 Euclidean distance를 사용했지만, 다른종류의 similarity metric (Manhattan distance, Cosine similarity,etc.)도 사용가능하고 실제로 요즘은 hyper sphere 위에 mapping 한다는 개념으로 cosine simlarity를 사용하여 Theta+margin 개념을 사용하고 있다.

 

첫번째 L식으로 보게되면 Cross-Entropy(이하 CE)와 굉장히 유사하게 생겼는데 CE는 Classification task를 수행하면서 network에서 결과로 나오는 probabilty값을 사용한다면 , Contrastive loss의 Ls(similar class)와 Ld(dissimilar class)는 metric learning loss로써 network에서 결과로 나오는 포인트의 위치관계를 담고있다.

-> 이것이 cross-entropy를 metric learning 으로 사용하지 않는 이유인데, 즉 , CE는 이미지에서 뽑은 feature가 비교하고자 하는 이미지에서 가까운지,먼지 상관없이 뽑는법을 배우게된다.

 

실제 Le Cunn의 식 

Ls,Ld의 해당하는 부분의 식을 그래프로 그려보면 바로 학습을 진행할경우 같은 class는 0에 가깝게, 다른 class는 m(margin)보다 크게 보내는 Loss function임을 알 수 있다. 다만 Le cunn이 Ld에 1/D같은식을 안쓴이유를

Equalibrium이라는 intuition을 얘기 하는데, 이는 GAN에서 얘기하는것과 비슷하다.

Loss를 무작정 극단으로 치우치게 해서 학습(class가 다른 것들을 무한이 멀리보냄)하게 되면, 이미지상 비슷하지만  다른class 또한 무한히 멀리 보내게되고 그 반대도 학습한다. 결국 학습을 끝냈을때(Equilibrium에 도달하기 힘들어 학습하는데 오래걸리기도 함) generalization 능력을 잃게된다.

 

아래는 블로그 원작자의 원문 설명은 다음과 같다.  

  • If we were to use the same “margin” concept for similar points, we won’t force the similar points to be as close to each other as possible — thus a lot of them would be located near the margin and could be easily pushed out of it, which would make the training unstable and difficult to converge.
  • If we were to use the {1 / Dw} term for the dissimilar points, then we would continue pushing away white dots for eternity (in theory) or for just a very long time, even when the results are already separable and usable for a nearest-neighbour classification. This would also make it difficult to reach the Equilibrium point, is simply unnecessary and may push dissimilar points TOO far away, which may worsen the generalization performance of the model.

 

모델의 개략적인 모습은 다음 사진과 같다.

아래는 MNIST의 Contrastive Loss를 적용시켰을때 feature map의 모습

 

출처 : medium.com/@maksym.bekuzarov/losses-explained-contrastive-loss-f8f57fe32246

사진, 식 출처 : arxiv.org/abs/1704.08063

 

Losses explained: Contrastive Loss

This is a series of posts explaining different loss functions used for the task of Face Recognition/Face Verification.

medium.com

+나의 생각

+ Recent posts