-
Notifications
You must be signed in to change notification settings - Fork 5
/
dataloader.py
92 lines (79 loc) · 3.18 KB
/
dataloader.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
import os
import logging
import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
def _getCifarLoader(data, dataset, batch_size, workers):
traindir = os.path.join(data)
valdir = os.path.join(data)
if dataset == 'cifar10':
normalize = transforms.Normalize(mean=(0.4914, 0.4822, 0.4465),
std=(0.2023, 0.1994, 0.2010))
else:
normalize = transforms.Normalize(mean=(0.507, 0.487, 0.441),
std=(0.267, 0.256, 0.276))
logging.info('=> Preparing dataset %s' % dataset)
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize,
])
if dataset == 'cifar10':
dataloader = datasets.CIFAR10
num_classes = 10
else:
dataloader = datasets.CIFAR100
num_classes = 100
trainset = dataloader(root=traindir,
train=True,
download=False,
transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset,
batch_size=batch_size,
shuffle=True,
num_workers=workers)
testset = dataloader(root=valdir,
train=False,
download=False,
transform=transform_test)
testloader = torch.utils.data.DataLoader(testset,
batch_size=batch_size,
shuffle=False,
num_workers=workers)
return trainloader, testloader
def _getImageNetLoader(data, batch_size, workers):
traindir = os.path.join(data, 'train')
valdir = os.path.join(data, 'val')
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
train_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(traindir, transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.2, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size, shuffle=True,
num_workers=workers, pin_memory=True,
drop_last=True)
val_loader = torch.utils.data.DataLoader(
datasets.ImageFolder(valdir, transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size, shuffle=False,
num_workers=workers, pin_memory=True,
drop_last=True)
return train_loader, val_loader
def getDataLoader(data, dataset, batch_size, workers):
if dataset == 'imagenet':
return _getImageNetLoader(data, batch_size, workers)
else:
return _getCifarLoader(data, dataset, batch_size, workers)