-
Notifications
You must be signed in to change notification settings - Fork 0
/
dataset.py
354 lines (276 loc) · 10.4 KB
/
dataset.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
import numpy as np
import torch
import torchvision
from PIL import Image
import os
from copy import deepcopy
import pickle
class CIFAR10Biaugment(torchvision.datasets.CIFAR10):
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.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
pil_img = Image.fromarray(img)
if self.transform is not None:
img = self.transform(pil_img)
img2 = self.transform(pil_img)
else:
img2 = img = pil_img
if self.target_transform is not None:
target = self.target_transform(target)
return (img, img2), target, index
class CIFAR100Biaugment(CIFAR10Biaugment):
"""`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
This is a subclass of the `CIFAR10Biaugment` Dataset.
"""
base_folder = 'cifar-100-python'
url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
filename = "cifar-100-python.tar.gz"
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
meta = {
'filename': 'meta',
'key': 'fine_label_names',
'md5': '7973b15100ade9c7d40fb424638fde48',
}
class STL10Biaugment(torchvision.datasets.STL10):
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
if self.labels is not None:
img, target = self.data[index], int(self.labels[index])
else:
img, target = self.data[index], None
# doing this so that it is consistent with all other datasets
# to return a PIL Image
pil_img = Image.fromarray(np.transpose(img, (1, 2, 0)))
if self.transform is not None:
img = self.transform(pil_img)
img2 = self.transform(pil_img)
else:
img2 = img = pil_img
if self.target_transform is not None:
target = self.target_transform(target)
return (img, img2), target, index
class CIFAR10Multiaugment(torchvision.datasets.CIFAR10):
def __init__(self, *args, n_augmentations=8, **kwargs):
super(CIFAR10Multiaugment, self).__init__(*args, **kwargs)
self.n_augmentations = n_augmentations
assert self.transforms is not None
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.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
pil_img = Image.fromarray(img)
imgs = [self.transform(pil_img) for _ in range(self.n_augmentations)]
if self.target_transform is not None:
target = self.target_transform(target)
return torch.stack(imgs, dim=0), target, index
class CIFAR100Multiaugment(CIFAR10Multiaugment):
"""`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
This is a subclass of the `CIFAR10Biaugment` Dataset.
"""
base_folder = 'cifar-100-python'
url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz"
filename = "cifar-100-python.tar.gz"
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
meta = {
'filename': 'meta',
'key': 'fine_label_names',
'md5': '7973b15100ade9c7d40fb424638fde48',
}
class ImageNetBiaugment(torchvision.datasets.ImageNet):
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
img = self.transform(sample)
img2 = self.transform(sample)
else:
img2 = img = sample
if self.target_transform is not None:
target = self.target_transform(target)
return (img, img2), target, index
class ImageFolderBiaugment(torchvision.datasets.ImageFolder):
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path)
if self.transform is not None:
img = self.transform(sample)
img2 = self.transform(sample)
else:
img2 = img = sample
if self.target_transform is not None:
target = self.target_transform(target)
return (img, img2), target, index
class SideInfomation:
def __init__(self, df_path):
self.df = pd.read_csv(df_path)
class AttributeImageDataset(torch.utils.data.Dataset):
'''
dataset for attribute neural selection
'''
def __init__(self, df, data_path, transform=None, num_attr=-1):
'''
label_known_mask: str, the column name of mask for whether the class labels are known
'''
self.df = df
self.attr_list = [i for i in self.df.columns if 'attr_val' in i]
self.attr_num = len(self.attr_list)
self.transform = transform
self.data_path = data_path
self.num_attr = num_attr
self.attr_list = self.rank_attributes(self.attr_list)
if self.num_attr > 0:
self.attr_list = self.attr_list[:self.num_attr]
if -1 in self.df.index:
self.df = df.drop([-1])
def rank_attributes(self, attr_list, method_='entropy'):
data = self.df.loc[:, attr_list]
if method_ == 'entropy':
entropy_attr = data.apply(lambda col: entropy(col), axis=0) # should be [num_of_attr]
sort_order = np.argsort(entropy_attr)[::-1]
attr_list_new = []
for i in sort_order:
attr_list_new.append(attr_list[i])
return attr_list
def __len__(self):
return len(self.df)
def __getitem__(self, index):
'''
if self.label_known_mask is set:
return attributes, class, mask
Note: mask: 1 indicate known, 0 indicate unknown
class: -1 for unknown, otherwise known.
else:
return attributes, -1, 0
'''
attributes = np.array(self.df.iloc[index][self.attr_list].tolist(), dtype='float32')
if self.num_attr >0:
attributes = attributes[:self.num_attr]
# img
img = Image.open(os.path.join(self.data_path, self.df.iloc[index]['path']))
img = deepcopy(img)
if not img.mode == 'RGB':
img = img.convert("RGB")
if self.transform:
img1 = self.transform(img)
img2 = self.transform(img)
return (img1, img2), attributes, index
# dataset for additional information conditioning
class CKSDataset(torch.utils.data.Dataset):
"""This dataset is particularly suitable for conditioning on additional continuous value
user should provide the file path, as well as the corresponding continuous vector accosicated with each image
"""
def __init__(self, transform=None, pickle_file_path="", root=None):
super(CKSDataset, self).__init__()
with open(pickle_file_path, 'rb') as f:
feature_file = pickle.load(f)
self.paths = feature_file[0] # list,
self.features = feature_file[1].astype(np.float32) # numpy array, [num_data, feature_dim]
self.transform = transform
self.root = root
def __len__(self):
return len(self.paths)
def __getitem__(self, idx):
# transform path
if self.root:
image_id = "/".join(self.paths[idx].split("/")[-2:])
path = os.path.join(self.root, image_id)
img = Image.open(path)
img = deepcopy(img)
if not img.mode == 'RGB':
img = img.convert("RGB")
if self.transform:
img1 = self.transform(img)
img2 = self.transform(img)
else:
img1 = img2 = img
feature_idx = self.features[idx]
return (img1, img2), feature_idx, idx
class ColorMNISTBiAugDataset(torch.utils.data.Dataset):
def __init__(self, root, split, transform=None, biaug=True, conditional=True, mask_lbl_percent=0.1):
super(ColorMNISTBiAugDataset, self).__init__()
self.root = root
self.split = split
self.transform = transform
self.biaug = biaug
self.conditional = conditional
# train
self.img = np.load(os.path.join(root, split, f'{split}_images.npy'))
self.label = np.load(os.path.join(root, split, f'{split}_labels.npy'))
self.color = np.load(os.path.join(root, split, f'{split}_augment_colors.npy'))
assert self.img.shape[0] == self.label.shape[0]
assert self.img.shape[0] == self.color.shape[0]
def __len__(self):
return self.img.shape[0]
def __getitem__(self, idx):
img = (self.img[idx] * 255).astype(np.uint8).transpose([1, 2, 0])
img = Image.fromarray(img)
lbl = self.label[idx]
color = self.color[idx].astype(np.float32)
if self.transform:
img1 = self.transform(img)
if self.biaug:
img2 = self.transform(img)
img = (img1, img2)
else:
img = img1
if self.conditional:
return img, lbl, torch.from_numpy(color)
else:
return img, lbl
# helper functions
def entropy(x):
'''
H(x)
'''
unique, count = np.unique(x, return_counts=True, axis=0)
prob = count/len(x)
H = np.sum((-1)*prob*np.log2(prob))
return H
def add_indices(dataset_cls):
class NewClass(dataset_cls):
def __getitem__(self, item):
output = super(NewClass, self).__getitem__(item)
return (*output, item)
return NewClass