-
Notifications
You must be signed in to change notification settings - Fork 2
/
datasets.py
300 lines (241 loc) · 12.8 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
# ------------------------------------------
# Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
# ------------------------------------------
# Modification:
# Added code for Simple Continual Learning datasets
# -- Jaeho Lee, [email protected]
# ------------------------------------------
import random
import torch
from torch.utils.data.dataset import Subset
from torchvision import datasets, transforms
from timm.data import create_transform
from continual_datasets.continual_datasets import *
import utils
class Lambda(transforms.Lambda):
def __init__(self, lambd, nb_classes):
super().__init__(lambd)
self.nb_classes = nb_classes
def __call__(self, img):
return self.lambd(img, self.nb_classes)
def target_transform(x, nb_classes):
return x + nb_classes
def build_continual_dataloader(args):
dataloader = list()
class_mask = list() if args.task_inc or args.train_mask else None
transform_train = build_transform(True, args)
transform_val = build_transform(False, args)
print("Train transforms: ", transform_train)
print("Test transforms: ", transform_val)
if args.dataset.startswith('Split-'):
dataset_train, dataset_val, dataset_feat_train = get_dataset(args.dataset.replace('Split-',''), transform_train, transform_val, args)
args.nb_classes = len(dataset_val.classes)
splited_dataset, class_mask = split_single_dataset(dataset_train, dataset_val, args)
else:
if args.dataset == '5-datasets':
dataset_list = ['SVHN', 'MNIST', 'CIFAR10', 'NotMNIST', 'FashionMNIST']
else:
dataset_list = args.dataset.split(',')
if args.shuffle:
random.shuffle(dataset_list)
print(dataset_list)
args.nb_classes = 0
for i in range(args.num_tasks):
if args.dataset.startswith('Split-'):
dataset_train, dataset_val = splited_dataset[i]
else:
dataset_train, dataset_val, dataset_feat_train = get_dataset(dataset_list[i], transform_train, transform_val, args)
transform_target = Lambda(target_transform, args.nb_classes)
if class_mask is not None:
class_mask.append([i + args.nb_classes for i in range(len(dataset_val.classes))])
args.nb_classes += len(dataset_val.classes)
if not args.task_inc:
dataset_train.target_transform = transform_target
dataset_val.target_transform = transform_target
dataset_feat_train.target_transform = transform_target
if args.distributed and utils.get_world_size() > 1:
num_tasks = utils.get_world_size()
global_rank = utils.get_rank()
sampler_train = torch.utils.data.DistributedSampler(
dataset_train, num_replicas=num_tasks, rank=global_rank, shuffle=True)
sampler_val = torch.utils.data.SequentialSampler(dataset_val)
else:
sampler_train = torch.utils.data.RandomSampler(dataset_train)
sampler_val = torch.utils.data.SequentialSampler(dataset_val)
data_loader_train = torch.utils.data.DataLoader(
dataset_train, sampler=sampler_train,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
)
data_loader_val = torch.utils.data.DataLoader(
dataset_val, sampler=sampler_val,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
)
data_loader_feat_train = torch.utils.data.DataLoader(
dataset_feat_train, sampler=sampler_train,
batch_size=args.batch_size,
num_workers=args.num_workers,
pin_memory=args.pin_mem,
)
# print("Dataloader len: ", len(data_loader_val))
# for batch_number, batch in enumerate(data_loader_val):
# # Print the shape of the first element in the batch
# first_batch_item = batch[0]
# print("Shape of the first element in the batch:", first_batch_item.shape)
# print("Batch: ",batch)
# break
# exit(0)
dataloader.append({'train': data_loader_train, 'val': data_loader_val, 'feat_train': data_loader_feat_train})
return dataloader, class_mask
def get_dataset(dataset, transform_train, transform_val, args,):
if dataset == 'CIFAR100':
dataset_train = datasets.CIFAR100(args.data_path, train=True, download=True, transform=transform_train)
dataset_val = datasets.CIFAR100(args.data_path, train=False, download=True, transform=transform_val)
dataset_feat_train = datasets.CIFAR100(args.data_path, train=True, download=True, transform=transform_val)
elif dataset == 'CIFAR10':
dataset_train = datasets.CIFAR10(args.data_path, train=True, download=True, transform=transform_train)
dataset_val = datasets.CIFAR10(args.data_path, train=False, download=True, transform=transform_val)
elif dataset == 'MNIST':
dataset_train = MNIST_RGB(args.data_path, train=True, download=True, transform=transform_train)
dataset_val = MNIST_RGB(args.data_path, train=False, download=True, transform=transform_val)
elif dataset == 'FashionMNIST':
dataset_train = FashionMNIST(args.data_path, train=True, download=True, transform=transform_train)
dataset_val = FashionMNIST(args.data_path, train=False, download=True, transform=transform_val)
elif dataset == 'SVHN':
dataset_train = SVHN(args.data_path, split='train', download=True, transform=transform_train)
dataset_val = SVHN(args.data_path, split='test', download=True, transform=transform_val)
elif dataset == 'NotMNIST':
dataset_train = NotMNIST(args.data_path, train=True, download=True, transform=transform_train)
dataset_val = NotMNIST(args.data_path, train=False, download=True, transform=transform_val)
elif dataset == 'Flower102':
dataset_train = Flowers102(args.data_path, split='train', download=True, transform=transform_train)
dataset_val = Flowers102(args.data_path, split='test', download=True, transform=transform_val)
elif dataset == 'Cars196':
dataset_train = StanfordCars(args.data_path, split='train', download=True, transform=transform_train)
dataset_val = StanfordCars(args.data_path, split='test', download=True, transform=transform_val)
elif dataset == 'CUB200':
dataset_train = CUB200(args.data_path, train=True, download=True, transform=transform_train).data
dataset_val = CUB200(args.data_path, train=False, download=True, transform=transform_val).data
dataset_feat_train = CUB200(args.data_path, train=True, download=True, transform=transform_val).data
elif dataset == 'Scene67':
dataset_train = Scene67(args.data_path, train=True, download=True, transform=transform_train).data
dataset_val = Scene67(args.data_path, train=False, download=True, transform=transform_val).data
elif dataset == 'TinyImagenet':
dataset_train = TinyImagenet(args.data_path, train=True, download=True, transform=transform_train).data
dataset_val = TinyImagenet(args.data_path, train=False, download=True, transform=transform_val).data
elif dataset == 'Imagenet-R':
dataset_train = Imagenet_R(args.data_path, train=True, download=True, transform=transform_train).data
dataset_val = Imagenet_R(args.data_path, train=False, download=True, transform=transform_val).data
dataset_feat_train = Imagenet_R(args.data_path, train=True, download=True, transform=transform_val).data
else:
raise ValueError('Dataset {} not found.'.format(dataset))
return dataset_train, dataset_val, dataset_feat_train
def split_single_dataset(dataset_train, dataset_val, args, dataset_feat_train=None,):
nb_classes = len(dataset_val.classes)
assert nb_classes % args.num_tasks == 0
classes_per_task = nb_classes // args.num_tasks
labels = [i for i in range(nb_classes)]
split_datasets = list()
mask = list()
if args.shuffle:
random.shuffle(labels)
for _ in range(args.num_tasks):
train_split_indices = []
test_split_indices = []
feat_split_indices = []
scope = labels[:classes_per_task]
labels = labels[classes_per_task:]
mask.append(scope)
for k in range(len(dataset_train.targets)):
if int(dataset_train.targets[k]) in scope:
train_split_indices.append(k)
feat_split_indices.append(k)
for h in range(len(dataset_val.targets)):
if int(dataset_val.targets[h]) in scope:
test_split_indices.append(h)
subset_train, subset_val = Subset(dataset_train, train_split_indices), Subset(dataset_val, test_split_indices)
split_datasets.append([subset_train, subset_val])
return split_datasets, mask
# T.ColorJitter(brightness=.5, hue=.3),
# T.RandomPerspective(distortion_scale=0.6, p=1.0),
# T.RandomRotation(degrees=(0, 180)),
# T.RandomAffine(degrees=(30, 70), translate=(0.1, 0.3), scale=(0.5, 0.75)),
# T.RandomInvert(),
# T.RandomPosterize(bits=2),
# T.RandomSolarize(threshold=192.0),
# T.RandomAdjustSharpness(sharpness_factor=2),
# T.RandomAutocontrast(),
# T.RandomEqualize()
def build_transform(is_train, args):
resize_im = args.input_size > 32
if is_train:
scale = (0.05, 1.0)
ratio = (3. / 4., 4. / 3.)
transform = transforms.Compose([
transforms.RandomResizedCrop(args.input_size, scale=scale, ratio=ratio),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
])
if args.use_transform:
if "CUB" in args.dataset:
transform = transforms.Compose([
transforms.Resize((300, 300), interpolation=3),
transforms.RandomCrop((224, 224)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
elif "CIFAR" in args.dataset:
transform = transforms.Compose([
transforms.RandomResizedCrop(224, interpolation=3),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=63/255),
transforms.RandomPerspective(distortion_scale=0.6, p=1.0),
transforms.RandomRotation(degrees=(0, 180)),
transforms.RandomAffine(degrees=(30, 70), translate=(0.1, 0.3), scale=(0.5, 0.75)),
transforms.RandomInvert(),
transforms.RandomPosterize(bits=2),
transforms.RandomSolarize(threshold=192.0),
transforms.RandomAdjustSharpness(sharpness_factor=2),
transforms.RandomAutocontrast(),
transforms.RandomEqualize(),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5071, 0.4867, 0.4408), std=(0.2675, 0.2565, 0.2761)),
])
else:
transform = transforms.Compose([
transforms.RandomResizedCrop(224, interpolation=3),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
return transform
t = []
if resize_im:
size = int((256 / 224) * args.input_size)
t.append(
transforms.Resize(size, interpolation=3), # to maintain same ratio w.r.t. 224 images
)
t.append(transforms.CenterCrop(args.input_size))
t.append(transforms.ToTensor())
if args.use_transform:
if "CUB" in args.dataset:
t = [transforms.Resize(256, interpolation=3),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),]
elif "CIFAR" in args.dataset:
t = [transforms.Resize(256, interpolation=3),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=(0.5071, 0.4867, 0.4408), std=(0.2675, 0.2565, 0.2761)),]
else:
t = [transforms.Resize(256, interpolation=3),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),]
return transforms.Compose(t)