Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

dataset_2loss.py 16 KB

You have to be logged in to leave a comment. Sign In
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
  1. # This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate
  2. import torch
  3. from PIL import Image
  4. import json
  5. import numpy as np
  6. import torchvision.transforms as transforms
  7. import os
  8. identity = lambda x:x
  9. import math
  10. from random import choices
  11. def get_patches(img, transform_jigsaw, transform_patch_jigsaw, permutations):
  12. if np.random.rand() < 0.30:
  13. img = img.convert('LA').convert('RGB')## this should be L instead....... need to change that!!
  14. # import ipdb; ipdb.set_trace()
  15. # if img.size[0] != 255:
  16. # img.save('img_ori.png')
  17. img = transform_jigsaw(img)
  18. s = float(img.size[0]) / 3
  19. # s = float(img.shape[1]) / 3
  20. a = s / 2
  21. tiles = [None] * 9
  22. # img.save('img.png')
  23. for n in range(9):
  24. i = int(n / 3)
  25. j = n % 3
  26. c = [a * i * 2 + a, a * j * 2 + a]
  27. c = np.array([math.ceil(c[1] - a), math.ceil(c[0] - a), int(c[1] + a ), int(c[0] + a )]).astype(int)
  28. tile = img.crop(c.tolist())
  29. # print(c)
  30. # tile.save(str(n)+'.png')
  31. # import ipdb; ipdb.set_trace()
  32. tile = transform_patch_jigsaw(tile)
  33. if tile.shape[1] != 64 and tile.shape[2] != 64:
  34. print(tile.shape)
  35. # Normalize the patches indipendently to avoid low level features shortcut
  36. try:
  37. m, s = tile.view(3, -1).mean(dim=1).numpy(), tile.view(3, -1).std(dim=1).numpy()
  38. except RuntimeError:
  39. print(tile.shape)
  40. exit(1)
  41. s[s == 0] = 1
  42. # import ipdb; ipdb.set_trace()
  43. norm = transforms.Normalize(mean=m.tolist(), std=s.tolist())
  44. ## Use original normalization
  45. # norm = transforms.Normalize(mean=[0.485, 0.456, 0.406],
  46. # std =[0.229, 0.224, 0.225])
  47. tile = norm(tile)
  48. tiles[n] = tile
  49. # import torchvision
  50. # torchvision.utils.save_image(norm(tile),'tile_'+str(n)+'.png')
  51. # norm = transforms.Normalize(mean=[0.485, 0.456, 0.406],
  52. # std =[0.229, 0.224, 0.225])
  53. # torchvision.utils.save_image(norm(tile),'tile_patch_'+str(n)+'.png')
  54. # import ipdb; ipdb.set_trace()
  55. order = np.random.randint(len(permutations))
  56. data = [tiles[permutations[order][t]] for t in range(9)]
  57. data = torch.stack(data, 0)
  58. return data, int(order)
  59. def retrive_permutations(classes):
  60. all_perm = np.load('data/permutations_%d.npy' % (classes))
  61. # from range [1,9] to [0,8]
  62. if all_perm.min() == 1:
  63. all_perm = all_perm - 1
  64. return all_perm
  65. def combine_jsons(files):
  66. meta = {'image_names': [], "image_labels": []}
  67. label_count = 0
  68. for file in files:
  69. with open(file, 'r') as f:
  70. data = json.load(f)
  71. meta['image_names'].extend(data["image_names"])
  72. image_labels = data["image_labels"]
  73. label_map = {}
  74. for label in list(set(image_labels)):
  75. label_map[label] = label_count
  76. label_count += 1
  77. for i,label in enumerate(image_labels):
  78. image_labels[i] = label_map[label]
  79. meta["image_labels"].extend(image_labels)
  80. return meta
  81. class SimpleDataset:
  82. def __init__(self, data_file, transform, target_transform=identity, \
  83. jigsaw=False, transform_jigsaw=None, transform_patch_jigsaw=None, \
  84. rotation=False, isAircraft=False, grey=False, return_name=False, low_res=False, image_size=None):
  85. if type(data_file) is list:
  86. self.meta = combine_jsons(data_file)
  87. else:
  88. with open(data_file, 'r') as f:
  89. self.meta = json.load(f)
  90. self.transform = transform
  91. self.target_transform = target_transform
  92. self.jigsaw = jigsaw
  93. self.transform_jigsaw = transform_jigsaw
  94. self.transform_patch_jigsaw = transform_patch_jigsaw
  95. self.permutations = retrive_permutations(35)
  96. self.rotation = rotation
  97. self.isAircraft = False#isAircraft
  98. self.grey = grey
  99. self.return_name = return_name
  100. self.low_res = low_res
  101. if self.low_res:
  102. self.low_res_transform = transforms.Compose(
  103. [
  104. transforms.Resize((image_size//4, image_size//4)),
  105. transforms.Resize((image_size, image_size))
  106. ]
  107. )
  108. def __getitem__(self,i):
  109. # import ipdb; ipdb.set_trace()
  110. # image_path = os.path.join(self.meta['image_names'][i].replace('images','images_lowres'))
  111. image_path = os.path.join(self.meta['image_names'][i])
  112. # image_path = os.path.join(self.meta['image_names'][i].replace('filelists/cars/images/','/data/jcsu/distill-net/data/cars/images_56_224/car_ims/'))
  113. # print(self.meta['image_names'][i])
  114. # import ipdb; ipdb.set_trace()
  115. # image_path = os.path.join(self.meta['image_names'][i].replace('/data/jcsu/CloserLookFewShot/filelists/CUB/CUB_200_2011/images/','/data/jcsu/distill-net/data/cub/images_lowres_full_50_224/'))
  116. # print(image_path)
  117. # exit(0)
  118. if self.grey:
  119. img = Image.open(image_path).convert('L').convert('RGB')
  120. else:
  121. img = Image.open(image_path).convert('RGB')
  122. if self.low_res:
  123. img = self.low_res_transform(img)
  124. # if self.isAircraft:
  125. # ## crop the banner
  126. # img = img.crop((0,0,img.size[0],img.size[1]-20))
  127. if self.jigsaw:
  128. patches, order = get_patches(img, self.transform_jigsaw, self.transform_patch_jigsaw, self.permutations)
  129. if self.rotation:
  130. rotated_imgs = [
  131. self.transform(img),
  132. self.transform(img.rotate(90,expand=True)),
  133. self.transform(img.rotate(180,expand=True)),
  134. self.transform(img.rotate(270,expand=True))
  135. ]
  136. rotation_labels = torch.LongTensor([0, 1, 2, 3])
  137. img = self.transform(img)
  138. target = self.target_transform(self.meta['image_labels'][i])
  139. if self.jigsaw and self.rotation:
  140. return img, target, patches, order, torch.stack(rotated_imgs, dim=0), rotation_labels
  141. elif self.jigsaw:
  142. if self.return_name:
  143. return img, target, patches, order, image_path
  144. else:
  145. return img, target, patches, order
  146. elif self.rotation:
  147. if self.return_name:
  148. return img, target, torch.stack(rotated_imgs, dim=0), rotation_labels, image_path
  149. else:
  150. return img, target, torch.stack(rotated_imgs, dim=0), rotation_labels
  151. else:
  152. if self.return_name:
  153. return img, target, image_path
  154. else:
  155. return img, target
  156. def __len__(self):
  157. return len(self.meta['image_names'])
  158. class SetDataset:
  159. def __init__(self, data_file, batch_size, transform, jigsaw=False, \
  160. transform_jigsaw=None, transform_patch_jigsaw=None, transform_rotation=None, rotation=False, isAircraft=False, grey=False, low_res=False, image_size=None, sup_ratio=1.0, semi_sup=False):
  161. self.jigsaw = jigsaw
  162. self.transform_jigsaw = transform_jigsaw
  163. self.transform_patch_jigsaw = transform_patch_jigsaw
  164. self.rotation = rotation
  165. self.isAircraft = isAircraft
  166. self.grey = grey
  167. self.low_res = low_res
  168. self.semi_sup = semi_sup
  169. self.transform_rotation = transform_rotation
  170. if type(data_file) is list:
  171. self.meta = combine_jsons(data_file)
  172. else:
  173. with open(data_file, 'r') as f:
  174. self.meta = json.load(f)
  175. self.cl_list = np.unique(self.meta['image_labels']).tolist()
  176. self.sub_meta = {}
  177. for cl in self.cl_list:
  178. self.sub_meta[cl] = []
  179. for x,y in zip(self.meta['image_names'],self.meta['image_labels']):
  180. self.sub_meta[y].append(x)
  181. # # remove from cl_list also
  182. # for cl in self.cl_list.copy():
  183. # print(cl, len(self.sub_meta[cl]))
  184. # if len(self.sub_meta[cl]) < batch_size:
  185. # print(len(self.sub_meta[cl]), " Removing ", cl)
  186. # self.cl_list.remove(cl)
  187. # self.sub_meta.pop(cl)
  188. if sup_ratio < 1.0:
  189. print("sup ratio: %0.2f; self-sup ratio: %0.2f" % (sup_ratio, 1-sup_ratio))
  190. self.sub_meta_self_sup = {}
  191. for y in self.cl_list:
  192. self_sup_indices = choices(list(range(0, len(self.sub_meta[y]))), k=int(1-sup_ratio) * len(self.sub_meta[y]))
  193. self.sub_meta_self_sup[y] = [self.sub_meta[y][x] for x in self_sup_indices]
  194. self.sub_meta[y] = [x for i, x in enumerate(self.sub_meta[y]) if i not in self_sup_indices]
  195. if semi_sup:
  196. print("semi_sup called in dataset_2loss")
  197. self.sub_meta_semi_sup = {}
  198. for y in self.cl_list:
  199. semi_sup_indices = choices(list(range(0, len(self.sub_meta[y]))), k=int(0.5 * len(self.sub_meta[y])))
  200. self.sub_meta_semi_sup[y] = [self.sub_meta[y][x] for x in semi_sup_indices]
  201. self.sub_meta[y] = [x for i, x in enumerate(self.sub_meta[y]) if i not in semi_sup_indices]
  202. print("class: %d; semi_sup: 50%% - %d images; sup: 50%% - %d images" % (y, len(self.sub_meta_semi_sup[y]), len(self.sub_meta[y])))
  203. self.sub_dataloader = []
  204. sub_data_loader_params = dict(batch_size = batch_size,
  205. shuffle = True,
  206. num_workers = 0, #use main thread only or may receive multiple batches
  207. pin_memory = False)
  208. for i,cl in enumerate(self.cl_list):
  209. sub_dataset = SubDataset(self.sub_meta[cl], cl, transform = transform, jigsaw=self.jigsaw, \
  210. transform_jigsaw=self.transform_jigsaw, transform_patch_jigsaw=self.transform_patch_jigsaw, transform_rotation=self.transform_rotation, \
  211. rotation=self.rotation, isAircraft=self.isAircraft, grey=self.grey, low_res=self.low_res, image_size=image_size, sub_meta_semi_sup=self.sub_meta_semi_sup[cl] if self.semi_sup else None, sub_meta_self_sup=self.sub_meta_self_sup[cl] if sup_ratio < 1.0 else None)
  212. self.sub_dataloader.append( torch.utils.data.DataLoader(sub_dataset, **sub_data_loader_params) )
  213. def __getitem__(self,i):
  214. return next(iter(self.sub_dataloader[i]))
  215. def __len__(self):
  216. return len(self.cl_list)
  217. class SubDataset:
  218. def __init__(self, sub_meta, cl, transform=transforms.ToTensor(), target_transform=identity, transform_rotation=None, \
  219. jigsaw=False, transform_jigsaw=None, transform_patch_jigsaw=None, rotation=False, isAircraft=False, grey=False, low_res=False, image_size=None, sub_meta_semi_sup=None, sub_meta_self_sup=None):
  220. self.sub_meta = sub_meta
  221. self.cl = cl
  222. self.transform = transform
  223. self.target_transform = target_transform
  224. self.rotation = rotation
  225. self.isAircraft = False #isAircraft
  226. self.grey = grey
  227. self.low_res = low_res
  228. self.jigsaw = jigsaw
  229. if jigsaw:
  230. self.permutations = retrive_permutations(35)
  231. self.transform_jigsaw = transform_jigsaw
  232. self.transform_patch_jigsaw = transform_patch_jigsaw
  233. if self.low_res:
  234. self.low_res_transform = transforms.Compose(
  235. [
  236. transforms.Resize((image_size//4, image_size//4)),
  237. transforms.Resize((image_size, image_size))
  238. ]
  239. )
  240. if self.rotation:
  241. self.transform_rotation = transform_rotation
  242. self.resize_transform = transforms.Resize((64,64)) # added because Conv4 does not support rotation on fc6
  243. self.sub_meta_semi_sup = sub_meta_semi_sup
  244. self.sub_meta_self_sup = sub_meta_self_sup
  245. def __getitem__(self,i):
  246. image_path = os.path.join(self.sub_meta[i])
  247. # image_path = os.path.join(self.sub_meta[i].replace('images','images_lowres'))
  248. # print(image_path)
  249. # image_path = os.path.join(self.sub_meta[i].replace('filelists/cars/images/','/data/jcsu/distill-net/data/cars/images_56_224/car_ims/'))
  250. # image_path = os.path.join(self.sub_meta[i].replace('/data/jcsu/CloserLookFewShot/filelists/CUB/CUB_200_2011/images/','/data/jcsu/distill-net/data/cub/images_lowres_full_50_224/'))
  251. # print(image_path)
  252. # import ipdb; ipdb.set_trace()
  253. if self.grey:
  254. img = Image.open(image_path).convert('L').convert('RGB')
  255. else:
  256. img = Image.open(image_path).convert('RGB')
  257. if self.low_res:
  258. img = self.low_res_transform(img)
  259. # if self.isAircraft:
  260. # ## crop the banner
  261. # img = img.crop((0,0,img.size[0],img.size[1]-20))
  262. if self.sub_meta_self_sup:
  263. img_ss = os.path.join(self.sub_meta_self_sup[choices(list(range(0,len(self.sub_meta_self_sup))), k=1)[0]])
  264. else:
  265. img_ss = img
  266. if self.jigsaw:
  267. patches, order = get_patches(img_ss, self.transform_jigsaw, self.transform_patch_jigsaw, self.permutations)
  268. if self.rotation:
  269. img_rot = self.resize_transform(img_ss)
  270. rotated_imgs = [
  271. self.transform_rotation(img_rot),
  272. self.transform_rotation(img_rot.rotate(90,expand=True)),
  273. self.transform_rotation(img_rot.rotate(180,expand=True)),
  274. self.transform_rotation(img_rot.rotate(270,expand=True))
  275. ]
  276. rotation_labels = torch.LongTensor([0, 1, 2, 3])
  277. img = self.transform(img)
  278. target = self.target_transform(self.cl)
  279. if self.sub_meta_semi_sup:
  280. semi_sup_img_path = os.path.join(self.sub_meta_semi_sup[choices(list(range(0,len(self.sub_meta_semi_sup))), k=1)[0]])
  281. if self.grey:
  282. semi_sup_img = Image.open(semi_sup_img_path).convert('L').convert('RGB')
  283. else:
  284. semi_sup_img = Image.open(semi_sup_img_path).convert('RGB')
  285. if self.low_res:
  286. semi_sup_img = self.low_res_transform(semi_sup_img)
  287. # if self.isAircraft:
  288. # ## crop the banner
  289. # semi_sup_img = semi_sup_img.crop((0,0,semi_sup_img.size[0],semi_sup_img.size[1]-20))
  290. semi_sup_img = self.transform(semi_sup_img)
  291. img = img.unsqueeze(0)
  292. semi_sup_img = semi_sup_img.unsqueeze(0)
  293. img = torch.cat([img, semi_sup_img], dim=0)
  294. if self.jigsaw and self.rotation:
  295. return img, target, patches, order, torch.stack(rotated_imgs, dim=0), rotation_labels
  296. elif self.jigsaw:
  297. return img, target, patches, order
  298. elif self.rotation:
  299. return img, target, torch.stack(rotated_imgs, dim=0), rotation_labels
  300. else:
  301. return img, target
  302. def __len__(self):
  303. return len(self.sub_meta)
  304. class EpisodicBatchSampler(object):
  305. def __init__(self, n_classes, n_way, n_episodes):
  306. self.n_classes = n_classes
  307. self.n_way = n_way
  308. self.n_episodes = n_episodes
  309. def __len__(self):
  310. return self.n_episodes
  311. def __iter__(self):
  312. for i in range(self.n_episodes):
  313. yield torch.randperm(self.n_classes)[:self.n_way]
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...