-
Notifications
You must be signed in to change notification settings - Fork 4
/
data.py
220 lines (173 loc) · 7.38 KB
/
data.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
import os
import torch
from tqdm import tqdm
import threading
_lock = threading.Lock()
from transforms import get_transform
from dataset_fashionIQ import FashionIQDataset
from dataset_shoes import ShoesDataset
from dataset_cirr import CIRRDataset
from dataset_f200k import Fashion200K
################################################################################
# *** GET FUNCTIONS FOR DATA LOADERS
################################################################################
# Generic functions
def get_loader_single(opt, vocab, split, transform, what_elements="triplet",
shuffle=True, drop_last=False):
# Dataset
if opt.data_name == 'fashionIQ':
dataset = FashionIQDataset(split, vocab, transform, what_elements,
opt.load_image_feature, fashion_categories=opt.categories)
elif opt.data_name == 'fashion200K':
dataset = Fashion200K(split, vocab, transform, what_elements, opt.load_image_feature)
elif opt.data_name == 'shoes':
dataset = ShoesDataset(split, vocab, transform, what_elements, opt.load_image_feature)
elif opt.data_name == 'cirr':
dataset = CIRRDataset(split, vocab, transform, what_elements, opt.load_image_feature)
# Data loader
collate_fn = get_collate_fn(what_elements)
data_loader = torch.utils.data.DataLoader(dataset=dataset,
batch_size=opt.batch_size,
shuffle=shuffle,
pin_memory=True,
num_workers=opt.workers,
drop_last=drop_last,
collate_fn=collate_fn)
print("#### dataset size:", len(dataset))
print("#### batch size: {} (drop last? {})".format(opt.batch_size, drop_last))
return data_loader
def get_eval_loader_generic(opt, vocab, split, what_elements):
transform = get_transform(opt, phase="eval")
loader = get_loader_single(opt, vocab, split, transform, what_elements,
shuffle=False, drop_last=False)
return loader
# Functions to be called from outside this file
def get_train_loader(opt, vocab, split='train', shuffle=True):
transform = get_transform(opt, phase="train")
triplet_loader = get_loader_single(opt, vocab, split, transform, "triplet",
shuffle=shuffle, drop_last=True)
return triplet_loader
def get_eval_loaders(opt, vocab, split='val'):
queries_loader = get_eval_loader_generic(opt, vocab, split, "query")
targets_loader = get_eval_loader_generic(opt, vocab, split, "target")
return queries_loader, targets_loader
def get_subset_loader(opt, vocab, split='val'):
return get_eval_loader_generic(opt, vocab, split, "subset")
def get_soft_targets_loader(opt, vocab, split='val'):
return get_eval_loader_generic(opt, vocab, split, "soft_targets")
################################################################################
# *** COLLATE FN FUNCTIONS
################################################################################
def get_collate_fn(what_elements):
if what_elements=='triplet':
collate_fn_func = collate_fn_triplet
elif what_elements=='query':
collate_fn_func = collate_fn_query
elif what_elements=='target':
collate_fn_func = collate_fn_img_with_id
elif what_elements=='subset':
collate_fn_func = collate_fn_tensor_with_index
elif what_elements == 'soft_targets':
collate_fn_func = collate_fn_direct
return collate_fn_func
def collate_fn_triplet(data):
"""Build mini-batch tensors from a list of tuples.
Args:
data: list of (images_src, sentences, images_trg, raw_caption, dataset_index) tuple.
- images (src/trg): torch tensor of shape (3, 256, 256) or (*).
- sentence: torch tensor of shape (?); variable length.
- raw_caption: string
- dataset_index: integer
Returns:
images_src: torch tensor of shape (batch_size, 3, 256, 256) or (batch_size, *).
sentences_padded: torch tensor of shape (batch_size, padded_length).
lengths: list; valid length for each padded sentence.
images_trg: same as images_src for target images
raw_caps: list of the involved captions, as raw text.
dataset_ids: index of the element in the dataset.
"""
# Sort a data list by sentence length
data.sort(key=lambda x: len(x[1]), reverse=True)
images_src, sentences, images_trg, raw_caps, dataset_ids = zip(*data)
# Merge images (convert tuple of 3D tensor to 4D tensor)
images_src = torch.stack(images_src, 0)
images_trg = torch.stack(images_trg, 0)
# Merge sentences (convert tuple of 1D tensor to 2D tensor)
lengths = torch.tensor([len(cap) for cap in sentences])
sentences_padded = torch.zeros(len(sentences), max(lengths)).long()
for i, cap in enumerate(sentences):
end = lengths[i]
sentences_padded[i, :end] = cap[:end]
return images_src, sentences_padded, lengths, images_trg, raw_caps, dataset_ids
def collate_fn_query(data):
"""Build mini-batch tensors from a list of tuples.
Args:
data: list of (image_src, sentence, img_src_id, img_trg_id, raw_caption, dataset_index) tuple.
- image_src : torch tensor of shape (3, 256, 256) or (*).
- sentence: torch tensor of shape (?); variable length.
- img_src_id: integer
- img_trg_id: list of integers
- raw_caption: string
- dataset_index: integer
Returns:
images_src: torch tensor of shape (batch_size, 3, 256, 256) or (batch_size, *).
sentences_padded: torch tensor of shape (batch_size, padded_length).
lengths: list; valid length for each padded sentence.
img_src_ids: list of ids of the source image
img_trg_ids: list of lists, where each list is a list of target image ids
raw_caps: list of the involved captions, as raw text.
dataset_ids: index of the element in the dataset.
"""
# Sort a data list by sentence length
data.sort(key=lambda x: len(x[1]), reverse=True)
images_src, sentences, img_src_ids, img_trg_ids, raw_caps, dataset_ids = zip(*data)
# Merge images (convert tuple of 3D tensor to 4D tensor)
images_src = torch.stack(images_src, 0)
# Merge sentences (convert tuple of 1D tensor to 2D tensor)
lengths = torch.tensor([len(cap) for cap in sentences])
sentences_padded = torch.zeros(len(sentences), max(lengths)).long()
for i, cap in enumerate(sentences):
end = lengths[i]
sentences_padded[i, :end] = cap[:end]
return images_src, sentences_padded, lengths, img_src_ids, img_trg_ids, raw_caps, dataset_ids
def collate_fn_img_with_id(data):
"""Build mini-batch tensors from a list of tuples.
Args:
data: list of (image, id, dataset_index) tuple.
- images: torch tensor of shape (3, 256, 256) or (*)
- id: integer
- dataset_index: integer
Returns:
images: torch tensor of shape (batch_size, 3, 256, 256) or (batch_size, *).
ids: IDs of the image
dataset_ids: index of the element in the dataset.
"""
# Extract data
images, ids, dataset_ids = zip(*data)
# Merge images (convert tuple of 3D tensor to 4D tensor)
images = torch.stack(images, 0)
return images, ids, dataset_ids
def collate_fn_tensor_with_index(data):
"""Build mini-batch tensors from a list of tuples.
Args:
data: list of (thing, dataset_index) tuple.
- thing: torch tensor of shape (*).
- dataset_index: integer
Returns:
things: torch tensor of shape (batch_size, *).
dataset_ids: index of the element in the dataset.
"""
# Extract data
things, dataset_ids = zip(*data)
# Merge things (convert tuple of *D tensor to (*+1)D tensor)
things = torch.stack(things, 0)
return things, dataset_ids
def collate_fn_direct(data):
"""Build mini-batch tensors from a list of tuples.
Args:
data: list of tuples
Returns:
one list per element in a tuple, gathering all the elements at the
same position in the tuple, accross all tuples
"""
return zip(*data)