-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
176 lines (138 loc) · 6.17 KB
/
dataset.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
#!/usr/bin/env python
import os
import torch
import PIL
from torch.nn.utils.rnn import pad_sequence
from vocabulary import SpecialToken
# ==================================================================================================
# -- helpers ---------------------------------------------------------------------------------------
# ==================================================================================================
class Flickr8kFolder(object):
"""
Helper object to ease the accessibility to the files defining the dataset.
WARNING: This class assumes that the data is organized as follows:
.
|__ Flickr8k_Dataset
| |_ [img_id].jpg
| |_ ...
|
|__ Flickr8k_Text
|_Flickr8k.token.txt
|_Flickr_8k.devImages.txt
|_Flickr_8k.testImages.txt
|_Flickr_8k.trainImages.txt
"""
def __init__(self, root):
self.root = root
@property
def img_root(self):
return os.path.join(self.root, 'Flickr8k_Dataset')
@property
def text_root(self):
return os.path.join(self.root, 'Flickr8k_Text')
@property
def ann_file(self):
"""
Annotation file.
This file contains the image id and the corresponding caption for each one of the images
that define the dataset. Each image has five different captions and the captions are already
tokenized.
"""
return os.path.join(self.text_root, 'Flickr8k.token.txt')
@property
def train_imgs_file(self):
"""
Train images file.
This file contains the ids of the images that define the trainning set.
"""
return os.path.join(self.text_root, 'Flickr_8k.trainImages.txt')
@property
def test_imgs_file(self):
"""
Test images file.
This file contains the ids of the images that define the testing set.
"""
return os.path.join(self.text_root, 'Flickr_8k.testImages.txt')
@property
def eval_imgs_file(self):
"""
Evaluation images file.
This file contains the ids of the images that define the evaluation set.
"""
return os.path.join(self.text_root, 'Flickr_8k.devImages.txt')
# ==================================================================================================
# -- flickr8k dataset ------------------------------------------------------------------------------
# ==================================================================================================
class Flickr8kDataset(torch.utils.data.Dataset):
"""
Flickr8k custom dataset.
"""
def __init__(self, data_folder, split='train', transform=None, target_transform=None):
super(Flickr8kDataset, self).__init__()
self._data_folder = data_folder
self._transform = transform
self._target_transform = target_transform
if split == 'train':
_split_imgs_file = data_folder.train_imgs_file
elif split == 'test':
_split_imgs_file = data_folder.test_imgs_file
elif split == 'eval':
_split_imgs_file = data_folder.eval_imgs_file
# Processing split imgs file.
split_imgs = [] # list of image ids
with open(_split_imgs_file) as f:
split_imgs = [line[:-1] for line in f.readlines()]
# Proccessing tokenized captions. Each sample is defined with the tuple (image_id, [tokens])
self.samples = []
with open(data_folder.ann_file) as f:
for line in f.readlines():
line = line.split()
image_id, tokens = line[0], line[1:]
if image_id[:-2] in split_imgs:
self.samples.append((image_id, tokens))
def __len__(self):
return len(self.samples)
def __getitem__(self, key):
image_id, tokens = self.samples[key]
# Processing image
filename = os.path.join(self._data_folder.img_root, image_id[:-2])
image = PIL.Image.open(filename).convert('RGB')
if self._transform is not None:
image = self._transform(image)
# Processing caption.
caption = tokens
if self._target_transform is not None:
caption = self._target_transform(tokens)
return image, caption
def flickr_collate_fn(batch):
"""
Custom collate function to be used with the data loader.
This methos returns a padded caption set to be used in the trainning stage (with the <START>
special token removed) and a padded caption set to be used during the computation loss (with the
<END> special token removed). The returned data is sorted in descending order based on the
caption length.
:param bacth: list of tuples (image, caption) returned by the dataset.
- img - float tensor of shape (channels, height, width).
- caption - long tensor of variable length.
:returns: tuple (imgs, captions_train, captions_loss, lengths)
- imgs - float tensor of shape (batch_size, channels, height, width)
- captions_train - long tensor of shape (batch_size, max_seq_length)
- captions_loss - long tensor of shape (batch_size, max_seq_length)
- lengths - long tensor of shape (batch_size)
"""
# Sort data by caption length in descending order.
batch.sort(key=lambda x: x[1].size(0), reverse=True)
imgs = [sample[0] for sample in batch]
captions_train = [sample[1][:-1] for sample in batch] # Remove <end> special token.
captions_loss = [sample[1][1:] for sample in batch] # Remove <start> special token.
lengths = [len(caption) for caption in captions_train]
# Padding captions.
captions_train = pad_sequence(captions_train,
batch_first=True,
padding_value=SpecialToken.PAD.value.index)
captions_loss = pad_sequence(captions_loss,
batch_first=True,
padding_value=SpecialToken.PAD.value.index)
# Length list to long tensor.
lengths = torch.tensor(lengths, dtype=torch.int64)
return torch.stack(imgs), captions_train, captions_loss, lengths