TripletWithFastSelectionDisk.py 8.08 KB
Newer Older
1
2
3
4
5
6
7
8
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# @author: Tiago de Freitas Pereira <tiago.pereira@idiap.ch>
# @date: Wed 11 May 2016 09:39:36 CEST 

import numpy
import tensorflow as tf

9
10
11
from .Disk import Disk
from .Triplet import Triplet
from .OnlineSampling import OnlineSampling
12
13
14
from scipy.spatial.distance import euclidean, cdist

import logging
15
logger = logging.getLogger("bob.learn")
16

Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
17

18
class TripletWithFastSelectionDisk(Triplet, Disk, OnlineSampling):
19
    """
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
20
21
    This data shuffler generates triplets from :py:class:`bob.learn.tensorflow.datashuffler.Triplet` and
    :py:class:`bob.learn.tensorflow.datashuffler.Disk` shufflers.
22
23
24
25
26
27
28
29

    The selection of the triplets is inspired in the paper:

    Schroff, Florian, Dmitry Kalenichenko, and James Philbin.
    "Facenet: A unified embedding for face recognition and clustering." Proceedings of the IEEE Conference on
    Computer Vision and Pattern Recognition. 2015.

    In this shuffler, the triplets are selected as the following:
30
31
32
33

    1. Select M identities.
    2. Get N pairs anchor-positive (for each M identities) such that the argmax(anchor, positive).
    3. For each pair anchor-positive, find the "semi-hard" negative samples such that :math:`argmin(||f(x_a) - f(x_p)||^2 < ||f(x_a) - f(x_n)||^2`.
34
35

     **Parameters**
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

     data:
       Input data to be trainer

     labels:
       Labels. These labels should be set from 0..1

     input_shape:
       The shape of the inputs

     input_dtype:
       The type of the data,

     batch_size:
       Batch size

     seed:
       The seed of the random number generator

     data_augmentation:
       The algorithm used for data augmentation. Look :py:class:`bob.learn.tensorflow.datashuffler.DataAugmentation`

     normalizer:
       The algorithm used for feature scaling. Look :py:class:`bob.learn.tensorflow.datashuffler.ScaleFactor`, :py:class:`bob.learn.tensorflow.datashuffler.Linear` and :py:class:`bob.learn.tensorflow.datashuffler.MeanOffset`
60
61
62
63
    """

    def __init__(self, data, labels,
                 input_shape,
Tiago Pereira's avatar
Tiago Pereira committed
64
                 input_dtype="float32",
65
66
67
                 batch_size=1,
                 seed=10,
                 data_augmentation=None,
68
                 total_identities=10,
69
                 normalizer=None):
70
71
72
73
74
75
76
77

        super(TripletWithFastSelectionDisk, self).__init__(
            data=data,
            labels=labels,
            input_shape=input_shape,
            input_dtype=input_dtype,
            batch_size=batch_size,
            seed=seed,
78
79
            data_augmentation=data_augmentation,
            normalizer=normalizer
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        )
        self.clear_variables()
        # Seting the seed
        numpy.random.seed(seed)

        self.total_identities = total_identities
        self.first_batch = True

        # For the negative search I'll load `N` times the batch
        self.batch_increase_factor = 4

    def get_random_batch(self):
        """
        Get a random triplet

        **Parameters**
            is_target_set_train: Defining the target set to get the batch

        **Return**
        """

Tiago Pereira's avatar
Tiago Pereira committed
101
        shape = [self.batch_size] + list(self.input_shape[1:])
102

Tiago Pereira's avatar
Tiago Pereira committed
103
104
105
        sample_a = numpy.zeros(shape=shape, dtype=self.input_dtype)
        sample_p = numpy.zeros(shape=shape, dtype=self.input_dtype)
        sample_n = numpy.zeros(shape=shape, dtype=self.input_dtype)
Tiago Pereira's avatar
Tiago Pereira committed
106
107

        for i in range(shape[0]):
108
            file_name_a, file_name_p, file_name_n = self.get_one_triplet(self.data, self.labels)
109
110
111
            sample_a[i, ...] = self.normalize_sample(self.load_from_file(str(file_name_a)))
            sample_p[i, ...] = self.normalize_sample(self.load_from_file(str(file_name_p)))
            sample_n[i, ...] = self.normalize_sample(self.load_from_file(str(file_name_n)))
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130

        return [sample_a, sample_p, sample_n]

    def get_batch(self):
        """
        Get SELECTED triplets

        **Parameters**
            is_target_set_train: Defining the target set to get the batch

        **Return**
        """

        if self.first_batch:
            self.first_batch = False
            return self.get_random_batch()

        # Selecting the classes used in the selection
        indexes = numpy.random.choice(len(self.possible_labels), self.total_identities, replace=False)
131
        samples_per_identity = int(numpy.ceil(self.batch_size/float(self.total_identities)))
132
133
134
        anchor_labels = numpy.ones(samples_per_identity) * self.possible_labels[indexes[0]]

        for i in range(1, self.total_identities):
Tiago Pereira's avatar
Tiago Pereira committed
135
            anchor_labels = numpy.hstack((anchor_labels, numpy.ones(samples_per_identity) * self.possible_labels[indexes[i]]))
136
137
        anchor_labels = anchor_labels[0:self.batch_size]

Tiago Pereira's avatar
Tiago Pereira committed
138
        samples_a = numpy.zeros(shape=self.shape, dtype=self.input_dtype)
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

        # Computing the embedding
        for i in range(self.shape[0]):
            samples_a[i, ...] = self.get_anchor(anchor_labels[i])
        embedding_a = self.project(samples_a)

        # Getting the positives
        samples_p, embedding_p, d_anchor_positive = self.get_positives(anchor_labels, embedding_a)
        samples_n = self.get_negative(anchor_labels, embedding_a, d_anchor_positive)

        return samples_a, samples_p, samples_n

    def get_anchor(self, label):
        """
        Select random samples as anchor
        """

        # Getting the indexes of the data from a particular client
        indexes = numpy.where(self.labels == label)[0]
        numpy.random.shuffle(indexes)

        file_name = self.data[indexes[0], ...]
        anchor = self.load_from_file(str(file_name))

163
        anchor = self.normalize_sample(anchor)
164
165
166
167
168
169
170

        return anchor

    def get_positives(self, anchor_labels, embedding_a):
        """
        Get the a random set of positive pairs
        """
Tiago Pereira's avatar
Tiago Pereira committed
171
        samples_p = numpy.zeros(shape=self.shape, dtype=self.input_dtype)
172
173
174
175
176
        for i in range(self.shape[0]):
            l = anchor_labels[i]
            indexes = numpy.where(self.labels == l)[0]
            numpy.random.shuffle(indexes)
            file_name = self.data[indexes[0], ...]
177
            samples_p[i, ...] = self.normalize_sample(self.load_from_file(str(file_name)))
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

        embedding_p = self.project(samples_p)

        # Computing the distances
        d_anchor_positive = []
        for i in range(self.shape[0]):
            d_anchor_positive.append(euclidean(embedding_a[i, :], embedding_p[i, :]))

        return samples_p, embedding_p, d_anchor_positive

    def get_negative(self, anchor_labels, embedding_a, d_anchor_positive):
        """
        Get the the semi-hard negative
        """

        # Shuffling all the dataset
        indexes = range(len(self.labels))
        numpy.random.shuffle(indexes)

        negative_samples_search = self.batch_size*self.batch_increase_factor

        # Limiting to the batch size, otherwise the number of comparisons will explode
        indexes = indexes[0:negative_samples_search]

        # Loading samples for the semi-hard search
        shape = tuple([len(indexes)] + list(self.shape[1:]))
Tiago Pereira's avatar
Tiago Pereira committed
204
205
        temp_samples_n = numpy.zeros(shape=shape, dtype=self.input_dtype)
        samples_n = numpy.zeros(shape=self.shape, dtype=self.input_dtype)
206
207
        for i in range(shape[0]):
            file_name = self.data[indexes[i], ...]
208
            temp_samples_n[i, ...] = self.normalize_sample(self.load_from_file(str(file_name)))
209
210
211
212
213
214
215
216
217
218
219

        # Computing all the embeddings
        embedding_temp_n = self.project(temp_samples_n)

        # Computing the distances
        d_anchor_negative = cdist(embedding_a, embedding_temp_n, metric='euclidean')

        # Selecting the negative samples
        for i in range(self.shape[0]):
            label = anchor_labels[i]
            possible_candidates = [d if d > d_anchor_positive[i] else numpy.inf for d in  d_anchor_negative[i]]
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
220
            
221
222
223
            for j in numpy.argsort(possible_candidates):

                # Checking if they don't have the same label
Tiago de Freitas Pereira's avatar
Tiago de Freitas Pereira committed
224
                if self.labels[indexes[j]] != label:
225
226
227
228
229
230
                    samples_n[i, ...] = temp_samples_n[j, ...]
                    if numpy.isinf(possible_candidates[j]):
                        logger.info("SEMI-HARD negative not found, took the first one")
                    break

        return samples_n