-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path13-siamese-networks.html
636 lines (413 loc) · 18.9 KB
/
13-siamese-networks.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
<!DOCTYPE html>
<html>
<head>
<title>13. Siamese Networks [Andrei Bursuc]</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" href="./assets/katex.min.css">
<link rel="stylesheet" type="text/css" href="./assets/slides.css">
<link rel="stylesheet" type="text/css" href="./assets/grid.css">
</head>
<body>
<textarea id="source">
layout: true
.center.footer[Marc LELARGE and Andrei BURSUC | Deep Learning Do It Yourself | 13. Siamese Networks]
---
class: center, middle, title-slide
count: false
# 13. Siamese Networks and Representation Learning
<br/>
<br/>
.bold[Andrei Bursuc ]
<br/>
url: https://dataflowr.github.io/website/
<!-- url: https://abursuc.github.io//slides/polytechnique/03_cnns_siamese.html -->
.citation[
With slides from F. Fleuret, O. Grisel, E. Oyallon, G. Louppe, Y. Avrithis ...]
---
# Siamese networks
.center.width-60[]
- **Recognition:** given a face, classify among K possible persons
- **Verification:** verify that two faces belongs to the same person
A verification system can be implemented as a similarity measure. If it's really good, useful for recognition.
---
class: middle, center
.big[Training a classifier with so many classes and so few samples per classes is challenging.]
.hidden.big[In addition, for such use-cases, new classes can appear on the fly anytime.]
---
count: false
class: middle, center
.big[Training a classifier with so many classes and so few samples per classes is challenging.]
.big[In addition, for such use-cases, new classes can appear on the fly anytime.]
---
class: middle, center
.big[Instead of training a network to do classification, we can train it to compute useful features from images, allowing us to measure similarities/dissimilarities between images.]
---
# Siamese architecture
.center.width-60[]
- an input sample is a _pair_ $( \mathbf{x}\_i, \mathbf{x}\_j)$
.citation[ S. Chopra et al.,Learning a similarity metric discriminatively, with application to face verification, CVPR 2005]
---
# Siamese architecture
.center.width-60[]
- an input sample is a _pair_ $( \mathbf{x}\_i, \mathbf{x}\_j)$
- both $\mathbf{x}\_i$, $\mathbf{x}\_j$ go through the _same_ function $f$ with _shared_ parameters $\theta$
.citation[ S. Chopra et al.,Learning a similarity metric discriminatively, with application to face verification, CVPR 2005]
---
# Siamese architecture
.center.width-60[]
- an input sample is a _pair_ $( \mathbf{x}\_i, \mathbf{x}\_j)$
- both $\mathbf{x}\_i$, $\mathbf{x}\_j$ go through the _same_ function $f$ with _shared_ parameters $\theta$
- loss $\ell\_{ij}$ is measured on output pair $( \mathbf{y}\_i, \mathbf{y}\_j)$ and target $t\_{ij}$
.citation[ S. Chopra et al.,Learning a similarity metric discriminatively, with application to face verification, CVPR 2005]
---
# Contrastive loss
.center.width-60[]
- input samples $\mathbf{x}\_i$, output vectors $\mathbf{y}\_i= f(\mathbf{x}\_i; \theta)$, target variables $t\_{ij}=\mathbb{1}[\text{sim}(\mathbf{x}\_i, \mathbf{x}\_j)]$
- _contrastive loss_ is a function of distance $\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert$ only
$$\ell\_{ij} = L((\mathbf{y}\_i,\mathbf{y}\_j), t\_{ij} ) = \ell (\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert, t\_{ij})$$
.citation[ R. Hadsell et al., Dimensionality reduction by learning an invariant mapping, CVPR 2006]
---
# Contrastive loss
.center.width-60[]
- input samples $\mathbf{x}\_i$, output vectors $\mathbf{y}\_i= f(\mathbf{x}\_i; \theta)$, target variables $t\_{ij}=\mathbb{1}[\text{sim}(\mathbf{x}\_i, \mathbf{x}\_j)]$
- _contrastive loss_ is a function of distance $\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert$ only
$$\ell\_{ij} = L((\mathbf{y}\_i,\mathbf{y}\_j), t\_{ij} ) = \ell (\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert, t\_{ij})$$
- _similar_ samples are _attracted_
$$\ell(x,t)=\textcolor{red}{t\ell^{+}} + (1-t)\ell^{-}(x) = \textcolor{red}{t x^2} + (1-t)[m-x]^2\_+$$
.citation[ R. Hadsell et al., Dimensionality reduction by learning an invariant mapping, CVPR 2006]
---
# Contrastive loss
.center.width-60[]
- input samples $\mathbf{x}\_i$, output vectors $\mathbf{y}\_i= f(\mathbf{x}\_i; \theta)$, target variables $t\_{ij}=\mathbb{1}[\text{sim}(\mathbf{x}\_i, \mathbf{x}\_j)]$
- _contrastive loss_ is a function of distance $\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert$ only
$$\ell\_{ij} = L((\mathbf{y}\_i,\mathbf{y}\_j), t\_{ij} ) = \ell (\Vert \mathbf{y}\_i - \mathbf{y}\_j \Vert, t\_{ij})$$
- _dissimilar_ samples are _repelled_ if closer than margin $m$
$$\ell(x,t)=t\ell^{+} + (1-t)\textcolor{red}{\ell^{-}(x)} = t x^2 + (1-t)\textcolor{red}{[m-x]^2\_+}$$
.citation[ R. Hadsell et al., Dimensionality reduction by learning an invariant mapping, CVPR 2006]
---
# Training siamese networks
## Data collection and loading
- sample positive pairs $( \mathbf{x}\_i, \mathbf{x}\_j)$, with samples coming from the same class
- sample negative pairs $( \mathbf{x}\_i, \mathbf{x}\_j)$, with samples of different classes
- combine pairs of samples in larger mini-batches
- __it's highly important to properly tune mini-batches__: balance positives and negatives, discard easy negatives and positives and focus on more difficult ones.
.hidden[
## Learning
- pass all images through the two networks with shared parameters (in fact the same network)
- backpropagate through the two networks and sum gradients from the two samples
]
---
count: false
# Training siamese networks
## Data collection and loading
- sample positive pairs $( \mathbf{x}\_i, \mathbf{x}\_j)$, with samples coming from the same class
- sample negative pairs $( \mathbf{x}\_i, \mathbf{x}\_j)$, with samples of different classes
- combine pairs of samples in larger mini-batches
- __it's highly important to properly tune mini-batches__: balance positives and negatives, discard easy negatives and positives and focus on more difficult ones.
## Learning
- pass all images through the two networks with shared parameters (in fact the same network)
- backpropagate through the two networks and sum gradients from the two samples
---
# Triplet architecture
.grid[
.kol-6-12[
.center.width-100[]
]
.kol-6-12[
- an input sample is a _triple_ $(\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-)$
]
]
.citation[ Wang et al., Learning fine-grained image similarity with deep ranking, CVPR 2014]
---
# Triplet architecture
.grid[
.kol-6-12[
.center.width-100[]
]
.kol-6-12[
- an input sample is a _triple_ $(\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-)$
- $\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-$ go through the _same_ function $f$ with _shared_ parameters $\theta$
]
]
.citation[ Wang et al., Learning fine-grained image similarity with deep ranking, CVPR 2014]
---
# Triplet architecture
.grid[
.kol-6-12[
.center.width-100[]
]
.kol-6-12[
- an input sample is a _triple_ $(\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-)$
- $\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-$ go through the _same_ function $f$ with _shared_ parameters $\theta$
- loss $\ell\_i$ is measured on output triple $(\mathbf{y}\_i, \mathbf{y}\_i^+, \mathbf{y}\_i^-)$
]
]
.citation[ Wang et al., Learning fine-grained image similarity with deep ranking, CVPR 2014]
---
# Triplet loss
- input _anchor_ $\mathbf{x}\_i$, output vector $\mathbf{y}\_i = f(\mathbf{x}\_i; \theta)$
- positive $\mathbf{y}\_i^+ = f(\mathbf{x}\_i^+; \theta)$, negative $\mathbf{y}\_i^- = f(\mathbf{x}\_i^-; \theta)$
- _triplet loss_ is a function of distances $\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert$, $\Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert$ only
$$\ell\_i = L(\mathbf{y}\_i, \mathbf{y}\_i^+, \mathbf{y}\_i^-) =\ell(\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert, \Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert)$$
$$\ell(x^+, x^-) = [m + (x^+)^2 - (x^-)^2]\_+$$
so distance $\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert$ should be less than $\Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert$ by _margin_ $m$
.citation[ Wang et al., Learning fine-grained image similarity with deep ranking, CVPR 2014]
---
# Triplet loss
- input _anchor_ $\mathbf{x}\_i$, output vector $\mathbf{y}\_i = f(\mathbf{x}\_i; \theta)$
- positive $\mathbf{y}\_i^+ = f(\mathbf{x}\_i^+; \theta)$, negative $\mathbf{y}\_i^- = f(\mathbf{x}\_i^-; \theta)$
- _triplet loss_ is a function of distances $\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert$, $\Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert$ only
$$\ell\_i = L(\mathbf{y}\_i, \mathbf{y}\_i^+, \mathbf{y}\_i^-) =\ell(\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert, \Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert)$$
$$\ell(x^+, x^-) = [m + (x^+)^2 - (x^-)^2]\_+$$
so distance $\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert$ should be less than $\Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert$ by _margin_ $m$
- by taking _two pairs_ $(\mathbf{x}\_i, \mathbf{x}\_i^+)$ and $(\mathbf{x}\_i, \mathbf{x}\_i^-)$ at a time with targets $1$, $0$ respectively, the _contrastive loss_ can be writen similarly
$$\ell(x^+, x^-) = (x^+)^2 + [m-x^-]^2\_+$$
so distance $\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert$ should be small and $\Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert$ larger than $m$
.citation[ Wang et al., Learning fine-grained image similarity with deep ranking, CVPR 2014]
---
count: false
# Training with the triplet loss
$$\ell\_i = L(\mathbf{y}\_i, \mathbf{y}\_i^+, \mathbf{y}\_i^-) =\ell(\Vert \mathbf{y}\_i - \mathbf{y}\_i^+ \Vert, \Vert \mathbf{y}\_i - \mathbf{y}\_i^- \Vert)$$
- sample a mini-batch of triplets$(\mathbf{x}\_i, \mathbf{x}\_i^+, \mathbf{x}\_i^-)$
- forward pass on all $3$ networks
- compute loss over all samples and sum gradients for updating weights
---
# Siamese networks
.grid[
.kol-6-12[
```
class SiameseNet(nn.Module):
def __init__(self, embedding_net):
super(SiameseNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2):
output1 = self.embedding_net(x1)
output2 = self.embedding_net(x2)
return output1, output2
def get_embedding(self, x):
return self.embedding_net(x)
```
]
.kol-6-12[
```
class TripletNet(nn.Module):
def __init__(self, embedding_net):
super(TripletNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2, x3):
output1 = self.embedding_net(x1)
output2 = self.embedding_net(x2)
output3 = self.embedding_net(x3)
return output1, output2, output3
def get_embedding(self, x):
return self.embedding_net(x)
```
]
]
---
count:false
# Siamese networks
.grid[
.kol-6-12[
```
class SiameseNet(nn.Module):
def __init__(self, embedding_net):
super(SiameseNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2):
* output1 = self.embedding_net(x1)
* output2 = self.embedding_net(x2)
return output1, output2
def get_embedding(self, x):
return self.embedding_net(x)
```
]
.kol-6-12[
```
class TripletNet(nn.Module):
def __init__(self, embedding_net):
super(TripletNet, self).__init__()
self.embedding_net = embedding_net
def forward(self, x1, x2, x3):
* output1 = self.embedding_net(x1)
* output2 = self.embedding_net(x2)
* output3 = self.embedding_net(x3)
return output1, output2, output3
def get_embedding(self, x):
return self.embedding_net(x)
```
]
]
---
# Hard negative sampling
After a few epochs, If $(\mathbf{x}\_i, \mathbf{x}\_i^{+}, \mathbf{x}\_i^{-})$ are chosen randomly, it will be easy to satisfy the inequality in the loss.
--
Gradients in one batch quickly become almost $0$ except for **hard cases**.
Random sampling is inefficient to find these hard cases
--
count: false
- **Hard triplet sampling:** sample $\mathbf{x}\_i^{-}$ such that:
$$||\mathbf{y} - \mathbf{y}^{+}|| > ||\mathbf{y} - \mathbf{y}^{-}|| + m$$
- **Semi Hard triplet sampling:** sample $\mathbf{x}\_i^{-}$ such that:
$$||\mathbf{y} - \mathbf{y}^{+}|| > ||\mathbf{y} - \mathbf{y}^{-}||$$
---
class: middle, center
# Applications
---
# Face recognition
.center.width-30[]
- A threshold is computed on test set to decide which faces are the same
- Best model achieves 99.6% verification accuracy on Labeled Faces in the Wild dataset
- Works well even with non-camera facing faces
.citation[F. Schroff et al., Facenet: A unified embedding for face recognition and clustering, CVPR 2015 ]
---
# Deep image retrieval
.center.width-70[]
.citation[A. Gordo et al., Deep Image Retrieval: Learning Global Representations for Image Search, ECCV 2016 ]
- query $\mathbf{x}\_i$, relevant $\mathbf{x}\_i^+$ (same building), irrelevant $\mathbf{x}\_i^-$ (other building)
---
count: false
# Deep image retrieval
.center.width-70[]
.citation[A. Gordo et al., Deep Image Retrieval: Learning Global Representations for Image Search, ECCV 2016 ]
- query $\mathbf{x}\_i$, relevant $\mathbf{x}\_i^+$ (same building), irrelevant $\mathbf{x}\_i^-$ (other building)
---
count: false
# Deep image retrieval
.center.width-70[]
.citation[A. Gordo et al., Deep Image Retrieval: Learning Global Representations for Image Search, ECCV 2016 ]
- query $\mathbf{x}\_i$, relevant $\mathbf{x}\_i^+$ (same building), irrelevant $\mathbf{x}\_i^-$ (other building)
- triplet loss is evaluated on output $(\mathbf{y}\_i, \mathbf{y}\_i^+, \mathbf{y}\_i^-)$
---
# Patch matching
.center.width-45[]
---
# Patch matching
.center.width-70[]
.credit[Figure credit: A. Vedaldi]
---
# Patch matching
.center.width-60[]
.credit[Figure credit: A. Vedaldi]
---
# Image reconstruction
.center.width-70[]
.caption[Structure from motion]
.citation[F. Radenovic et al., CNN Image Retrieval Learns From BoW: Unsupervised Fine-Tuning with Hard Examples, ECCV 2016 <br/>
Schonberger et al., From Single Image Query to Detailed 3D Reconstruction, CVPR 2015.]
---
# Person re-identification
.grid[
.kol-6-12[
.center.width-70[]
]
.kol-6-12[
]
]
.citation[J. Almazan et al., Re-ID Done Right: towards Good Practices for Person re-Identification, arXiv 2018]
---
count: false
# Person re-identification
.grid[
.kol-6-12[
.center.width-70[]
]
.kol-6-12[
.center.width-70[]
]
]
.citation[J. Almazan et al., Re-ID Done Right: towards Good Practices for Person re-Identification, arXiv 2018]
---
class: middle, center
.big[Going beyond pairs and triplets ...]
---
# N-pair loss
.center.width-70[]
.caption[Deep metric learning with (left) triplet loss and (right) $(N+1)$-tuplet loss. <br/>$(N+1)$-tuplet loss pushes $N-1$ negative examples all at once.]
- generalize *triplet-loss* with **N-pair loss**
- sample pairs of similar examples and use as negative all the other samples in the mini-batch
.citation[K. Sohn, Improved Deep Metric Learning with Multi-class N-pair Loss Objective, NeurIPS 2016]
---
# Histogram loss
.center.width-70[]
- for a mini-batch compute all pairwise positive similarities and negative similarities
- compile similarities into distributions (differentiable approximations of distributions)
- the loss aims to repell the two distributions
.citation[E. Ustinova et al., Learning Deep Embeddings with Histogram Loss, NeurIPS 2016]
---
class: middle, center
## Few classes, few labels
---
# Prototypical networks
Learns to extract class prototype vectors:
- class prototype vector = mean feature vector of training examples
- classify test example to the class with the closest prototype ($L\_2$ distance)
- prototype vectors are similar to classification weights of networks
.grid[
.kol-6-12[
Prototype vector of $k$-th class:
$$c\_k=\frac{1}{|S\_k|} \sum\_{(x\_i, y\_i) \in S\_k} f\_{\theta}(x\_i)$$
Classification for example $x$:
$$p\_{\theta}(y=k|x) = \frac{\exp(-d(f\_{\theta}(x), c\_k))}{\sum\_{k'}\exp(-d(f\_{\theta}(x), c\_{k'}))}$$
]
.kol-6-12[
.center.width-70[]
]
]
.citation[J Snell et al., Prototypical Networks for Few-shot Learning, NeurIPS 2017]
---
# Take-aways
- .big[A specific type of architectures suitable for representation learning]
- .big[In case of many classes and class imbalance, siamese networks might be better, while for standard settings use classification]
- .big[Modern methods leverage siamese networks for unsupervised learning, where the network must recognize a perturbed sample in a large pool of negatives.]
---
class: end-slide, center
count: false
The end.
</textarea>
<script src="./assets/remark-latest.min.js"></script>
<script src="./assets/auto-render.min.js"></script>
<script src="./assets/katex.min.js"></script>
<script type="text/javascript">
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// var options = {sourceUrl: getParameterByName("p"),
// highlightLanguage: "python",
// // highlightStyle: "tomorrow",
// // highlightStyle: "default",
// highlightStyle: "github",
// // highlightStyle: "googlecode",
// // highlightStyle: "zenburn",
// highlightSpans: true,
// highlightLines: true,
// ratio: "16:9"};
var options = {sourceUrl: getParameterByName("p"),
highlightLanguage: "python",
highlightStyle: "github",
highlightSpans: true,
highlightLines: true,
ratio: "16:9",
slideNumberFormat: (current, total) => `
<div class="progress-bar-container">${current}/${total} <br/><br/>
<div class="progress-bar" style="width: ${current/total*100}%"></div>
</div>
`};
var renderMath = function() {
renderMathInElement(document.body, {delimiters: [ // mind the order of delimiters(!?)
{left: "$$", right: "$$", display: true},
{left: "$", right: "$", display: false},
{left: "\\[", right: "\\]", display: true},
{left: "\\(", right: "\\)", display: false},
]});
}
var slideshow = remark.create(options, renderMath);
</script>
</body>
</html>