-
Notifications
You must be signed in to change notification settings - Fork 164
/
datasets.py
323 lines (258 loc) · 11.5 KB
/
datasets.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
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# ---------------------------------------------------------------
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for NVAE. To view a copy of this license, see the LICENSE file.
# ---------------------------------------------------------------
"""Code for getting the data loaders."""
import numpy as np
from PIL import Image
import torch
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from scipy.io import loadmat
import os
import urllib
from lmdb_datasets import LMDBDataset
from thirdparty.lsun import LSUN
class StackedMNIST(dset.MNIST):
def __init__(self, root, train=True, transform=None, target_transform=None,
download=False):
super(StackedMNIST, self).__init__(root=root, train=train, transform=transform,
target_transform=target_transform, download=download)
index1 = np.hstack([np.random.permutation(len(self.data)), np.random.permutation(len(self.data))])
index2 = np.hstack([np.random.permutation(len(self.data)), np.random.permutation(len(self.data))])
index3 = np.hstack([np.random.permutation(len(self.data)), np.random.permutation(len(self.data))])
self.num_images = 2 * len(self.data)
self.index = []
for i in range(self.num_images):
self.index.append((index1[i], index2[i], index3[i]))
def __len__(self):
return self.num_images
def __getitem__(self, index):
img = np.zeros((28, 28, 3), dtype=np.uint8)
target = 0
for i in range(3):
img_, target_ = self.data[self.index[index][i]], int(self.targets[self.index[index][i]])
img[:, :, i] = img_
target += target_ * 10 ** (2 - i)
img = Image.fromarray(img, mode="RGB")
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
class Binarize(object):
""" This class introduces a binarization transformation
"""
def __call__(self, pic):
return torch.Tensor(pic.size()).bernoulli_(pic)
def __repr__(self):
return self.__class__.__name__ + '()'
class CropCelebA64(object):
""" This class applies cropping for CelebA64. This is a simplified implementation of:
https://github.com/andersbll/autoencoding_beyond_pixels/blob/master/dataset/celeba.py
"""
def __call__(self, pic):
new_pic = pic.crop((15, 40, 178 - 15, 218 - 30))
return new_pic
def __repr__(self):
return self.__class__.__name__ + '()'
def get_loaders(args):
"""Get data loaders for required dataset."""
return get_loaders_eval(args.dataset, args)
def download_omniglot(data_dir):
filename = 'chardata.mat'
if not os.path.exists(data_dir):
os.mkdir(data_dir)
url = 'https://raw.github.com/yburda/iwae/master/datasets/OMNIGLOT/chardata.mat'
filepath = os.path.join(data_dir, filename)
if not os.path.exists(filepath):
filepath, _ = urllib.request.urlretrieve(url, filepath)
print('Downloaded', filename)
return
def load_omniglot(data_dir):
download_omniglot(data_dir)
data_path = os.path.join(data_dir, 'chardata.mat')
omni = loadmat(data_path)
train_data = 255 * omni['data'].astype('float32').reshape((28, 28, -1)).transpose((2, 1, 0))
test_data = 255 * omni['testdata'].astype('float32').reshape((28, 28, -1)).transpose((2, 1, 0))
train_data = train_data.astype('uint8')
test_data = test_data.astype('uint8')
return train_data, test_data
class OMNIGLOT(Dataset):
def __init__(self, data, transform):
self.data = data
self.transform = transform
def __getitem__(self, index):
d = self.data[index]
img = Image.fromarray(d)
return self.transform(img), 0 # return zero as label.
def __len__(self):
return len(self.data)
def get_loaders_eval(dataset, args):
"""Get train and valid loaders for cifar10/tiny imagenet."""
if dataset == 'cifar10':
num_classes = 10
train_transform, valid_transform = _data_transforms_cifar10(args)
train_data = dset.CIFAR10(
root=args.data, train=True, download=True, transform=train_transform)
valid_data = dset.CIFAR10(
root=args.data, train=False, download=True, transform=valid_transform)
elif dataset == 'mnist':
num_classes = 10
train_transform, valid_transform = _data_transforms_mnist(args)
train_data = dset.MNIST(
root=args.data, train=True, download=True, transform=train_transform)
valid_data = dset.MNIST(
root=args.data, train=False, download=True, transform=valid_transform)
elif dataset == 'stacked_mnist':
num_classes = 1000
train_transform, valid_transform = _data_transforms_stacked_mnist(args)
train_data = StackedMNIST(
root=args.data, train=True, download=True, transform=train_transform)
valid_data = StackedMNIST(
root=args.data, train=False, download=True, transform=valid_transform)
elif dataset == 'omniglot':
num_classes = 0
download_omniglot(args.data)
train_transform, valid_transform = _data_transforms_mnist(args)
train_data, valid_data = load_omniglot(args.data)
train_data = OMNIGLOT(train_data, train_transform)
valid_data = OMNIGLOT(valid_data, valid_transform)
elif dataset.startswith('celeba'):
if dataset == 'celeba_64':
resize = 64
num_classes = 40
train_transform, valid_transform = _data_transforms_celeba64(resize)
train_data = LMDBDataset(root=args.data, name='celeba64', train=True, transform=train_transform, is_encoded=True)
valid_data = LMDBDataset(root=args.data, name='celeba64', train=False, transform=valid_transform, is_encoded=True)
elif dataset in {'celeba_256'}:
num_classes = 1
resize = int(dataset.split('_')[1])
train_transform, valid_transform = _data_transforms_generic(resize)
train_data = LMDBDataset(root=args.data, name='celeba', train=True, transform=train_transform)
valid_data = LMDBDataset(root=args.data, name='celeba', train=False, transform=valid_transform)
else:
raise NotImplementedError
elif dataset.startswith('lsun'):
if dataset.startswith('lsun_bedroom'):
resize = int(dataset.split('_')[-1])
num_classes = 1
train_transform, valid_transform = _data_transforms_lsun(resize)
train_data = LSUN(root=args.data, classes=['bedroom_train'], transform=train_transform)
valid_data = LSUN(root=args.data, classes=['bedroom_val'], transform=valid_transform)
elif dataset.startswith('lsun_church'):
resize = int(dataset.split('_')[-1])
num_classes = 1
train_transform, valid_transform = _data_transforms_lsun(resize)
train_data = LSUN(root=args.data, classes=['church_outdoor_train'], transform=train_transform)
valid_data = LSUN(root=args.data, classes=['church_outdoor_val'], transform=valid_transform)
elif dataset.startswith('lsun_tower'):
resize = int(dataset.split('_')[-1])
num_classes = 1
train_transform, valid_transform = _data_transforms_lsun(resize)
train_data = LSUN(root=args.data, classes=['tower_train'], transform=train_transform)
valid_data = LSUN(root=args.data, classes=['tower_val'], transform=valid_transform)
else:
raise NotImplementedError
elif dataset.startswith('imagenet'):
num_classes = 1
resize = int(dataset.split('_')[1])
assert args.data.replace('/', '')[-3:] == dataset.replace('/', '')[-3:], 'the size should match'
train_transform, valid_transform = _data_transforms_generic(resize)
train_data = LMDBDataset(root=args.data, name='imagenet-oord', train=True, transform=train_transform)
valid_data = LMDBDataset(root=args.data, name='imagenet-oord', train=False, transform=valid_transform)
elif dataset.startswith('ffhq'):
num_classes = 1
resize = 256
train_transform, valid_transform = _data_transforms_generic(resize)
train_data = LMDBDataset(root=args.data, name='ffhq', train=True, transform=train_transform)
valid_data = LMDBDataset(root=args.data, name='ffhq', train=False, transform=valid_transform)
else:
raise NotImplementedError
train_sampler, valid_sampler = None, None
if args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_data)
valid_sampler = torch.utils.data.distributed.DistributedSampler(valid_data)
train_queue = torch.utils.data.DataLoader(
train_data, batch_size=args.batch_size,
shuffle=(train_sampler is None),
sampler=train_sampler, pin_memory=True, num_workers=8, drop_last=True)
valid_queue = torch.utils.data.DataLoader(
valid_data, batch_size=args.batch_size,
shuffle=(valid_sampler is None),
sampler=valid_sampler, pin_memory=True, num_workers=1, drop_last=False)
return train_queue, valid_queue, num_classes
def _data_transforms_cifar10(args):
"""Get data transforms for cifar10."""
train_transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor()
])
valid_transform = transforms.Compose([
transforms.ToTensor()
])
return train_transform, valid_transform
def _data_transforms_mnist(args):
"""Get data transforms for cifar10."""
train_transform = transforms.Compose([
transforms.Pad(padding=2),
transforms.ToTensor(),
Binarize(),
])
valid_transform = transforms.Compose([
transforms.Pad(padding=2),
transforms.ToTensor(),
Binarize(),
])
return train_transform, valid_transform
def _data_transforms_stacked_mnist(args):
"""Get data transforms for cifar10."""
train_transform = transforms.Compose([
transforms.Pad(padding=2),
transforms.ToTensor()
])
valid_transform = transforms.Compose([
transforms.Pad(padding=2),
transforms.ToTensor()
])
return train_transform, valid_transform
def _data_transforms_generic(size):
train_transform = transforms.Compose([
transforms.Resize(size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
valid_transform = transforms.Compose([
transforms.Resize(size),
transforms.ToTensor(),
])
return train_transform, valid_transform
def _data_transforms_celeba64(size):
train_transform = transforms.Compose([
CropCelebA64(),
transforms.Resize(size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
valid_transform = transforms.Compose([
CropCelebA64(),
transforms.Resize(size),
transforms.ToTensor(),
])
return train_transform, valid_transform
def _data_transforms_lsun(size):
train_transform = transforms.Compose([
transforms.Resize(size),
transforms.RandomCrop(size),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
])
valid_transform = transforms.Compose([
transforms.Resize(size),
transforms.CenterCrop(size),
transforms.ToTensor(),
])
return train_transform, valid_transform