This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathdatasets.py
436 lines (330 loc) · 13.9 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
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
import torch.utils.data as data
from PIL import Image
import numpy as np
from torchvision.datasets import MNIST, CIFAR10
from torchvision.datasets import DatasetFolder
from PIL import Image
import os
import os.path
import sys
import logging
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
def accimage_loader(path):
import accimage
try:
return accimage.Image(path)
except IOError:
# Potentially a decoding problem, fall back to PIL.Image
return pil_loader(path)
def pil_loader(path):
# open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
def default_loader(path):
from torchvision import get_image_backend
if get_image_backend() == 'accimage':
return accimage_loader(path)
else:
return pil_loader(path)
class MNIST_truncated(data.Dataset):
def __init__(self, root, dataidxs=None, train=True, transform=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform = target_transform
self.download = download
self.data, self.target = self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
mnist_dataobj = MNIST(self.root, self.train, self.transform, self.target_transform, self.download)
if self.train:
data = mnist_dataobj.train_data
target = mnist_dataobj.train_labels
else:
data = mnist_dataobj.test_data
target = mnist_dataobj.test_labels
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
return data, target
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.target[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img.numpy(), mode='L')
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
def __len__(self):
return len(self.data)
class CIFAR10_truncated(data.Dataset):
def __init__(self, root, dataidxs=None, train=True, transform=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform = target_transform
self.download = download
self.data, self.target = self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
cifar_dataobj = CIFAR10(self.root, self.train, self.transform, self.target_transform, self.download)
if self.train:
#print("train member of the class: {}".format(self.train))
#data = cifar_dataobj.train_data
data = cifar_dataobj.data
target = np.array(cifar_dataobj.targets)
else:
data = cifar_dataobj.data
target = np.array(cifar_dataobj.targets)
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
return data, target
def truncate_channel(self, index):
for i in range(index.shape[0]):
gs_index = index[i]
self.data[gs_index, :, :, 1] = 0.0
self.data[gs_index, :, :, 2] = 0.0
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.target[index]
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
def __len__(self):
return len(self.data)
class CIFAR10ColorGrayScale(data.Dataset):
def __init__(self, root, dataidxs=None, train=True, transform_color=None, transofrm_gray_scale=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform_color = transform_color
self.transofrm_gray_scale = transofrm_gray_scale
self.target_transform = target_transform
self.download = download
self._gray_scale_indices = []
self.data, self.target = self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
cifar_dataobj = CIFAR10(self.root, self.train, None, self.target_transform, self.download)
if self.train:
#print("train member of the class: {}".format(self.train))
#data = cifar_dataobj.train_data
data = cifar_dataobj.data
target = np.array(cifar_dataobj.targets)
else:
data = cifar_dataobj.data
target = np.array(cifar_dataobj.targets)
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
return data, target
def truncate_channel(self, index):
self._gray_scale_indices = index
for i in range(index.shape[0]):
gs_index = index[i]
self.data[gs_index, :, :, 1] = self.data[gs_index, :, :, 0]
self.data[gs_index, :, :, 2] = self.data[gs_index, :, :, 0]
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.target[index]
#if self.transform is not None:
if index in self._gray_scale_indices:
if self.transofrm_gray_scale is not None:
img = self.transofrm_gray_scale(img)
else:
if self.transform_color is not None:
img = self.transform_color(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.data)
class CIFAR10ColorGrayScaleTruncated(data.Dataset):
def __init__(self, root, dataidxs=None, gray_scale_indices=None,
train=True, transform_color=None, transofrm_gray_scale=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform_color = transform_color
self.transofrm_gray_scale = transofrm_gray_scale
self.target_transform = target_transform
self._gray_scale_indices = gray_scale_indices
self.download = download
self.cifar_dataobj = CIFAR10(self.root, self.train, None, self.target_transform, self.download)
# we need to trunc the channle first
self.__truncate_channel__(index=gray_scale_indices)
# then we trunct he dataset
self.data, self.target = self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
if self.train:
data = self.cifar_dataobj.data
target = np.array(self.cifar_dataobj.targets)
else:
data = self.cifar_dataobj.data
target = np.array(self.cifar_dataobj.targets)
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
return data, target
def __truncate_channel__(self, index):
#self._gray_scale_indices = index
for i in range(index.shape[0]):
gs_index = index[i]
self.cifar_dataobj.data[gs_index, :, :, 1] = self.cifar_dataobj.data[gs_index, :, :, 0]
self.cifar_dataobj.data[gs_index, :, :, 2] = self.cifar_dataobj.data[gs_index, :, :, 0]
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.target[index]
#if self.transform is not None:
if index in self._gray_scale_indices:
if self.transofrm_gray_scale is not None:
img = self.transofrm_gray_scale(img)
else:
if self.transform_color is not None:
img = self.transform_color(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.data)
class CIFAR10ColorGrayScaleOverSampled(data.Dataset):
'''
Here we conduct oversampling strategy (over the underrepresented domain) in mitigating the data bias
'''
def __init__(self, root, dataidxs=None, gray_scale_indices=None,
train=True, transform_color=None, transofrm_gray_scale=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform_color = transform_color
self.transofrm_gray_scale = transofrm_gray_scale
self.target_transform = target_transform
self._gray_scale_indices = gray_scale_indices
self.download = download
self.cifar_dataobj = CIFAR10(self.root, self.train, None, self.target_transform, self.download)
# we need to trunc the channle first
self.__truncate_channel__(index=gray_scale_indices)
# then we trunct he dataset
self.data, self.target = self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
if self.train:
data = self.cifar_dataobj.data
target = np.array(self.cifar_dataobj.targets)
else:
data = self.cifar_dataobj.data
target = np.array(self.cifar_dataobj.targets)
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
return data, target
def __truncate_channel__(self, index):
#self._gray_scale_indices = index
for i in range(index.shape[0]):
gs_index = index[i]
self.cifar_dataobj.data[gs_index, :, :, 1] = self.cifar_dataobj.data[gs_index, :, :, 0]
self.cifar_dataobj.data[gs_index, :, :, 2] = self.cifar_dataobj.data[gs_index, :, :, 0]
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.target[index]
#if self.transform is not None:
if index in self._gray_scale_indices:
if self.transofrm_gray_scale is not None:
img = self.transofrm_gray_scale(img)
else:
if self.transform_color is not None:
img = self.transform_color(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
def __len__(self):
return len(self.data)
class ImageFolderTruncated(DatasetFolder):
"""A generic data loader where the images are arranged in this way: ::
root/dog/xxx.png
root/dog/xxy.png
root/dog/xxz.png
root/cat/123.png
root/cat/nsdf3.png
root/cat/asd932_.png
Args:
root (string): Root directory path.
transform (callable, optional): A function/transform that takes in an PIL image
and returns a transformed version. E.g, ``transforms.RandomCrop``
target_transform (callable, optional): A function/transform that takes in the
target and transforms it.
loader (callable, optional): A function to load an image given its path.
is_valid_file (callable, optional): A function that takes path of an Image file
and check if the file is a valid_file (used to check of corrupt files)
Attributes:
classes (list): List of the class names.
class_to_idx (dict): Dict with items (class_name, class_index).
imgs (list): List of (image path, class_index) tuples
"""
def __init__(self, root, dataidxs=None, transform=None, target_transform=None,
loader=default_loader, is_valid_file=None):
super(ImageFolderTruncated, self).__init__(root, loader, IMG_EXTENSIONS if is_valid_file is None else None,
transform=transform,
target_transform=target_transform,
is_valid_file=is_valid_file)
self.imgs = self.samples
self.dataidxs = dataidxs
### we need to fetch training labels out here:
self._train_labels = np.array([tup[-1] for tup in self.imgs])
self.__build_truncated_dataset__()
def __build_truncated_dataset__(self):
if self.dataidxs is not None:
#self.imgs = self.imgs[self.dataidxs]
self.imgs = [self.imgs[idx] for idx in self.dataidxs]
def __len__(self):
return len(self.imgs)
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.imgs[index]
sample = self.loader(path)
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target
@property
def get_train_labels(self):
return self._train_labels