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

protonet_2loss.py 27 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
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
  1. # This code is modified from https://github.com/jakesnell/prototypical-networks
  2. import models.backbone as backbone
  3. import torch
  4. import torch.nn as nn
  5. from torch.autograd import Variable
  6. import numpy as np
  7. import torch.nn.functional as F
  8. from methods.meta_template import MetaTemplate
  9. from models.model_resnet import *
  10. from itertools import cycle
  11. import wandb
  12. try:
  13. from apex.parallel import DistributedDataParallel as DDP
  14. from apex.fp16_utils import *
  15. from apex import amp, optimizers
  16. from apex.multi_tensor_apply import multi_tensor_applier
  17. except ImportError:
  18. print("AMP is not installed. If --amp is True, code will fail.")
  19. from utils.io_utils import data_prefetcher
  20. from utils.utils import Logger
  21. class ProtoNet(MetaTemplate):
  22. def __init__(self, model_func, n_way, n_support, jigsaw=False, lbda=0.0, rotation=False, tracking=False, lbda_jigsaw=0.0, lbda_rotation=0.0, use_bn=True, pretrain=False, model="resnet18"):
  23. super(ProtoNet, self).__init__( model_func, n_way, n_support, use_bn, pretrain, tracking=tracking)
  24. self.loss_fn = nn.CrossEntropyLoss()
  25. self.jigsaw = jigsaw
  26. self.rotation = rotation
  27. self.lbda = lbda
  28. self.lbda_jigsaw = lbda_jigsaw
  29. self.lbda_rotation = lbda_rotation
  30. # self.lbda_proto = lbda_proto
  31. self.global_count = 0
  32. if self.jigsaw and self.rotation:
  33. self.fc6 = nn.Sequential()
  34. self.fc6.add_module('fc6_s1',nn.Linear(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet
  35. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  36. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  37. self.fc7_jigsaw = nn.Sequential()
  38. self.fc7_jigsaw.add_module('fc7',nn.Linear(9*1024,4096)) if model != "resnet18" else self.fc7_jigsaw.add_module('fc7',nn.Linear(9*512,4096))#for resnet
  39. self.fc7_jigsaw.add_module('relu7',nn.ReLU(inplace=True))
  40. self.fc7_jigsaw.add_module('drop7',nn.Dropout(p=0.5))
  41. self.classifier_jigsaw = nn.Sequential()
  42. self.classifier_jigsaw.add_module('fc8',nn.Linear(4096, 35))
  43. self.fc7_rotation = nn.Sequential()
  44. self.fc7_rotation.add_module('fc7',nn.Linear(1024,128)) if model != "resnet18" else self.fc7_rotation.add_module('fc7',nn.Linear(512,128))#for resnet
  45. self.fc7_rotation.add_module('relu7',nn.ReLU(inplace=True))
  46. self.fc7_rotation.add_module('drop7',nn.Dropout(p=0.5))
  47. self.classifier_rotation = nn.Sequential()
  48. self.classifier_rotation.add_module('fc8',nn.Linear(128, 4))
  49. elif self.jigsaw:
  50. self.fc6 = nn.Sequential()
  51. self.fc6.add_module('fc6_s1',nn.Linear(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet
  52. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  53. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  54. self.fc7 = nn.Sequential()
  55. self.fc7.add_module('fc7',nn.Linear(9*1024,4096)) if model != "resnet18" else self.fc7.add_module('fc7',nn.Linear(9*512,4096))#for resnet
  56. self.fc7.add_module('relu7',nn.ReLU(inplace=True))
  57. self.fc7.add_module('drop7',nn.Dropout(p=0.5))
  58. self.classifier = nn.Sequential()
  59. self.classifier.add_module('fc8',nn.Linear(4096, 35))
  60. elif self.rotation:
  61. self.fc6 = nn.Sequential()
  62. self.fc6.add_module('fc6_s1',nn.Linear(1024, 1024)) if model != "resnet18" else self.fc6.add_module('fc6_s1',nn.Linear(512, 512))#for resnet
  63. self.fc6.add_module('relu6_s1',nn.ReLU(inplace=True))
  64. self.fc6.add_module('drop6_s1',nn.Dropout(p=0.5))
  65. self.fc7 = nn.Sequential()
  66. self.fc7.add_module('fc7',nn.Linear(1024,128)) if model != "resnet18" else self.fc7.add_module('fc7',nn.Linear(512,128))#for resnet
  67. self.fc7.add_module('relu7',nn.ReLU(inplace=True))
  68. self.fc7.add_module('drop7',nn.Dropout(p=0.5))
  69. self.classifier_rotation = nn.Sequential()
  70. self.classifier_rotation.add_module('fc8',nn.Linear(128, 4))
  71. def train_loop(self, epoch, train_loader, optimizer, pbar=None, enable_amp=None, base_loader_u = None, semi_sup=False):
  72. avg_loss=0
  73. avg_loss_proto=0
  74. avg_loss_jigsaw=0
  75. avg_loss_rotation=0
  76. if base_loader_u:
  77. loader = zip(train_loader, cycle(base_loader_u))
  78. else:
  79. loader = train_loader
  80. iter_num = 0
  81. for iter_num, inputs in enumerate(loader):
  82. self.global_count += 1
  83. x = inputs[0] if not base_loader_u else inputs[0][0]
  84. if semi_sup:
  85. semi_inputs = x[:, :, 1]
  86. x = x[:, :, 0]
  87. else:
  88. semi_inputs = None
  89. self.n_query = x.size(1) - self.n_support
  90. if self.change_way:
  91. self.n_way = x.size(0)
  92. optimizer.zero_grad()
  93. # import ipdb; ipdb.set_trace()
  94. if base_loader_u:
  95. aux_inputs = inputs[1]
  96. if len(aux_inputs[2].shape) == 5:
  97. aux_inputs[2] = aux_inputs[2].view(self.n_way, self.n_support + self.n_query, *aux_inputs[2].size()[1:])
  98. if len(aux_inputs) > 4 and len(aux_inputs[4].shape) == 5:
  99. aux_inputs[4] = aux_inputs[4].view(self.n_way, self.n_support + self.n_query, *aux_inputs[4].size()[1:])
  100. else:
  101. aux_inputs = inputs
  102. if self.jigsaw and self.rotation:
  103. loss_proto, loss_jigsaw, loss_rotation, acc, acc_jigsaw, acc_rotation = self.set_forward_loss( x, aux_inputs[2], aux_inputs[3], aux_inputs[4], aux_inputs[5], semi_inputs=semi_inputs )# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])
  104. loss = (1.0-self.lbda_jigsaw-self.lbda_rotation) * loss_proto + self.lbda_jigsaw * loss_jigsaw + self.lbda_rotation * loss_rotation
  105. # loss = 0.0 * loss_proto + self.lbda * loss_jigsaw
  106. Logger.log({'train/loss_proto': float(loss_proto.item())}, step=self.global_count)
  107. Logger.log({'train/loss_jigsaw': float(loss_jigsaw.item())}, step=self.global_count)
  108. Logger.log({'train/loss_rotation': float(loss_rotation.item())}, step=self.global_count)
  109. elif self.jigsaw:
  110. # import ipdb; ipdb.set_trace()
  111. loss_proto, loss_jigsaw, acc, acc_jigsaw = self.set_forward_loss( x, aux_inputs[2], aux_inputs[3], semi_inputs=semi_inputs )# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])
  112. loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_jigsaw
  113. # loss = 0.0 * loss_proto + self.lbda * loss_jigsaw
  114. Logger.log({'train/loss_proto': float(loss_proto.item())}, step=self.global_count)
  115. Logger.log({'train/loss_jigsaw': float(loss_jigsaw.item())}, step=self.global_count)
  116. elif self.rotation:
  117. # import ipdb; ipdb.set_trace()
  118. loss_proto, loss_rotation, acc, acc_rotation = self.set_forward_loss( x, aux_inputs[2], aux_inputs[3], semi_inputs=semi_inputs )# torch.Size([5, 21, 9, 3, 75, 75]), torch.Size([5, 21])
  119. loss = (1.0-self.lbda) * loss_proto + self.lbda * loss_rotation
  120. Logger.log({'train/loss_proto': float(loss_proto.item())}, step=self.global_count)
  121. Logger.log({'train/loss_rotation': float(loss_rotation.item())}, step=self.global_count)
  122. else:
  123. loss, acc = self.set_forward_loss( x, semi_inputs=semi_inputs )
  124. if enable_amp:
  125. with amp.scale_loss(loss, optimizer) as scaled_loss:
  126. scaled_loss.backward()
  127. else:
  128. loss.backward()
  129. optimizer.step()
  130. # avg_loss = avg_loss+loss.data[0]
  131. avg_loss = avg_loss+loss.data
  132. Logger.log({'train/loss': float(loss.item())}, step=self.global_count)
  133. pbar.update(1)
  134. if self.jigsaw and self.rotation:
  135. avg_loss_proto += loss_proto.data
  136. avg_loss_jigsaw += loss_jigsaw.data
  137. avg_loss_rotation += loss_rotation.data
  138. Logger.log({'train/acc_proto': float(acc.item())}, step=self.global_count)
  139. Logger.log({'train/acc_jigsaw': float(acc_jigsaw.item())}, step=self.global_count)
  140. Logger.log({'train/acc_rotation': float(acc_rotation.item())}, step=self.global_count)
  141. elif self.jigsaw:
  142. avg_loss_proto += loss_proto.data
  143. avg_loss_jigsaw += loss_jigsaw.data
  144. Logger.log({'train/acc_proto': float(acc.item())}, step=self.global_count)
  145. Logger.log({'train/acc_jigsaw': float(acc_jigsaw.item())}, step=self.global_count)
  146. elif self.rotation:
  147. avg_loss_proto += loss_proto.data
  148. avg_loss_rotation += loss_rotation.data
  149. Logger.log({'train/acc_proto': float(acc.item())}, step=self.global_count)
  150. Logger.log({'train/acc_rotation': float(acc_rotation.item())}, step=self.global_count)
  151. return avg_loss
  152. def test_loop(self, test_loader, record = None, base_loader_u=None, semi_sup=False, proto_only=False):
  153. correct =0
  154. count = 0
  155. acc_all = []
  156. acc_all_jigsaw = []
  157. acc_all_rotation = []
  158. iter_num = len(test_loader)
  159. if base_loader_u:
  160. loader = zip(test_loader, cycle(base_loader_u))
  161. else:
  162. loader = test_loader
  163. i = 0
  164. for i, inputs in enumerate(loader):
  165. x = inputs[0] if not base_loader_u else inputs[0][0]
  166. if semi_sup:
  167. semi_inputs = x[:, :, 1]
  168. x = x[:, :, 0]
  169. else:
  170. semi_inputs = None
  171. self.n_query = x.size(1) - self.n_support
  172. if self.change_way:
  173. self.n_way = x.size(0)
  174. if base_loader_u:
  175. aux_inputs = inputs[1]
  176. if len(aux_inputs[2].shape) == 5:
  177. aux_inputs[2] = aux_inputs[2].view(self.n_way, self.n_support + self.n_query, *aux_inputs[2].size()[1:])
  178. if len(aux_inputs) > 4 and len(aux_inputs[4].shape) == 5:
  179. aux_inputs[4] = aux_inputs[4].view(self.n_way, self.n_support + self.n_query, *aux_inputs[4].size()[1:])
  180. else:
  181. aux_inputs = inputs
  182. if not proto_only:
  183. if self.jigsaw and self.rotation:
  184. correct_this, correct_this_jigsaw, correct_this_rotation, count_this, count_this_jigsaw, count_this_rotation = self.correct(x, aux_inputs[2], aux_inputs[3], aux_inputs[4], aux_inputs[5], semi_inputs=semi_inputs )
  185. elif self.jigsaw:
  186. correct_this, correct_this_jigsaw, count_this, count_this_jigsaw = self.correct(x, aux_inputs[2], aux_inputs[3], semi_inputs=semi_inputs )
  187. elif self.rotation:
  188. correct_this, correct_this_rotation, count_this, count_this_rotation = self.correct(x, aux_inputs[2], aux_inputs[3], semi_inputs=semi_inputs )
  189. else:
  190. correct_this, count_this = self.correct(x, semi_inputs=semi_inputs )
  191. else:
  192. correct_this, count_this = self.correct(x, semi_inputs=semi_inputs )
  193. acc_all.append(correct_this/ count_this*100)
  194. if not proto_only:
  195. if self.jigsaw and self.rotation:
  196. acc_all_jigsaw.append(correct_this_jigsaw/ count_this_jigsaw*100)
  197. acc_all_rotation.append(correct_this_rotation/ count_this_rotation*100)
  198. elif self.jigsaw:
  199. acc_all_jigsaw.append(correct_this_jigsaw/ count_this_jigsaw*100)
  200. elif self.rotation:
  201. acc_all_rotation.append(correct_this_rotation/ count_this_rotation*100)
  202. acc_all = np.asarray(acc_all)
  203. acc_mean = np.mean(acc_all)
  204. acc_std = np.std(acc_all)
  205. print('%d Test Protonet Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean, 1.96* acc_std/np.sqrt(iter_num)))
  206. if not proto_only:
  207. if self.jigsaw and self.rotation:
  208. acc_all_jigsaw = np.asarray(acc_all_jigsaw)
  209. acc_mean_jigsaw = np.mean(acc_all_jigsaw)
  210. acc_std_jigsaw = np.std(acc_all_jigsaw)
  211. print('%d Test Jigsaw Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_jigsaw, 1.96* acc_std_jigsaw/np.sqrt(iter_num)))
  212. acc_all_rotation = np.asarray(acc_all_rotation)
  213. acc_mean_rotation = np.mean(acc_all_rotation)
  214. acc_std_rotation = np.std(acc_all_rotation)
  215. print('%d Test Rotation Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_rotation, 1.96* acc_std_rotation/np.sqrt(iter_num)))
  216. return acc_mean, acc_mean_jigsaw, acc_mean_rotation
  217. elif self.jigsaw:
  218. acc_all_jigsaw = np.asarray(acc_all_jigsaw)
  219. acc_mean_jigsaw = np.mean(acc_all_jigsaw)
  220. acc_std_jigsaw = np.std(acc_all_jigsaw)
  221. print('%d Test Jigsaw Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_jigsaw, 1.96* acc_std_jigsaw/np.sqrt(iter_num)))
  222. return acc_mean, acc_mean_jigsaw
  223. elif self.rotation:
  224. acc_all_rotation = np.asarray(acc_all_rotation)
  225. acc_mean_rotation = np.mean(acc_all_rotation)
  226. acc_std_rotation = np.std(acc_all_rotation)
  227. print('%d Test Rotation Acc = %4.2f%% +- %4.2f%%' %(iter_num, acc_mean_rotation, 1.96* acc_std_rotation/np.sqrt(iter_num)))
  228. return acc_mean, acc_mean_rotation
  229. else:
  230. return acc_mean
  231. else:
  232. return acc_mean, acc_std
  233. def correct(self, x, patches=None, patches_label=None, patches_rotation=None, patches_label_rotation=None, semi_inputs=None):
  234. if self.jigsaw and self.rotation and patches != None and patches_rotation != None:
  235. scores, x_, y_, x_rotation, y_rotation = self.set_forward(x,patches=patches,patches_label=patches_label,patches_rotation=patches_rotation, patches_label_rotation=patches_label_rotation, semi_inputs=semi_inputs)
  236. elif self.jigsaw and patches != None:
  237. scores, x_, y_ = self.set_forward(x,patches=patches,patches_label=patches_label, semi_inputs=semi_inputs)
  238. elif self.rotation and patches != None:
  239. scores, x_, y_ = self.set_forward(x,patches=patches,patches_label=patches_label, semi_inputs=semi_inputs)
  240. else:
  241. scores = self.set_forward(x, semi_inputs=semi_inputs)
  242. y_query = np.repeat(range( self.n_way ), self.n_query )
  243. topk_scores, topk_labels = scores.data.topk(1, 1, True, True)
  244. topk_ind = topk_labels.cpu().numpy()
  245. top1_correct = np.sum(topk_ind[:,0] == y_query)
  246. if self.jigsaw and self.rotation and patches != None and patches_rotation != None:
  247. pred = torch.max(x_,1)
  248. top1_correct_jigsaw = torch.sum(pred[1] == y_)
  249. pred_rotation = torch.max(x_rotation,1)
  250. top1_correct_rotation = torch.sum(pred_rotation[1] == y_rotation)
  251. return float(top1_correct), float(top1_correct_jigsaw), float(top1_correct_rotation), len(y_query), len(y_), len(y_rotation)
  252. elif self.jigsaw and patches != None:
  253. pred = torch.max(x_,1)
  254. top1_correct_jigsaw = torch.sum(pred[1] == y_)
  255. return float(top1_correct), float(top1_correct_jigsaw), len(y_query), len(y_)
  256. elif self.rotation and patches != None:
  257. pred = torch.max(x_,1)
  258. top1_correct_rotation = torch.sum(pred[1] == y_)
  259. return float(top1_correct), float(top1_correct_rotation), len(y_query), len(y_)
  260. else:
  261. return float(top1_correct), len(y_query)
  262. def set_forward_test(self,x,is_feature = False, semi_inputs=None):
  263. z_support, z_query = self.parse_feature(x,is_feature)
  264. z_support = z_support.contiguous()
  265. z_proto_nway_kshot = z_support.view(self.n_way, self.n_support, -1 )
  266. z_proto = z_proto_nway_kshot.mean(1) #the shape of z is [n_data, n_dim]
  267. z_query = z_query.contiguous().view(self.n_way* self.n_query, -1 )
  268. dists = euclidean_dist(z_query, z_proto)
  269. if semi_inputs != None:
  270. semi_inputs = semi_inputs.cuda()
  271. semi_inputs = semi_inputs.contiguous().view( self.n_way * (self.n_support + self.n_query), *semi_inputs.size()[2:])
  272. semi_z = self.feature(semi_inputs)
  273. semi_z = semi_z.view(semi_z.shape[0], -1)
  274. inner_dist = -euclidean_dist(semi_z, z_proto)
  275. class_assignments = torch.argmax(F.softmax(inner_dist, dim=1), dim=1)
  276. z_proto_refined = z_proto_nway_kshot.mean(1)
  277. for i in range(0, self.n_way):
  278. class_i_tensors = None
  279. for j in range(0, semi_z.shape[0]):
  280. if class_assignments[j] == i:
  281. class_i_tensors = torch.cat([class_i_tensors, semi_z[j]]) if class_i_tensors != None else semi_z[j]
  282. z_proto_refined[i] = class_i_tensors.mean(0)
  283. dists = euclidean_dist(z_query, z_proto_refined)
  284. # get cluster assignments - basic softmax over distance of the prototypes from
  285. # recalculate the mean - append them to the corresponding columns in z_proto and then take a mean
  286. # recal the distance
  287. scores = -dists
  288. return scores
  289. def set_forward(self,x,is_feature = False, patches=None, patches_label=None, patches_rotation=None, patches_label_rotation=None, semi_inputs=None):
  290. z_support, z_query = self.parse_feature(x,is_feature)
  291. z_support = z_support.contiguous()
  292. z_proto_nway_kshot = z_support.view(self.n_way, self.n_support, -1 )
  293. z_proto = z_proto_nway_kshot.mean(1) #the shape of z is [n_data, n_dim]
  294. z_query = z_query.contiguous().view(self.n_way* self.n_query, -1 )
  295. dists = euclidean_dist(z_query, z_proto)
  296. if semi_inputs != None:
  297. semi_inputs = semi_inputs.cuda()
  298. semi_inputs = semi_inputs.contiguous().view( self.n_way * (self.n_support + self.n_query), *semi_inputs.size()[2:])
  299. semi_z = self.feature(semi_inputs)
  300. semi_z = semi_z.view(semi_z.shape[0], -1)
  301. inner_dist = -euclidean_dist(semi_z, z_proto)
  302. class_assignments = torch.argmax(F.softmax(inner_dist, dim=1), dim=1)
  303. z_proto_refined = z_proto_nway_kshot.mean(1)
  304. for i in range(0, self.n_way):
  305. class_i_tensors = None
  306. for j in range(0, semi_z.shape[0]):
  307. if class_assignments[j] == i:
  308. class_i_tensors = torch.cat([class_i_tensors, semi_z[j]]) if class_i_tensors != None else semi_z[j]
  309. z_proto_refined[i] = class_i_tensors.mean(0)
  310. dists = euclidean_dist(z_query, z_proto_refined)
  311. scores = -dists
  312. if self.jigsaw and self.rotation and patches != None and patches_rotation != None:
  313. # import ipdb; ipdb.set_trace()
  314. # patches = patches[:,:self.n_support,...]
  315. # patches = patches[:,:,...]#S is shot+query
  316. Way,S,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])
  317. B = Way*S
  318. # patches = patches.contiguous()
  319. patches = patches.view(Way*S*T,C,H,W).cuda()#torch.Size([675, 3, 64, 64])
  320. # patches = Variable(patches.cuda())
  321. # import ipdb; ipdb.set_trace()
  322. if self.dual_cbam:
  323. patch_feat = self.feature(patches, jigsaw=True)#torch.Size([675, 512])
  324. else:
  325. patch_feat = self.feature(patches)#torch.Size([675, 512])
  326. x_ = patch_feat.view(Way*S,T,-1)
  327. x_ = x_.transpose(0,1)#torch.Size([9, 75, 512])
  328. x_list = []
  329. for i in range(9):
  330. # z = self.conv(x_[i])
  331. # z = self.fc6(z.view(B,-1))
  332. # import ipdb; ipdb.set_trace()
  333. z = self.fc6(x_[i])#torch.Size([75, 512])
  334. z = z.view([B,1,-1])#torch.Size([75, 1, 512])
  335. x_list.append(z)
  336. x_ = torch.cat(x_list,1)#torch.Size([75, 9, 512])
  337. x_ = self.fc7_jigsaw(x_.view(B,-1))#torch.Size([75, 9*512])
  338. x_ = self.classifier_jigsaw(x_)
  339. # y_ = patches_label[:,:self.n_support].contiguous().view(-1)
  340. # y_ = patches_label[:,:].contiguous().view(-1)
  341. y_ = patches_label.view(-1).cuda()
  342. # y_ = Variable(y_.cuda())
  343. ## rotation: ##
  344. # import ipdb; ipdb.set_trace()
  345. Way,S,T,C,H,W = patches_rotation.size()#torch.Size([5, 21, 4, 3, 224, 224])
  346. B = Way*S
  347. patches_rotation = patches_rotation.view(Way*S*T,C,H,W).cuda()
  348. x_rotation_ = self.feature(patches_rotation)#torch.Size([64, 512, 1, 1])
  349. x_rotation_ = x_rotation_.squeeze()
  350. x_rotation_ = self.fc6(x_rotation_)
  351. x_rotation_ = self.fc7_rotation(x_rotation_)#64,128
  352. x_rotation_ = self.classifier_rotation(x_rotation_)#64,4
  353. pred_rotation = torch.max(x_rotation_,1)
  354. y_rotation_ = patches_label_rotation.view(-1).cuda()
  355. return scores, x_, y_, x_rotation_, y_rotation_
  356. elif self.jigsaw and patches != None:
  357. # import ipdb; ipdb.set_trace()
  358. # patches = patches[:,:self.n_support,...]
  359. # patches = patches[:,:,...]#S is shot+query
  360. Way,S,T,C,H,W = patches.size()#torch.Size([5, 15, 9, 3, 75, 75])
  361. B = Way*S
  362. # patches = patches.contiguous()
  363. patches = patches.view(Way*S*T,C,H,W).cuda()#torch.Size([675, 3, 64, 64])
  364. # patches = Variable(patches.cuda())
  365. # import ipdb; ipdb.set_trace()
  366. if self.dual_cbam:
  367. patch_feat = self.feature(patches, jigsaw=True)#torch.Size([675, 512])
  368. else:
  369. patch_feat = self.feature(patches)#torch.Size([675, 512])
  370. x_ = patch_feat.view(Way*S,T,-1)
  371. x_ = x_.transpose(0,1)#torch.Size([9, 75, 512])
  372. x_list = []
  373. for i in range(9):
  374. # z = self.conv(x_[i])
  375. # z = self.fc6(z.view(B,-1))
  376. # import ipdb; ipdb.set_trace()
  377. z = self.fc6(x_[i])#torch.Size([75, 512])
  378. z = z.view([B,1,-1])#torch.Size([75, 1, 512])
  379. x_list.append(z)
  380. x_ = torch.cat(x_list,1)#torch.Size([75, 9, 512])
  381. x_ = self.fc7(x_.view(B,-1))#torch.Size([75, 9*512])
  382. x_ = self.classifier(x_)
  383. # y_ = patches_label[:,:self.n_support].contiguous().view(-1)
  384. # y_ = patches_label[:,:].contiguous().view(-1)
  385. y_ = patches_label.view(-1).cuda()
  386. # y_ = Variable(y_.cuda())
  387. return scores, x_, y_
  388. elif self.rotation and patches != None:
  389. # import ipdb; ipdb.set_trace()
  390. Way,S,T,C,H,W = patches.size()#torch.Size([5, 21, 4, 3, 224, 224])
  391. B = Way*S
  392. patches = patches.view(Way*S*T,C,H,W).cuda()
  393. x_ = self.feature(patches)#torch.Size([64, 512, 1, 1])
  394. x_ = x_.squeeze()
  395. x_ = self.fc6(x_)
  396. x_ = self.fc7(x_)#64,128
  397. x_ = self.classifier_rotation(x_)#64,4
  398. pred = torch.max(x_,1)
  399. y_ = patches_label.view(-1).cuda()
  400. return scores, x_, y_
  401. else:
  402. return scores
  403. def set_forward_loss(self, x, patches=None, patches_label=None, patches_rotation=None, patches_label_rotation=None, semi_inputs=None):
  404. y_query = torch.from_numpy(np.repeat(range( self.n_way ), self.n_query ))
  405. if self.jigsaw and self.rotation and patches != None and patches_rotation != None:
  406. scores, x_, y_, x_rotation_, y_rotation_ = self.set_forward(x,patches=patches,patches_label=patches_label,patches_rotation=patches_rotation,patches_label_rotation=patches_label_rotation, semi_inputs=semi_inputs)
  407. pred = torch.max(x_,1)
  408. acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)
  409. pred_rotation = torch.max(x_rotation_,1)
  410. acc_rotation = torch.sum(pred_rotation[1] == y_rotation_).cpu().numpy()*1.0/len(y_rotation_)
  411. elif self.jigsaw and patches != None:
  412. scores, x_, y_ = self.set_forward(x,patches=patches,patches_label=patches_label, semi_inputs=semi_inputs)
  413. pred = torch.max(x_,1)
  414. acc_jigsaw = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)
  415. elif self.rotation and patches != None:
  416. scores, x_, y_ = self.set_forward(x,patches=patches,patches_label=patches_label, semi_inputs=semi_inputs)
  417. pred = torch.max(x_,1)
  418. acc_rotation = torch.sum(pred[1] == y_).cpu().numpy()*1.0/len(y_)
  419. else:
  420. scores = self.set_forward(x,patches=patches,patches_label=patches_label, semi_inputs=semi_inputs)
  421. topk_scores, topk_labels = scores.data.topk(1, 1, True, True)
  422. topk_ind = topk_labels.cpu().numpy()
  423. acc = np.sum(topk_ind[:,0] == y_query.numpy())/len(y_query.numpy())
  424. y_query = Variable(y_query.cuda())
  425. if self.jigsaw and self.rotation:
  426. return self.loss_fn(scores, y_query), self.loss_fn(x_,y_), self.loss_fn(x_rotation_,y_rotation_), acc, acc_jigsaw, acc_rotation
  427. elif self.jigsaw:
  428. return self.loss_fn(scores, y_query), self.loss_fn(x_,y_), acc, acc_jigsaw
  429. elif self.rotation:
  430. return self.loss_fn(scores, y_query), self.loss_fn(x_,y_), acc, acc_rotation
  431. else:
  432. return self.loss_fn(scores, y_query), acc
  433. def parse_feature(self,x,is_feature):
  434. x = Variable(x.cuda())
  435. if is_feature:
  436. z_all = x
  437. else:
  438. x = x.contiguous().view( self.n_way * (self.n_support + self.n_query), *x.size()[2:])
  439. z_all = self.feature(x)
  440. # import ipdb; ipdb.set_trace()
  441. # print(z_all.shape)
  442. z_all = z_all.view( self.n_way, self.n_support + self.n_query, -1)
  443. # print(z_all.shape)
  444. z_support = z_all[:, :self.n_support]
  445. z_query = z_all[:, self.n_support:]
  446. # import ipdb; ipdb.set_trace()
  447. return z_support, z_query
  448. def euclidean_dist( x, y):
  449. # x: N x D
  450. # y: M x D
  451. n = x.size(0)
  452. m = y.size(0)
  453. d = x.size(1)
  454. assert d == y.size(1)
  455. x = x.unsqueeze(1).expand(n, m, d)
  456. y = y.unsqueeze(0).expand(n, m, d)
  457. return torch.pow(x - y, 2).sum(2)
Tip!

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

Comments

Loading...