-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataloaders.py
567 lines (437 loc) · 21.7 KB
/
dataloaders.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
# import os, torch
# import torchvision
import numpy as np
# import scipy.io as sio
import torch
# from torchvision import datasets
import torchvision
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
import os
from utils import Standardize, CustomDataset
from utils import random_split, sample_weights
def load_dataset(args):
kwargs = {'num_workers': args.num_workers, 'pin_memory': True} if args.cuda else {}
if args.dataset == 'smallnorb':
args.channels = 2
args.n_classes = 5
args.Hin = args.crop_dim
args.Win = args.crop_dim
dataset = 'smallNORB_48'
working_dir = os.path.join(os.getcwd(), 'data', dataset)
dataset_paths = {'train': os.path.join(working_dir,'train'),
'test': os.path.join(working_dir,'test')}
dataloaders = smallnorb(args, dataset_paths)
# args.class_names = ('car', 'animal', 'truck', 'airplane', 'human') # 0,1,2,3,4 labels
# args.n_channels, args.n_classes = 2, 5
elif args.dataset == 'mnist':
args.channels = 1
args.n_classes = 10
args.Hin = args.crop_dim
args.Win = args.crop_dim
dataset = "MNIST"
working_dir = os.path.join(os.getcwd(), 'data', dataset)
dataset_paths = {'train': os.path.join(working_dir,'train'),
'test': os.path.join(working_dir,'test')}
dataloaders = mnist(args, dataset_paths)
# train_loader = torch.utils.data.DataLoader(
# torchvision.datasets.MNIST('../data', train=True, download=True,
# transform=transforms.Compose([
# transforms.Pad(2), transforms.RandomCrop(28),
# transforms.ToTensor()
# ])),
# batch_size=args.batch_size, shuffle=True, **kwargs)
#
# test_loader = torch.utils.data.DataLoader(
# torchvision.datasets.MNIST('../data', train=False, transform=transforms.Compose([
# transforms.ToTensor()
# ])),
# batch_size=args.batch_size, shuffle=False, **kwargs)
elif args.dataset == 'svhn':
args.channels = 3
args.n_classes = 10
dataset = 'SVHN'
args.Hin = args.crop_dim
args.Win = args.crop_dim
working_dir = os.path.join(os.getcwd(), 'data', dataset)
dataset_paths = {'train': os.path.join(working_dir,'train'),
'test': os.path.join(working_dir,'test')}
dataloaders = svhn(args, dataset_paths)
elif args.dataset == 'fashionmnist':
args.channels = 1
args.n_classes = 10
dataset = 'FashionMNIST'
args.padding = 4
args.Hin = args.crop_dim
args.Win = args.crop_dim
working_dir = os.path.join(os.getcwd(), 'data', dataset)
dataset_paths = {'train': os.path.join(working_dir,'train'),
'test': os.path.join(working_dir,'test')}
dataloaders = fashionmnist(args, dataset_paths)
elif args.dataset == 'cifar10':
args.channels = 3
args.n_classes = 10
dataset = 'CIFAR10'
args.padding = 4
args.Hin = args.crop_dim
args.Win = args.crop_dim
working_dir = os.path.join(os.getcwd(), 'data', dataset)
dataset_paths = {'train': os.path.join(working_dir,'train'),
'test': os.path.join(working_dir,'test')}
dataloaders = cifar10(args, dataset_paths)
return dataloaders['train'], dataloaders['valid'], dataloaders['test']
def smallnorb(args, dataset_paths):
transf = {'train': transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim)),
transforms.ColorJitter(brightness=args.brightness/255., contrast=args.contrast),
transforms.ToTensor(),
Standardize()]),
# transforms.Normalize((0.75239172, 0.75738262), (0.1758033 , 0.17200065))]),
'test': transforms.Compose([
transforms.ToPILImage(),
transforms.CenterCrop((args.crop_dim, args.crop_dim)),
transforms.ToTensor(),
Standardize()])}
# transforms.Normalize((0.75239172, 0.75738262), (0.1758033 , 0.17200065))])}
config = {'train': True, 'test': False}
datasets = {i: smallNORB(dataset_paths[i], transform=transf[i],
shuffle=config[i]) for i in config.keys()}
# return data, labels dicts for new train set and class-balanced valid set
data, labels = random_split(data=datasets['train'].data,
labels=datasets['train'].labels,
n_classes=5,
n_samples_per_class=np.unique(
datasets['train'].labels, return_counts=True)[1] // 5) # % of train set per class
# define transforms for train set (without valid data)
transf['train_'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim)),
transforms.ColorJitter(brightness=args.brightness/255., contrast=args.contrast),
transforms.ToTensor(),
Standardize()])
# transforms.Normalize((0.75239172, 0.75738262), (0.1758033 , 0.17200065))])
# define transforms for class-balanced valid set
transf['valid'] = transforms.Compose([
transforms.ToPILImage(),
transforms.CenterCrop((args.crop_dim, args.crop_dim)),
transforms.ToTensor(),
Standardize()])
# transforms.Normalize((0.75239172, 0.75738262), (0.1758033 , 0.17200065))])
# save original full training set
datasets['train_valid'] = datasets['train']
# make new training set without validation samples
datasets['train'] = CustomDataset(data=data['train'],
labels=labels['train'], transform=transf['train_'])
# make class balanced validation set
datasets['valid'] = CustomDataset(data=data['valid'],
labels=labels['valid'], transform=transf['valid'])
config = {'train': True, 'train_valid': True,
'valid': False, 'test': False}
dataloaders = {i: DataLoader(datasets[i], shuffle=config[i], pin_memory=True,
num_workers=args.num_workers, batch_size=args.batch_size) for i in config.keys()}
return dataloaders
class smallNORB(Dataset):
''' In:
data_path (string): path to the dataset split folder, i.e. train/valid/test
transform (callable, optional): transform to be applied on a sample.
Out:
sample (dict): sample data and respective label'''
def __init__(self, data_path, shuffle=True, transform=None):
self.data_path = data_path
self.shuffle = shuffle
self.transform = transform
self.data, self.labels = [], []
# get path for each class folder
for class_label_idx, class_name in enumerate(os.listdir(data_path)):
class_path = os.path.join(data_path, class_name)
# get name of each file per class and respective class name/label index
for _, file_name in enumerate(os.listdir(class_path)):
img = np.load(os.path.join(data_path, class_name, file_name))
# Out ← [H, W, C] ← [C, H, W]
if img.shape[0] < img.shape[1]:
img = np.moveaxis(img, 0, -1)
self.data.extend([img])
self.labels.append(class_label_idx)
self.data = np.array(self.data, dtype=np.uint8)
self.labels = np.array(self.labels, dtype=np.int64)
if self.shuffle:
# shuffle the dataset
idx = np.random.permutation(self.data.shape[0])
self.data = self.data[idx]
self.labels = self.labels[idx]
def __len__(self):
return self.data.shape[0]
def __getitem__(self, idx):
if self.transform:
image = self.transform(self.data[idx])
return image, self.labels[idx] # (X, Y)
def mnist(args, dataset_paths):
''' Loads the MNIST dataset.
Returns: train/valid/test set split dataloaders.
'''
transf = {'train': transforms.Compose([
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ToTensor(),
transforms.Normalize((0.13066047,), (0.30810780,))
# transforms.Normalize((0.1307,), (0.3081,))
]),
'test': transforms.Compose([
transforms.Pad(np.maximum(0, (args.crop_dim-28) // 2)),
transforms.ToTensor(),
transforms.Normalize((0.13066047,), (0.30810780,))
# transforms.Normalize((0.1307,), (0.3081,))
])}
config = {'train': True, 'test': False}
datasets = {i: torchvision.datasets.MNIST(root=dataset_paths[i], transform=transf[i],
train=config[i], download=True) for i in config.keys()}
# split train into train and class-balanced valid set
data, labels = random_split(data=datasets['train'].data,
labels=datasets['train'].targets,
n_classes=10,
n_samples_per_class=np.repeat(500, 10)) # 500 per class
# define transforms for train set (without valid data)
transf['train_'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ToTensor(),
transforms.Normalize((0.13066047,), (0.30810780,))
])
# define transforms for class-balanced valid set
transf['valid'] = transforms.Compose([
transforms.ToPILImage(),
transforms.Pad(np.maximum(0, (args.crop_dim-28) // 2)),
transforms.ToTensor(),
transforms.Normalize((0.13066047,), (0.30810780,))
])
# save original full training set
datasets['train_valid'] = datasets['train']
# make new training set without validation samples
datasets['train'] = CustomDataset(data=data['train'],
labels=labels['train'], transform=transf['train_'])
# make class balanced validation set
datasets['valid'] = CustomDataset(data=data['valid'],
labels=labels['valid'], transform=transf['valid'])
config = {'train': True, 'train_valid': True,
'valid': False, 'test': False}
dataloaders = {i: DataLoader(datasets[i], num_workers=args.num_workers, pin_memory=True,
batch_size=args.batch_size, shuffle=config[i]) for i in config.keys()}
if args.test_affNIST:
working_dir = os.path.join(os.path.split(os.getcwd())[0], 'data', 'affNIST')
aff_transf = transforms.Compose([
transforms.ToPILImage(),
transforms.ToTensor(),
transforms.Normalize((0.13066047,), (0.30810780,))])
datasets['affNIST_test'] = affNIST(data_path=os.path.join(working_dir,'test'),
transform=aff_transf)
dataloaders['affNIST_test'] = DataLoader(datasets['affNIST_test'], pin_memory=True,
num_workers=args.num_workers, batch_size=args.batch_size, shuffle=False)
return dataloaders
def svhn(args, dataset_paths):
''' Loads the SVHN dataset.
Returns: train/valid/test set split dataloaders.
'''
transf = {
'train': transforms.Compose([
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ColorJitter(brightness=args.brightness, contrast=args.contrast),
transforms.ToTensor(),
# Standardize()]),
transforms.Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))]),
# 'extra': transforms.Compose([
# transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
# transforms.ColorJitter(brightness=args.brightness, contrast=args.contrast),
# transforms.ToTensor(),
# # Standardize()]),
# transforms.Normalize((0.4376821, 0.4437697, 0.47280442),
# (0.19803012, 0.20101562, 0.19703614)),
'test': transforms.Compose([
transforms.ToTensor(),
# Standardize()])}
transforms.Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))])
}
# config = {'train': True, 'extra': True, 'test': False}
config = {'train': True, 'test': False}
datasets = {i: torchvision.datasets.SVHN(root=dataset_paths[i], transform=transf[i],
split=i, download=True) for i in config.keys()}
# weighted sampler weights for full(f) training set
f_s_weights = sample_weights(datasets['train'].labels)
# print(np.repeat(1000, 10).reshape(-1))
#
# exit()
# return data, labels dicts for new train set and class-balanced valid set
data, labels = random_split(data=datasets['train'].data,
labels=datasets['train'].labels,
n_classes=10,
n_samples_per_class=np.repeat(1000, 10).reshape(-1))
# define transforms for train set (without valid data)
transf['train_'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ColorJitter(brightness=args.brightness, contrast=args.contrast),
transforms.ToTensor(),
# Standardize()])
transforms.Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))])
# define transforms for class-balanced valid set
transf['valid'] = transforms.Compose([
transforms.ToPILImage(),
transforms.ToTensor(),
# Standardize()])
transforms.Normalize((0.4376821, 0.4437697, 0.47280442),
(0.19803012, 0.20101562, 0.19703614))])
# save original full training set
datasets['train_valid'] = datasets['train']
# make channels last and convert to np arrays
data['train'] = np.moveaxis(np.array(data['train']), 1, -1)
data['valid'] = np.moveaxis(np.array(data['valid']), 1, -1)
# make new training set without validation samples
datasets['train'] = CustomDataset(data=data['train'],
labels=labels['train'], transform=transf['train_'])
# make class balanced validation set
datasets['valid'] = CustomDataset(data=data['valid'],
labels=labels['valid'], transform=transf['valid'])
# weighted sampler weights for new training set
s_weights = sample_weights(datasets['train'].labels)
config = {
'train': WeightedRandomSampler(s_weights,
num_samples=len(s_weights), replacement=True),
'train_valid': WeightedRandomSampler(f_s_weights,
num_samples=len(f_s_weights), replacement=True),
'valid': None, 'test': None}
dataloaders = {i: DataLoader(datasets[i], sampler=config[i],
num_workers=args.num_workers, pin_memory=True, drop_last=True,
batch_size=args.batch_size) for i in config.keys()}
#NOTE: comment these to use the weighted sampler dataloaders above instead
config = {'train': True, 'train_valid': True,
'valid': False, 'test': False}
dataloaders = {i: DataLoader(datasets[i], num_workers=args.num_workers, pin_memory=True,
batch_size=args.batch_size, shuffle=config[i]) for i in config.keys()}
return dataloaders
def fashionmnist(args, dataset_paths):
''' Loads the Fashion-MNIST dataset.
Returns: train/valid/test set split dataloaders.
'''
transf = {
'train': transforms.Compose([
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
# transforms.ColorJitter(brightness=args.brightness, contrast=args.contrast),
transforms.ToTensor(),
# Standardize()]),
transforms.Normalize((0.2860406,), (0.3530242,))
]),
'test': transforms.Compose([
transforms.Pad(padding=(args.crop_dim - 28) // 2),
transforms.ToTensor(),
# Standardize()])}
transforms.Normalize((0.2860406,), (0.3530242,))
])
}
# config = {'train': True, 'extra': True, 'test': False}
config = {'train': True, 'test': False}
datasets = {i: torchvision.datasets.FashionMNIST(root=dataset_paths[i], transform=transf[i],
train=config[i], download=True) for i in config.keys()}
# split train into train and class-balanced valid set
data, labels = random_split(data=datasets['train'].data,
labels=datasets['train'].targets,
n_classes=10,
n_samples_per_class=np.repeat(500, 10)) # 500 per class
# define transforms for train set (without valid data)
transf['train_'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ToTensor(),
transforms.Normalize((0.2860406,), (0.3530242,))
])
# define transforms for class-balanced valid set
transf['valid'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.ToTensor(),
transforms.Normalize((0.2860406,), (0.3530242,))
])
# transf['train_'] = transf['train']
# transf['valid'] = transf['train']
# save original full training set
datasets['train_valid'] = datasets['train']
# make new training set without validation samples
datasets['train'] = CustomDataset(data=data['train'],
labels=labels['train'], transform=transf['train_'])
# make class balanced validation set
datasets['valid'] = CustomDataset(data=data['valid'],
labels=labels['valid'], transform=transf['valid'])
config = {'train': True, 'train_valid': True,
'valid': False, 'test': False}
dataloaders = {i: DataLoader(datasets[i], num_workers=args.num_workers, pin_memory=True,
batch_size=args.batch_size, shuffle=config[i]) for i in config.keys()}
return dataloaders
def cifar10(args, dataset_paths):
''' Loads the CIFAR-10 dataset.
Returns: train/valid/test set split dataloaders.
'''
transf = {
'train': transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
# transforms.ColorJitter(brightness=args.brightness, contrast=args.contrast),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
# Standardize()]),
transforms.Normalize((0.4913997, 0.4821584, 0.4465309),
(0.2470322, 0.2434851, 0.2615878)),
]),
'test': transforms.Compose([
transforms.ToTensor(),
# Standardize()])}
transforms.Normalize((0.4913997, 0.4821584, 0.4465309),
(0.2470322, 0.2434851, 0.2615878))
])
}
# config = {'train': True, 'extra': True, 'test': False}
config = {'train': True, 'test': False}
datasets = {i: torchvision.datasets.CIFAR10(root=dataset_paths[i], transform=transf[i],
train=config[i], download=True) for i in config.keys()}
# print(datasets['train'][0])
# exit()
datasets['train'].targets = torch.LongTensor(datasets['train'].targets)
datasets['test'].targets = torch.LongTensor(datasets['test'].targets)
# split train into train and class-balanced valid set
data, labels = random_split(data=datasets['train'].data,
labels=datasets['train'].targets,
n_classes=10,
n_samples_per_class=np.repeat(500, 10)) # 500 per class
# define transforms for train set (without valid data)
transf['train_'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize((0.4913997, 0.4821584, 0.4465309),
(0.2470322, 0.2434851, 0.2615878)),
])
# define transforms for class-balanced valid set
transf['valid'] = transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop((args.crop_dim, args.crop_dim), padding=args.padding),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize((0.4913997, 0.4821584, 0.4465309),
(0.2470322, 0.2434851, 0.2615878)),
])
# transf['train_'] = transf['train']
# transf['valid'] = transf['train']
# save original full training set
datasets['train_valid'] = datasets['train']
# make new training set without validation samples
datasets['train'] = CustomDataset(data=data['train'],
labels=labels['train'], transform=transf['train_'])
# make class balanced validation set
datasets['valid'] = CustomDataset(data=data['valid'],
labels=labels['valid'], transform=transf['valid'])
config = {'train': True, 'train_valid': True,
'valid': False, 'test': False}
dataloaders = {i: DataLoader(datasets[i], num_workers=args.num_workers, pin_memory=True,
batch_size=args.batch_size, shuffle=config[i]) for i in config.keys()}
return dataloaders