In Defense of the Triplet Loss for Person Re-Identification
arXiv:1703.07737
설명이 매우 간결하고 정확하다. 똑똑한 사람들이 쓴 티가 나는 논문. 별 다섯이다.
마지막에 트레이닝 팁도 일품
2017
Alexander Hermans*, Lucas Beyer* and Bastian Leibe
Visual Computing Institute
RWTH Aachen University
last@vision.rwth-aachen.org
∗Equal contribution. Ordering determined by a last minute coin flip.
목차
1. Introduction
- One prominent example in the recent literature is FaceNet : triplet loss
- Barnes-Hut t-SNE[1]
- In this paper they show that, contrary to current opinion, a plain CNN with a triplet loss can outperform current state-of-the-art approaches on both the Market-1501 [2] and MARS[3] datasets.
- 보통은 triple loss의 결과가 좋지 않음.
- hard triple을 찾기가 힘들다. 못찾으면 training will quickly stagnate.
- too hard → training unstable
- They place two previously proposed variants [4][5]
- They also show that a margin-less formulation performs slightly better, while removing one hyper-parameter.
- train a plain feed-foward CNN
- train from scratch
- Our networks using pretrained weights obtain the best results, but our far smaller architecture obtains respectable scores, providing a viable alternative for applications where person ReID needs to be performed on resource-constrained hardware, such as embedded devices.
contribution
- hard triplet을 찾을 필요 없게 한 점
- special layer없이 CNN만으로 좋은 결과를 얻은 점(물론 pretrained net을 쓰긴 했지만 scratch로부터 훈련해도 괜찮았다)
2. Learning Metric Embeddings, the Triplet Loss, and the Importance of Mining
- 이것저것 제거하는데 마음에 든다.
- For clarity we use the shortcut notation \(D_{i,j} = D(f_\theta(x_i), f_\theta(x_j))\), where we omit the indirect dependence of \(D_{i,j}\) on the parameters \(θ\). As is common practice, all loss-terms are divided by the number of summands in a batch; we omit this term in the following equations for conciseness.
- LMNN나왔다가, 그걸 보완하려고 triplet loss나왔다.$$ \mathcal{L}_{\text{tri}}(\theta) = \sum _{\substack{a,p,n\\ y_a = y_p \ne y_n}} [ m + D_{a,p} - D_{a,n} ] _+ $$ a와 p는 같은 클래스에 속하고, a와 n은 다른 클래스에 속하되, margin이 m이상인 것들만.
- triplet loss의 단점
- 데이터의 수가 늘어날수록 조합이 cubically 늘어남
- \(f_\theta\)는 상대적으로 빨리 학습이 진행되어서 대부분의 triplets를 uninformative하게 만듦. 따라서 hard case를 찾는 일이 crucial하게 된다. (hard negatives, hard positives를 찾아야 한다)
- 또 너무 hard한 케이스만 찾다보면 outlier를 골라내서 학습하게 된다. (normal case에서 성능이 오히려 떨어진다)
- 결국, moderate negatives[6]/positives[7]를 찾아야 한다.
- B triplets(3B images)가 있으면 \(6B^2-4B\)개의 조합이 가능하다고 써 있는데...?
- \(\binom{2B}{2}B + \binom{B}{2}2B = 3B^3 - 2B^2\) 아니고?
- 차라리 \(6B^3 - 4B^2 = 2B(2B-1)B + B(B-1)2B\)라면 그럴듯한데...
Batch Hard
$$\mathcal{L}_{BH}(\theta; X) = \overbrace{ \sum_{i=1}^P \sum_{a=1}^K }^{\text{all anchors}}[ m + \overbrace{ \max_{p=1\dots K}D(f_θ(x_a^i), f_θ(x^i_p)) }^{\text{ hardest positive}} - \overbrace{
\min_{\substack{ j=1\dots P \\ n = 1\dots K \\ j \ne i }} D(f_θ(x_a^i), f_θ(x_n^j))
}^{ \text{ hardest negative} } ]_+ $$
- 임의로 P개의 class선택하고 class마다 K개의 anchor를 선택한 후, 가장 어려운 positive/negative를 골라서 loss를 만든다.
- 이렇게 batch 안에서만 하는거 FaceNet에서 이미 언급되지 않았나???
- within the batch이므로 moderate triplets랜다. 붙이면 다 이름이다.
- All batch (\(\mathcal{L}_{BA}\))랑 반대.
- What are they saying?
Both the max and min functions are continuous and differentiable almost everywhere, meaning they can be used in a model trained by stochastic (sub-)gradient descent without concern. In fact, they are already widely available in popular deep-learning frameworks for the implementation of max-pooling and the ReLU [8] non-linearity.
- Lifted Embedding loss[9]와 비슷하다고 함. $$\mathcal{L}_L (θ; X) = \sum_{(a,p)\in X} [ D_{a,p} + \log\sum_{ \substack{n\in X \\ n\ne a, n \ne p} } (e^{ m- D_{a,n} } + e^{ m-D_{p,n} })]_+ $$하나도 안중요하지만 그냥 심심해서 써봤다.
distance measure
- 그냥 euclidean (norm)
- related works대부분은 squared euclidean을 쓴다고 하네?
soft margin
- hinge function \([ m + \bullet ]_+ \)은 ‘이미 옳은’ 분류를 다시 고치려들지 않게 만드는데, 분류가 이미 옳더라도 같은 클래스의 샘플들을 최대한 당기면 더 좋은 결과를 얻을 수 있다. 따라서 hinge function을 아래의 softplus function으로 대체할 수 있다. $$s(x) = \ln(1+\exp(x))$$hinge function과 비슷하나 hard cut-off가 없다.
- log1p함수(numerically stable, common) 이용.
3. Experiments
3.1. Datasets
- Market-1501과 MARS사용
- MARS는 Market-1501과 달리
- bounding box가 없다
- tracklet으로 구성. 기본적으로 multi-query setup. (연속장면의 한 컷을 tracklet이라고 하는것 같다). ‘feature embeddings are pooled across a tracklet’이라고 함. (근접한 컷 정보도 이용한다는 말 같음)
- evaluation은 mAP(mean average precision)와 CMC(cumulative matching curve)
- Z.Zhong[10]이 제공하는 코드로 평가
3.2. Training
- theano
- 코드는 공개 예정 [11]
- Adam with \(\epsilon = 10^{-3}, \beta_1= 0.9, \beta_2 = 0.999 \)
- decaying training schedule 썼다는데 learning rate decay말하는건가?$$\epsilon (t)
\begin{cases}
\epsilon_0 & \text{if}\ t \le t_0 \\
\epsilon_0 0.001^{\frac{t - t_0}{t_1 - t_0}} & \text{if}\ t_0 \le t \le t_1
\end{cases} \text{with}\ \epsilon_0 = 10^{-3}, t_0 = 15000, t_1= 25000$$ stopping training when reaching \(t_1\).
When entering the decay schedule at \(t_0\), set \(\beta_1 = 0.5\) because it’s common [12] 뭐가 커먼하다는거여
3.3. Network architectures
TriNet
- K.He[13]가 제공하는 ResNet-50
- 마지막 layer버리고, 2개 fully connected layers.(1024-[Batch Normalization bn]-ReLU-128)
- batch size=72 (18 persons, 4 images each)
- \(\epsilon_0 = 10^{-3}\)로 하면 너무 크다. 몇 iter뒤에 발산. \(3\cdot 10^{-4}\)줌.
LuNet
- training from scratch
- ResNet-v2 base, (but) leaky ReLU
- multiple \(3 \times 3\) max-poolings with stride 2 instead of strided convolutions
- omits the final avg-pooling of feature-maps
- much lighter(5M params) then TriNet(25.74M params)
- batch size=128 ( 32 persons with 4 images each)
- 자세한건 부록하고 코드를 봐라 해놓고 코드를 안보여주면 어케하냐
3.4. Triplet Loss
- 150명을 임의로 validation set. 나머지 475명으로 학습.
- 1/2로 resize한 이미지로 학습한 ‘LuNet’으로 실험. (input = H \(\times\) W = 128 \(\times\) 64)
- augmentation전혀 안함
- 알려진대로 vanilla triplet은 poor하다.[14][15][16]
- OHM(offline hard mining) 더해지면 훅간다.[17][18] 그리고 찾는데 시간도 엄청 걸려서 별로임.
- batch hard has almost no additional runtime cost and outperforms ‘batch all’.
- batch단위로 평균내는 과정에서 loss사라지는것 때문에, loss \(\ne 0\)인 것들 끼리만 평균내고 학습시켜보았더니 모든 setting에서 우수했음.
- boosting이랑 비슷하게 이해할수도 있다
- soft margin + batch hard 가 최고
3.5. Performance on Market-1501 and MARS
- PK images만든다. K부족하면 그냥 중복 씀.
- pretrained network쓸 때는 mean pixel value used during the original network training on ImageNet을 뺐다.(LuNet은 그냥 씀)
- 학습할 때 random crop. (9/8만큼 늘리고, 원 사이즈만한 이미지를 랜덤하게 잘라냄)
- test-time augmentation
- 테스트 이미지 horizontal flip(좌우 뒤집기)하고 다섯번 crop(네 귀 + 중앙)도 해서 각 embedding들(총10개)의 평균을 냄
- mAP의 3%정도를 높인다
- I : person의 id를 맞추는 방식
V : 두 사람이 같은지 맞추는 방식
E : embedding을 뽑는 방식- 보통 I 보다 E 가 더 우수한 성능을 보인다
- Re-ranking[19]
3.5.1. Market-1501 + 500k Distractors
- Market-1501이 제공하는 500k distracters
- Pretraining된 모델이 확실히 좋은 성능을 보임
- distractors가 섞여도 모든 모델이 어느정도 성능을 냄(학습결과가 좋다는 뜻)
3.6. To pretrain or not to Pretrain?
- Pretrained net이 좋기는 한데 사이즈등 제약이 있어서 porting이 어렵다
- Pretrained net에는 ‘intrinsic scale’이 있다고들 한다.
- 실제로 해보니 pretrained net(여기서는 TriNet)에서는 성능저하가 확연했으나 LuNet에서는 그렇지 않았다.(논문의 표3)
4. Discussion
Notes on Network Training
- embedding norm은 필요 없다.
- 차원을 겨우 하나 줄인다(합이 일정하므로 마지막 dimension이 redundant)
- embedding이 explode하거나 collapse할 때 그것을 관찰하기 어렵게 한다.
- loss가 줄지 않는다고 학습이 되지 않는것이 아니다
- 어려운 케이스 몇몇이 loss를 유지하게 만들 수도 있다. 일일이 관찰하는 수밖에 없다.
- 훈련과정을 관찰해보면, 처음엔 모든 embedding들이 하나로 모이는 듯 하다가, 각자 자신의 클러스터로 향해 간다. 서로 지나쳐가는 것처럼 보인다. 한번 지나쳐 간 뒤에는 각 클러스터들은 점점 멀리 퍼진다. Collapsing of training은, margin이 너무 크고 초기 spreading이 작을 때 관찰할 수 있는데, embedding들이 서로 지나쳐가려는 지점에서 멈춰버린다.
References
- ↑ L. Van Der Maaten. Accelerating t-SNE using Tree-Based Algorithms. JMLR, 15(1):3221–3245, 2014.
- ↑ L. Zheng, L. Shen, L. Tian, S. Wang, J. Wang, and Q. Tian. Scalable Person Re-Identification: A Benchmark. In ICCV, 2015.
- ↑ L. Zheng, Z. Bie, Y. Sun, J. Wang, C. Su, S. Wang, and Q. Tian. MARS: A Video Benchmark for Large-Scale Per- son Re-Identification. In ECCV, 2016.
- ↑ S. Ding, L. Lin, G. Wang, and H. Chao. Deep feature learning with relative distance comparison for person re-identification. Pattern Recognition, 48(10):2993–3003, 2015.
- ↑ H. O. Song, Y. Xiang, S. Jegelka, and S. Savarese. Deep Metric Learning via Lifted Structured Feature Embedding. In CVPR, 2016.
- ↑ F. Schroff, D. Kalenichenko, and J. Philbin. FaceNet: A Unified Embedding for Face Recognition and Clustering. In CVPR, 2015.
- ↑ H.Shi,Y.Yang,X.Zhu,S.Liao,Z.Lei,W.Zheng,andS.Z. Li. Embedding Deep Metric for Person Re-identification: A Study Against Large Variations. In ECCV, 2016.
- ↑ X. Glorot, A. Bordes, and Y. Bengio. Deep Sparse Rectifier Neural Networks. In AISTATS, 2011.
- ↑ H. O. Song, Y. Xiang, S. Jegelka, and S. Savarese. Deep Metric Learning via Lifted Structured Feature Embedding. In CVPR, 2016.
- ↑ Z. Zhong, L. Zheng, D. Cao, and S. Li. Re-ranking Person Re-identification with k-reciprocal Encoding. CVPR, 2017.
- ↑ https://github.com/VisualComputingInstitute/triplet-reid
The publication of all code is pending acceptance of the paper. Since we've been asked several times, this work was a submission to ICCV'17 and you can have look at the timeline, so if all goes well, code will come online sometime this summer.
- ↑ J.L.Ba,J.R.Kiros,andG.E.Hinton.LayerNormalization. arXiv preprint arXiv:1607.06450, 2016.
- ↑ K.He,X.Zhang,S.Ren,andJ.Sun.DeepResidualLearning for Image Recognition. In CVPR, 2016.
- ↑ M. Geng, Y. Wang, T. Xiang, and Y. Tian. Deep Transfer Learning for Person Re-identification. arXiv preprint arXiv:1611.05244, 2016.
- ↑ S. Ding, L. Lin, G. Wang, and H. Chao. Deep feature learning with relative distance comparison for person re-identification. Pattern Recognition, 48(10):2993–3003, 2015.
- ↑ W. Chen, X. Chen, J. Zhang, and K. Huang. A Multi-task Deep Network for Person Re-identification. arXiv preprint arXiv:1607.05369, 2016.
- ↑ F. Schroff, D. Kalenichenko, and J. Philbin. FaceNet: A Unified Embedding for Face Recognition and Clustering. In CVPR, 2015.
- ↑ H.Shi,Y.Yang,X.Zhu,S.Liao,Z.Lei,W.Zheng,andS.Z. Li. Embedding Deep Metric for Person Re-identification: A Study Against Large Variations. In ECCV, 2016.
- ↑ Z. Zhong, L. Zheng, D. Cao, and S. Li. Re-ranking Person Re-identification with k-reciprocal Encoding. CVPR, 2017.
Supplementary Material
A. Test-time Augmentation
- 원본을 리사이즈 해서 넣는 것이 가장 결과가 좋지 않다.
- 원본을 crop하고 + 좌우반전(horizontal flip)해서만 넣어도 big boost
- 5 crop \(\times\) 2 filp 다 하면 mAP 약 3% 향상(65→69, 55→60, 56→58. each for TriNet, LuNet, IDE(R) Ours. 표4)
B. Hard Positives, Hard Negatives and Outliers
- Market-1501에 outlier들도 좀 있고(스케일이 아예 다르거나 여러 사람이 동시에 등장하는 경우 있음), 아예 annotation이 잘못된 경우도 있다.
C. Experiments with Distractors
D. LuNet’s Architecture
- net initialization
- 초기화보다 Batch Normalization이 중요하다
- 0.3 leaky ReLU
E. Full t-SNE Visualization
F. Typical Training Logs
자세한 범례는 논문 참조

15000 updates부터 decay learning의 효과.
위 학습시의 embedding변화 :
loss가 정체된 듯한 구간에서도 embedding은 계속 변한다.(좌측 아래가 embedding간 거리)
embedding간 거리가 급격하게 감소하다가 다시 증가하는 것(화살표모양) 관찰 가능
TriNet등 더 좋은 net에서는 이 정체구간이 훨씬 짧다(이 위 그림에서 관찰가능). 이 그림은 굉장히 단순한 net으로 실험해본 것. net이 더 단순해지거나 margin이 커지면 아래 그림처럼 정체구간을 통과하지 못하고 학습에 실패하게 된다.
lunet에 OHM(offline hard mining)적용한것. 아래는 이때의 loss등을 그린 것. 앞서 나온 학습성공사례와 모양이 많이 다르다.
9/29/17 최근에 면접을 두어군데 봤는데 다 triplet loss아냐고 물어보더라. 이게 나온지가 언젠데 어떤 계기로 요즘 다시 뜨는지는 모르겠다. 어디 또 다른 논문이 났나. 어쨌든 문제는, 뭐 또 다른 심오한게 있는지 내 대답을 다 시큰둥하게 여기는것 같더니 역시나 쓴잔을 벌컥벌컥 먹여주시더라는.