-
Notifications
You must be signed in to change notification settings - Fork 11
/
TripletDataLayer.py
187 lines (165 loc) · 6.17 KB
/
TripletDataLayer.py
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
"""Copyright@Xianming Liu, University of Illinois at Urbana, Champaign
Implementation of Triplet Data Layer
"""
import atexit
import numpy as np
from BasePythonDataLayer import BasePythonDataLayer
from multiprocessing import (Process, Pipe)
from utils.SampleIO import extract_sample
from TripletSampler import TripletSampler
__authors__ = ['Xianming Liu(liuxianming@gmail.com)']
class TripletDataLayer(BasePythonDataLayer):
"""Triplet Data Layer:
Provide data batches for Triplet Network (using ranking loss)
Data: 3 * batch_size * channels * width * height
anchor image, positive and negative ones
Label: Relative Similarity (Optional)
Implemenation is based on BasePythonDataLayer,
need to implement:
1. get_next_minibatch(self) function
2. sampleing functions for randomly sampling and guided sampling
"""
def setup(self, bottom, top):
# setup functions from super class
super(TripletDataLayer, self).setup(bottom, top)
print("Using Triplet Python Data Layer")
# prefetch or not: default = False
self._sampling_type = self._layer_params.get('type', 'RANDOM')
self._prefetch = self._layer_params.get('prefetch', False)
"""Construct kwargs:
possible fields:
k - number of candidates when hard negative sampling
m - similarity graph filename for hard negative sampling
n - number of iterations before hard negative sampling
"""
kwargs = {}
for key, value in self._layer_params.iteritems():
if key.lower() in ['k', 'm', 'n']:
kwargs[key.lower()] = value
if self._prefetch:
# using prefetch to generate mini-batches
self._conn, conn = Pipe()
self._prefetch_process = TripletPrefetcher(
conn,
self._label, self._data,
self._mean, self._resize, self._batch_size,
self._sampling_type, **kwargs
)
print("Start Prefetching Process...")
self._prefetch_process.start()
def cleanup():
print("Terminating Prefetching Processs...")
self._prefetch_process.terminate()
self._prefetch_process.join()
self._conn.close()
atexit.register(cleanup)
else:
self._sampler = TripletSampler(
self._sampling_type, self._label, **kwargs)
self.reshape(bottom, top)
def get_a_datum(self):
"""Get a datum:
Sampling -> decode images -> stack numpy array
"""
sample = self._sampler.sample()
if self._compressed:
datum_ = [
extract_sample(self._data[id], self._mean, self._resize) for
id in sample[:3]]
else:
datum_ = [self._data[id] for id in sample[:3]]
if len(sample) == 4:
datum_.append(sample[-1])
return datum_
def get_next_minibatch(self):
if self._prefetch:
# get mini-batch from prefetcher
batch = self._conn.recv()
else:
# generate using in-thread functions
data = []
p_data = []
n_data = []
label = []
for i in range(self._batch_size):
datum_ = self.get_a_datum()
data.append(datum_[0])
p_data.append(datum_[1])
n_data.append(datum_[2])
if len(datum_) == 4:
# datum and label / margin
label.append(datum_[-1])
batch = [np.array(data),
np.array(p_data),
np.array(n_data)]
if len(label):
label = np.array(label).reshape(self._batch_size, 1, 1, 1)
batch.append(label)
return batch
class TripletPrefetcher(Process):
"""TripletPrefetcher:
Use a separate process to sample triplets,
following the same function implementations as TripletDataLayer
"""
def __init__(self, conn, labels, data,
mean, resize, batch_size,
# samping related parameters
sampling_type, **kwargs):
super(TripletPrefetcher, self).__init__()
self._conn = conn
self._labels = labels
self._data = data
if type(self._data[0]) is not str:
self._compressed = False
else:
self._compressed = True
self._batch_size = batch_size
self._mean = mean
self._resize = resize
self._sampling_type = sampling_type
# kwargs is a dictionary related with sampling
self._sampler = TripletSampler(
self._sampling_type, self._labels, **kwargs)
def type(self):
return "TripletPrefetcher"
def get_a_datum(self):
"""Get a datum:
Sampling -> decode images -> stack numpy array
"""
sample = self._sampler.sample()
if self._compressed:
datum_ = [
extract_sample(self._data[id], self._mean, self._resize) for
id in sample[:3]]
else:
datum_ = [self._data[id] for id in sample[:3]]
if len(sample) == 4:
datum_.append(sample[-1])
return datum_
def get_next_minibatch(self):
# generate using in-thread functions
data = []
p_data = []
n_data = []
label = []
for i in range(self._batch_size):
datum_ = self.get_a_datum()
# print(len(datum_), ":".join([str(x.shape) for x in datum_]))
data.append(datum_[0])
p_data.append(datum_[1])
n_data.append(datum_[2])
if len(datum_) == 4:
# datum and label / margin
label.append(datum_[-1])
batch = [np.array(data),
np.array(p_data),
np.array(n_data)]
if len(label):
label = np.array(label).reshape(self._batch_size, 1, 1, 1)
batch.append(label)
return batch
def run(self):
print("Prefetcher Started...")
while True:
batch = self.get_next_minibatch()
self._conn.send(batch)