forked from StanfordVL/ReferringRelationships
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator.py
275 lines (236 loc) · 10.5 KB
/
iterator.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
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
"""Iterator class that reads the data and batches it for training.
"""
from keras.utils import to_categorical
from keras.utils import Sequence
import argparse
import json
import h5py
import keras.backend as K
import numpy as np
import os
class DiscoveryIterator(Sequence):
"""Discovery version of iterator that drops objects and subjects.
"""
def __init__(self, data_dir, args):
"""Constructor for the iterator.
Args:
data_dir: Location of the annotations.
args: The arguments from the `config.py` file.
"""
self.data_dir = data_dir
self.input_dim = args.input_dim
self.use_subject = args.use_subject
self.use_predicate = args.use_predicate
self.use_object = args.use_object
self.batch_size = args.batch_size
self.categorical_predicate = args.categorical_predicate
self.use_internal_loss = args.use_internal_loss
self.num_predicates = args.num_predicates
self.num_objects = args.num_objects
# Drop variables.
self.subject_droprate = args.subject_droprate
self.object_droprate = args.object_droprate
self.always_drop_file = args.always_drop_file
if self.always_drop_file is not None:
self.drop_list = json.load(open(self.always_drop_file))
else:
self.drop_list = []
# Set the sizes of targets and images.
self.target_size = args.input_dim * args.input_dim
self.image_shape = (args.input_dim, args.input_dim, 3)
self.data_format = K.set_image_data_format('channels_last')
# Load the dataset
dataset = h5py.File(os.path.join(self.data_dir, 'dataset.hdf5'), 'r')
categories = dataset['categories']
self.samples = categories.shape[0]
self.length = int(float(self.samples) / self.batch_size)
def __len__(self):
"""The number of items in the dataset.
Returns:
The number of items in the dataset.
"""
return self.length
def get_image_dataset(self):
"""Retrieves the image dataset.
Returns:
The image hdf5 dataset.
"""
dataset = h5py.File(os.path.join(self.data_dir, 'images.hdf5'), 'r')
return dataset['images']
def on_epoch_end(self):
return
def __getitem__(self, idx):
"""Grab the next batch of data for training.
Args:
idx: The index between 0 and __len__().
Returns:
The next batch as a tuple containing two elements. The first element
is batch of inputs which contains the image, subject, predicate,
object. These inputs change depending on which inputs are training
with. The second element of the tuple contains the output masks we
want the model to predict.
"""
if not hasattr(self, 'images'):
images = h5py.File(os.path.join(self.data_dir, 'images.hdf5'), 'r')
dataset = h5py.File(os.path.join(self.data_dir, 'dataset.hdf5'), 'r')
self.images = images['images']
self.categories = dataset['categories']
self.subjects = dataset['subject_locations']
self.objects = dataset['object_locations']
start_idx = idx * self.batch_size
end_idx = min(self.samples, (idx + 1) * self.batch_size)
# Create the batches.
batch_rel = self.categories[start_idx:end_idx]
batch_s_regions = self.subjects[start_idx:end_idx].reshape(
self.batch_size, self.target_size)
batch_o_regions = self.objects[start_idx:end_idx].reshape(
self.batch_size, self.target_size)
current_batch_size = end_idx - start_idx
batch_image = np.zeros((current_batch_size,) + self.image_shape,
dtype=K.floatx())
for i, image_index in enumerate(batch_rel[:, 3]):
batch_image[i] = self.images[image_index]
# Choose the inputs based on the parts of the relationship we will use.
inputs = [batch_image]
if self.use_subject:
subject_masks = np.random.choice(
2, end_idx-start_idx,
p=[self.subject_droprate, 1.0 - self.subject_droprate,])
subject_cats = batch_rel[:, 0]
subject_cats[subject_masks == 0] = self.num_objects
inputs.append(subject_cats)
if self.use_predicate:
if self.categorical_predicate:
inputs.append(to_categorical(batch_rel[:, 1], num_classes=self.num_predicates))
else:
inputs.append(batch_rel[:, 1])
if self.use_object:
object_masks = np.random.choice(
2, end_idx-start_idx,
p=[self.object_droprate, 1.0 - self.object_droprate])
object_cats = batch_rel[:, 2]
object_cats[object_masks == 0] = self.num_objects
inputs.append(object_cats)
outputs = [batch_s_regions, batch_o_regions]
return inputs, outputs
class SmartIterator(Sequence):
"""Smart version of iterator that corresponds to `data.SmartDataset`.
"""
def __init__(self, data_dir, args):
"""Constructor for the iterator.
Args:
data_dir: Location of the annotations.
args: The arguments from the `config.py` file.
"""
self.data_dir = data_dir
self.input_dim = args.input_dim
self.output_dim = args.output_dim
self.use_subject = args.use_subject
self.use_predicate = args.use_predicate
self.use_object = args.use_object
self.batch_size = args.batch_size
self.categorical_predicate = args.categorical_predicate
self.use_internal_loss = args.use_internal_loss
self.num_predicates = args.num_predicates
# Set the sizes of targets and images.
self.target_size = self.output_dim * self.output_dim
self.image_shape = (self.input_dim, self.input_dim, 3)
self.data_format = K.set_image_data_format('channels_last')
# Load the dataset
dataset = h5py.File(os.path.join(self.data_dir, 'dataset.hdf5'), 'r')
categories = dataset['categories']
self.samples = categories.shape[0]
self.length = int(float(self.samples) / self.batch_size)
def __len__(self):
"""The number of items in the dataset.
Returns:
The number of items in the dataset.
"""
return self.length
def get_image_dataset(self):
"""Retrieves the image dataset.
Returns:
The image hdf5 dataset.
"""
dataset = h5py.File(os.path.join(self.data_dir, 'images.hdf5'), 'r')
return dataset['images']
def on_epoch_end(self):
return
def __getitem__(self, idx):
"""Grab the next batch of data for training.
Args:
idx: The index between 0 and __len__().
Returns:
The next batch as a tuple containing two elements. The first element
is batch of inputs which contains the image, subject, predicate,
object. These inputs change depending on which inputs are training
with. The second element of the tuple contains the output masks we
want the model to predict.
"""
if not hasattr(self, 'images'):
images = h5py.File(os.path.join(self.data_dir, 'images.hdf5'), 'r')
dataset = h5py.File(os.path.join(self.data_dir, 'dataset.hdf5'), 'r')
self.images = images['images']
self.categories = dataset['categories']
self.subjects = dataset['subject_locations']
self.objects = dataset['object_locations']
start_idx = idx * self.batch_size
end_idx = min(self.samples, (idx + 1) * self.batch_size)
# Create the batches.
batch_rel = self.categories[start_idx:end_idx]
batch_s_regions = self.subjects[start_idx:end_idx].reshape(
self.batch_size, self.target_size)
batch_o_regions = self.objects[start_idx:end_idx].reshape(
self.batch_size, self.target_size)
current_batch_size = end_idx - start_idx
batch_image = np.zeros((current_batch_size,) + self.image_shape,
dtype=K.floatx())
for i, image_index in enumerate(batch_rel[:, 3]):
batch_image[i] = self.images[image_index]
# Choose the inputs based on the parts of the relationship we will use.
inputs = [batch_image]
if self.use_subject:
inputs.append(batch_rel[:, 0])
if self.use_predicate:
if self.categorical_predicate:
inputs.append(to_categorical(batch_rel[:, 1], num_classes=self.num_predicates))
else:
inputs.append(batch_rel[:, 1])
if self.use_object:
inputs.append(batch_rel[:, 2])
outputs = [batch_s_regions, batch_o_regions]
return inputs, outputs
if __name__=='__main__':
parser = argparse.ArgumentParser(description='Iterator test.')
parser.add_argument('--data-dir', type=str,
default='data/vrd-10-10-2017/test/',
help='Location of the dataset.')
parser.add_argument('--dataset-type', type=str, default='smart',
help='[smart|discovery]')
parser.add_argument('--input-dim', type=int, default=224,
help='Size of the input image.')
parser.add_argument('--batch-size', type=int, default=1,
help='The batch size used in training.')
parser.add_argument('--num-print', type=int, default=1,
help='Number of entries to print.')
args = parser.parse_args()
args.use_subject = True
args.use_predicate = True
args.use_object = True
dataset_dict = {'smart': SmartIterator, 'discovery': DiscoveryIterator}
dataset = dataset_dict[args.dataset_type](args.data_dir, args)
print('Length of dataset: %d' % len(dataset))
print('Samples in dataset: %d'% dataset.samples)
count = 0
for inputs, outputs in dataset:
print('-'*20)
print('Image size: %d, %d, %d, %d' % inputs[0].shape)
print('Image avg pixel: %f' % np.average(inputs[0]))
print('Subject category: %d' % inputs[1][0])
print('Predicate category: %d' % inputs[2][0])
print('Object category: %d' % inputs[3][0])
print('Average subject heatmap pixels: %f' % np.average(outputs[0]))
print('Average object heatmap pixels: %f' % np.average(outputs[1]))
if count >= args.num_print:
break
count += 1