https://blog.csdn.net/u013082989/article/details/83537370
一、 Triplet loss
1、介紹
Triplet loss
最初是在 FaceNet: A Unified Embedding for Face Recognition and Clustering 論文中提出的,可以學到較好的人臉的embedding
- 為什么不適用
softmax
函數呢,softmax
最終的類別數是確定的,而Triplet loss
學到的是一個好的embedding
,相似的圖像在embedding
空間里是相近的,可以判斷是否是同一個人臉。
2、原理
- 輸入是一個三元組
<a, p, n>
a: anchor
p: positive
, 與a
是同一類別的樣本n: negative
, 與a
是不同類別的樣本
- 公式是:
- 所以最終的優化目標是拉近
a, p
的距離, 拉遠a, n
的距離 easy triplets
: L=0L = 0L=0 即 d(a,p)+margin<d(a,n)d(a, p) +margin < d(a, n)d(a,p)+margin<d(a,n),這種情況不需要優化,天然a, p
的距離很近,a, n
的距離遠hard triplets
: d(a,n)<d(a,p)d(a, n) < d(a, p)d(a,n)<d(a,p), 即a, p
的距離遠semi-hard triplets
: d(a,p)<d(a,n)<d(a,p)+margind(a, p) < d(a, n) < d(a, p) + margind(a,p)<d(a,n)<d(a,p)+margin, 即a, n
的距離靠的很近,但是有一個margin
- 所以最終的優化目標是拉近
FaceNet
中是隨機選取semi-hard triplets
進行訓練的, (也可以選擇hard triplets
或者兩者一起進行訓練)
3、訓練方法
3.1 offline
- 訓練集所有數據經過計算得到對應的
embeddings
, 可以得到 很多<i, j, k>
的三元組,然后再計算triplet loss
- 效率不高,因為需要過一遍所有的數據得到三元組,然后訓練反向更新網絡
3.2 online
- 從訓練集中抽取
B
個樣本,然后計算B
個embeddings
,可以產生 B3B^3B3 個triplets
(當然其中有不合法的,因為需要的是<a, p, n>
)
- 實際使用中采用此方法,又分為兩種策略 (是在一篇行人重識別的論文中提到的 In Defense of the Triplet Loss for Person Re-Identification),假設 B=PKB = PKB=PK, 其中
P
個身份的人,每個身份的人K
張圖片(一般K
取4
)Batch All
: 計算batch_size
中所有valid
的的hard triplet
和semi-hard triplet
, 然后取平均得到Loss
- 注意因為很多
easy triplets
的情況,所以平均會導致Loss
很小,所以是對所有 valid 的所有求平均 (下面代碼中會介紹) - 可以產生 PK(K−1)(PK−K)PK(K-1)(PK-K)PK(K−1)(PK−K)個
triplets
PK
個anchor
K-1
個positive
PK-K
個negative
- 注意因為很多
Batch Hard
: 對於每一個anchor
, 選擇距離最大的d(a, p)
和 距離最大的d(a, n)
- 所以公有 PKPKPK 個 三元組
triplets
- 所以公有 PKPKPK 個 三元組
二、 Tensorflow 中的實現
實際上這個損失函數不管K和L的差距有多大https://www.zhihu.com/question/382802283