-
Notifications
You must be signed in to change notification settings - Fork 4
/
datasets.py
894 lines (677 loc) · 30.1 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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
import torch
import torch.utils.data as data
from PIL import Image
import numpy as np
from torchvision.datasets import MNIST, EMNIST, CIFAR10
from torchvision.datasets import DatasetFolder, ImageFolder
from torchvision import transforms
from PIL import Image
import os
import os.path
import sys
import logging
import pickle
import copy
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 EMNIST_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):
emnist_dataobj = EMNIST(self.root, split="digits", train=self.train,
transform=self.transform,
target_transform=self.target_transform,
download=self.download)
if self.train:
data = emnist_dataobj.train_data
target = emnist_dataobj.train_labels
else:
data = emnist_dataobj.test_data
target = emnist_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)
def get_ardis_dataset():
# load the data from csv's
ardis_images=np.loadtxt('./data/ARDIS/ARDIS_train_2828.csv', dtype='float')
ardis_labels=np.loadtxt('./data/ARDIS/ARDIS_train_labels.csv', dtype='float')
#### reshape to be [samples][width][height]
ardis_images = ardis_images.reshape(ardis_images.shape[0], 28, 28).astype('float32')
# labels are one-hot encoded
indices_seven = np.where(ardis_labels[:,7] == 1)[0]
images_seven = ardis_images[indices_seven,:]
images_seven = torch.tensor(images_seven).type(torch.uint8)
labels_seven = torch.tensor([7 for y in ardis_labels])
ardis_dataset = EMNIST('./data', split="digits", train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
]))
ardis_dataset.data = images_seven
ardis_dataset.targets = labels_seven
return ardis_dataset
def get_southwest_dataset(attack_case='normal-case'):
if attack_case == 'normal-case':
with open('./saved_datasets/southwest_images_honest_full_normal.pkl', 'rb') as train_f:
saved_southwest_dataset_train = pickle.load(train_f)
elif attack_case == 'almost-edge-case':
with open('./saved_datasets/southwest_images_honest_almost_edge_case.pkl', 'rb') as train_f:
saved_southwest_dataset_train = pickle.load(train_f)
else:
saved_southwest_dataset_train = None
return saved_southwest_dataset_train
class EMNIST_NormalCase_truncated(data.Dataset):
'''
we use this class for normal case attack where normal
users also hold the poisoned data point with true label
'''
def __init__(self, root,
dataidxs=None,
train=True,
transform=None,
target_transform=None,
download=False,
user_id=0,
num_total_users=3383,
poison_type="ardis",
ardis_dataset_train=None,
attack_case='normal-case'):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform = target_transform
self.download = download
if attack_case == 'normal-case':
self._num_users_hold_edge_data = int(3383/20) # we allow 1/20 of the users (other than the attacker) to hold the edge data.
else:
# almost edge case
self._num_users_hold_edge_data = 66 # ~2% of users hold data
if poison_type == "ardis":
self.ardis_dataset_train = ardis_dataset_train
partition = np.array_split(np.arange(self.ardis_dataset_train.data.shape[0]), int(self._num_users_hold_edge_data))
if user_id in np.arange(self._num_users_hold_edge_data):
user_partition = partition[user_id]
self.saved_ardis_dataset_train = self.ardis_dataset_train.data[user_partition]
self.saved_ardis_label_train = self.ardis_dataset_train.targets[user_partition]
else:
user_partition = []
self.saved_ardis_dataset_train = self.ardis_dataset_train.data[user_partition]
self.saved_ardis_label_train = self.ardis_dataset_train.targets[user_partition]
else:
NotImplementedError("Unsupported poison type for normal case attack ...")
# logging.info("USER: {} got {} points".format(user_id, len(self.saved_ardis_dataset_train.data)))
self.data, self.target = self.__build_truncated_dataset__()
#if self.dataidxs is not None:
# print("$$$$$$$$ Inside data loader: user ID: {}, Combined data: {}, Ori data shape: {}".format(
# user_id, self.data.shape, len(dataidxs)))
def __build_truncated_dataset__(self):
emnist_dataobj = EMNIST(self.root, split="digits", train=self.train,
transform=self.transform,
target_transform=self.target_transform,
download=self.download)
if self.train:
data = emnist_dataobj.data
target = np.array(emnist_dataobj.targets)
else:
data = emnist_dataobj.data
target = np.array(emnist_dataobj.targets)
if self.dataidxs is not None:
data = data[self.dataidxs]
target = target[self.dataidxs]
data = np.append(data, self.saved_ardis_dataset_train, axis=0)
target = np.append(target, self.saved_ardis_label_train, axis=0)
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]
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 TinyImageNet_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):
# tinyimagenet_dataobj = TinyImageNet(self.root, self.train, self.transform, self.target_transform, self.download)
tinyimagenet_dataobj = ImageFolder(self.root)
# if self.dataidxs is not None:
# images = [images[i] for i in self.dataidxs]
# data = []
# target = []
# for img_path, target_class in images:
# with open(img_path, 'rb') as f:
# img = Image.open(f).convert('RGB')
# if self.transform is not None:
# img = self.transform(img)
# data.append(img)
# target.append(target_class)
# return data, target
if self.train:
data = tinyimagenet_dataobj.data
target = np.array(tinyimagenet_dataobj.targets)
else:
data = tinyimagenet_dataobj.data
target = np.array(tinyimagenet_dataobj.targets)
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]
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 CIFAR10NormalCase_truncated(data.Dataset):
'''
we use this class for normal case attack where normal
users also hold the poisoned data point with true label
'''
def __init__(self, root,
dataidxs=None,
train=True,
transform=None,
target_transform=None,
download=False,
user_id=0,
num_total_users=200,
poison_type="southwest",
ardis_dataset_train=None,
attack_case="normal-case"):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform = transform
self.target_transform = target_transform
self.download = download
self._DA_ratio = 4 # we hard code this argument for now
if attack_case == "normal-case":
self._num_users_hold_edge_data = 10 # we allow 5% of the users (other than the attacker) to hold the edge data.
elif attack_case == "almost-edge-case":
self._num_users_hold_edge_data = 5 # we allow 2.5% of the users (other than the attacker) to hold the edge data.
else:
NotImplementedError("Unsupported attacking case ...")
self.saved_southwest_dataset_train = copy.deepcopy(ardis_dataset_train)
if poison_type == "southwest":
partition = np.array_split(np.arange(int(self.saved_southwest_dataset_train.shape[0]/self._DA_ratio)),
int(self._num_users_hold_edge_data))
self.__aggregated_mapped_user_partition = []
# the maped sampling thing will happen here:
# we just generate `self.__aggregated_mapped_user_partition` once
prev_user_counter = 0
for bi_index, bi in enumerate(partition):
mapped_user_partition = []
for idx, up in enumerate(bi):
mapped_user_partition.extend([prev_user_counter+idx*self._DA_ratio+i for i in range(self._DA_ratio)])
prev_user_counter += len(bi)*self._DA_ratio
self.__aggregated_mapped_user_partition.append(mapped_user_partition)
if user_id in np.arange(self._num_users_hold_edge_data):
user_partition = self.__aggregated_mapped_user_partition[user_id]
print("######### user_partition: {}, user id: {}".format(user_partition, user_id))
self.saved_southwest_dataset_train = self.saved_southwest_dataset_train[user_partition, :, :, :]
self.saved_southwest_label_train = 0 * np.ones((self.saved_southwest_dataset_train.shape[0],), dtype =int)
else:
user_partition = []
self.saved_southwest_dataset_train = self.saved_southwest_dataset_train[user_partition, :, :, :]
self.saved_southwest_label_train = 0 * np.ones((self.saved_southwest_dataset_train.shape[0],), dtype =int)
else:
NotImplementedError("Unsupported poison type for normal case attack ...")
self.data, self.target = self.__build_truncated_dataset__()
#if self.dataidxs is not None:
# print("$$$$$$$$ Inside data loader: user ID: {}, Combined data: {}, Ori data shape: {}".format(
# user_id, self.data.shape, len(dataidxs)))
def __build_truncated_dataset__(self):
cifar_dataobj = CIFAR10(self.root, self.train, self.transform, self.target_transform, self.download)
if self.train:
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]
data = np.append(data, self.saved_southwest_dataset_train, axis=0)
target = np.append(target, self.saved_southwest_label_train, axis=0)
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]
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_Poisoned(data.Dataset):
"""
The main motivation for this object is to adopt different transform on the mixed poisoned dataset:
e.g. there are `M` good examples and `N` poisoned examples in the poisoned dataset.
"""
def __init__(self, root, clean_indices, poisoned_indices, dataidxs=None, train=True, transform_clean=None,
transform_poison=None, target_transform=None, download=False):
self.root = root
self.dataidxs = dataidxs
self.train = train
self.transform_clean = transform_clean
self.transform_poison = transform_poison
self.target_transform = target_transform
self.download = download
self._clean_indices = clean_indices
self._poisoned_indices = poisoned_indices
cifar_dataobj = CIFAR10(self.root, self.train, self.transform_clean, self.target_transform, self.download)
self.data = cifar_dataobj.data
self.target = np.array(cifar_dataobj.targets)
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]
# we always assume that the transform function is not None
if index in self._clean_indices:
img = self.transform_clean(img)
elif index in self._poisoned_indices:
img = self.transform_poison(img)
else:
raise NotImplementedError("Indices should be in clean or poisoned!")
#if index in 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)
# we probably don't need to truncate the 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
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.__build_truncated_dataset__()
self._train_labels = np.array([tup[-1] for tup in self.imgs])
def __build_truncated_dataset__(self):
if self.dataidxs is not None:
#self.imgs = self.imgs[self.dataidxs]
# try:
self.imgs = [self.imgs[idx] for idx in self.dataidxs]
# except Exception as e:
# import IPython
# IPython.embed()
# print(e)
# exit(0)
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