-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtrain_utils.py
726 lines (549 loc) · 27.8 KB
/
train_utils.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
# Nicola Dinsdale 2020
# Functions for training and validating the model
########################################################################################################################
# Import dependencies
import numpy as np
import torch
from torch.autograd import Variable
from sklearn.metrics import accuracy_score
########################################################################################################################
def train_unlearn_threedatasets(args, models, train_loaders, optimizers, criterions, epoch):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[optimizer, optimizer_conf, optimizer_dm] = optimizers
[b_train_dataloader, o_train_dataloader, w_train_dataloader] = train_loaders
[criteron, conf_criterion, domain_criterion] = criterions
regressor_loss = 0
domain_loss = 0
conf_loss = 0
encoder.train()
regressor.train()
domain_predictor.train()
true_domains = []
pred_domains = []
batches = 0
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (w_data, w_target, w_domain)) in enumerate(zip(b_train_dataloader, o_train_dataloader, w_train_dataloader)):
max_batch = len(b_data)
n1 = np.random.randint(1, max_batch - 2) # Must be at least one from each
n2 = np.random.randint(1, max_batch - n1 -1)
n3 = max_batch - n1 - n2
if n3 < 1:
assert ValueError('N3 must be greater that zero')
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
w_data = w_data[:n3]
w_target = w_target[:n3]
w_domain = w_domain[:n3]
data = torch.cat((b_data, o_data, w_data), 0)
target = torch.cat((b_target, o_target, w_target), 0)
domain_target = torch.cat((b_domain, o_domain, w_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size :
batches += 1
# First update the encoder and regressor
optimizer.zero_grad()
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:n1+n2], target[n1:n1+n2])
loss_3 = criteron(output_pred[n1+n2:], target[n1+n2:])
loss = loss_1 + loss_2 + loss_3
loss_total = loss
loss_total.backward(retain_graph=True)
optimizer.step()
# Now update just the domain classifier
optimizer_dm.zero_grad()
output_dm = domain_predictor(features.detach())
loss_dm = args.alpha * domain_criterion(output_dm, domain_target)
loss_dm.backward()
optimizer_dm.step()
# Now update just the encoder using the domain loss
optimizer_conf.zero_grad()
output_dm_conf = domain_predictor(features)
loss_conf = args.beta * conf_criterion(output_dm_conf, domain_target) # Get rid of the weight for not unsupervised
loss_conf.backward(retain_graph=False)
optimizer_conf.step()
regressor_loss += loss
domain_loss += loss_dm
conf_loss += loss_conf
output_dm_conf = np.argmax(output_dm_conf.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(output_dm_conf)
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, (batch_idx+1) * len(data), len(b_train_dataloader.dataset),
100. * (batch_idx+1) / len(b_train_dataloader), loss.item()), flush=True)
print('\t \t Confusion loss = ', loss_conf.item())
print('\t \t Domain Loss = ', loss_dm.item(), flush=True)
del target
del loss
del features
av_loss = regressor_loss / batches
av_conf = conf_loss / batches
av_dom = domain_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nTraining set: Average loss: {:.4f}'.format(av_loss, flush=True))
print('Training set: Average Conf loss: {:.4f}'.format(av_conf, flush=True))
print('Training set: Average Dom loss: {:.4f}'.format(av_dom, flush=True))
print('Training set: Average Acc: {:.4f}\n'.format(acc, flush=True))
return av_loss, acc, av_dom, av_conf
def train_unlearn_distinct(args, models, train_loaders, optimizers, criterions, epoch):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[optimizer, optimizer_conf, optimizer_dm] = optimizers
[b_train_dataloader, o_train_dataloader, b_train_int_dataloader, o_train_int_dataloader] = train_loaders
[criteron, conf_criterion, domain_criterion] = criterions
regressor_loss = 0
domain_loss = 0
conf_loss = 0
encoder.train()
regressor.train()
domain_predictor.train()
true_domains = []
pred_domains = []
batches = 0
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (b_int_data, b_int_domain), (o_int_data, o_int_domain)) in enumerate(zip(b_train_dataloader, o_train_dataloader, b_train_int_dataloader, o_train_int_dataloader)):
n1 = np.random.randint(1, len(b_data)-1)
n2 = len(b_data) - n1
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
b_int_data = b_int_data[:n1]
b_int_domain = b_int_domain[:n1]
o_int_data = o_int_data[:n2]
o_int_domain = o_int_domain[:n2]
data = torch.cat((b_data, o_data), 0)
target = torch.cat((b_target, o_target), 0)
domain_target = torch.cat((b_domain, o_domain), 0)
int_data = torch.cat((b_int_data, o_int_data), 0)
int_domain = torch.cat((b_int_domain, o_int_domain), 0)
if cuda:
data, target, domain_target, int_data, int_domain = data.cuda(), target.cuda(), domain_target.cuda(), int_data.cuda(), int_domain.cuda()
data, target, domain_target, int_data, int_domain = Variable(data), Variable(target), Variable(domain_target), Variable(int_data), Variable(int_domain)
if list(data.size())[0] == args.batch_size :
if list(int_domain.size())[0] == args.batch_size :
batches += 1
# First update the encoder and regressor
optimizer.zero_grad()
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:], target[n1:])
loss_total = loss_1 + loss_2
loss_total.backward()
optimizer.step()
# Now update just the domain classifier on the intersection data only
optimizer_dm.zero_grad()
new_features = encoder(int_data)
output_dm = domain_predictor(new_features.detach())
loss_dm = args.alpha * domain_criterion(output_dm, int_domain)
loss_dm.backward()
optimizer_dm.step()
# Now update just the encoder using the domain loss
optimizer_conf.zero_grad()
output_dm_conf = domain_predictor(new_features)
loss_conf = args.beta * conf_criterion(output_dm_conf, int_domain)
loss_conf.backward(retain_graph=False)
optimizer_conf.step()
regressor_loss += loss_total
domain_loss += loss_dm
conf_loss += loss_conf
output_dm_conf = np.argmax(output_dm_conf.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(int_domain.detach().cpu().numpy(), axis=1)
true_domains.append(np.array(domain_target))
pred_domains.append(np.array(output_dm_conf))
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, (batch_idx+1) * len(data), len(b_train_dataloader.dataset),
100. * (batch_idx+1) / len(b_train_dataloader), loss_total.item()), flush=True)
print('\t \t Confusion loss = ', loss_conf.item())
print('\t \t Domain Loss = ', loss_dm.item(), flush=True)
del target
del loss_total
del features
av_loss = regressor_loss / batches
av_conf = conf_loss / batches
av_dom = domain_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('Training set: Average loss: {:.4f}'.format(av_loss, flush=True))
print('Training set: Average Conf loss: {:.4f}'.format(av_conf, flush=True))
print('Training set: Average Dom loss: {:.4f}'.format(av_dom, flush=True))
print('Training set: Average Acc: {:.4f}\n'.format(acc, flush=True))
return av_loss, acc, av_dom, av_conf
def val_unlearn_threedatasets(args, models, val_loaders, criterions):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[b_val_dataloader, o_val_dataloader, w_val_dataloader] = val_loaders
[criteron, _, _] = criterions
encoder.eval()
regressor.eval()
domain_predictor.eval()
val_loss = 0
true_domains = []
pred_domains = []
batches = 0
with torch.no_grad():
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (w_data, w_target, w_domain)) in enumerate(zip(b_val_dataloader, o_val_dataloader, w_val_dataloader)):
max_batch = len(b_data)
n1 = np.random.randint(1, max_batch - 2) # Must be at least one from each
n2 = np.random.randint(1, max_batch - n1 - 1)
n3 = max_batch - n1 - n2
if n3 < 1:
assert ValueError('N3 must be greater that zero')
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
w_data = w_data[:n3]
w_target = w_target[:n3]
w_domain = w_domain[:n3]
data = torch.cat((b_data, o_data, w_data), 0)
target = torch.cat((b_target, o_target, w_target), 0)
domain_target = torch.cat((b_domain, o_domain, w_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size:
batches += 1
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:n1+n2], target[n1:n1+n2])
loss_3 = criteron(output_pred[n1+n2:n1+n2+n3], target[n1+n2:n1+n2+n3])
loss = loss_1 + loss_2 + loss_3
val_loss += loss
domains = domain_predictor.forward(features)
domains = np.argmax(domains.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(domains)
val_loss = val_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nValidation set: Average loss: {:.4f}\n'.format(val_loss, flush=True))
print('Validation set: Average Acc: {:.4f}\n'.format(acc, flush=True))
return val_loss, acc
def val_unlearn_distinct(args, models, val_loaders, criterions):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[b_val_dataloader, o_val_dataloader, b_int_val_dataloader, o_int_val_dataloader] = val_loaders
[criteron, _, _] = criterions
encoder.eval()
regressor.eval()
domain_predictor.eval()
val_loss = 0
true_domains = []
pred_domains = []
batches = 0
with torch.no_grad():
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (b_int_data, b_int_domain), (o_int_data, o_int_domain)) in enumerate(zip(b_val_dataloader, o_val_dataloader, b_int_val_dataloader, o_int_val_dataloader)):
n1 = np.random.randint(1, len(b_data) - 1)
n2 = len(b_data) - n1
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
b_int_data = b_int_data[:n1]
b_int_domain = b_int_domain[:n1]
o_int_data = o_int_data[:n2]
o_int_domain = o_int_domain[:n2]
data = torch.cat((b_data, o_data), 0)
target = torch.cat((b_target, o_target), 0)
domain_target = torch.cat((b_domain, o_domain), 0)
int_data = torch.cat((b_int_data, o_int_data), 0)
int_domain = torch.cat((b_int_domain, o_int_domain), 0)
if cuda:
data, target, domain_target, int_data, int_domain = data.cuda(), target.cuda(), domain_target.cuda(), int_data.cuda(), int_domain.cuda()
data, target, domain_target, int_data, int_domain = Variable(data), Variable(target), Variable(domain_target), Variable(int_data), Variable(int_domain)
if list(data.size())[0] == args.batch_size:
if list(int_data.size())[0] == args.batch_size:
batches += 1
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:n1+n2], target[n1:n1+n2])
loss_3 = criteron(output_pred[n1+n2:], target[n1+n2:])
loss = loss_1 + loss_2 + loss_3
val_loss += loss
new_features = encoder(int_data)
domains = domain_predictor.forward(new_features)
domains = np.argmax(domains.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(int_domain.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(domains)
val_loss = val_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nValidation set: Average loss: {:.4f}\n'.format(val_loss, flush=True))
print('Validation set: Average Acc: {:.4f}\n'.format(acc, flush=True))
return val_loss, acc
def train_encoder_unlearn_threedatasets(args, models, train_loaders, optimizers, criterions, epoch):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[optimizer] = optimizers
[b_train_dataloader, o_train_dataloader, w_train_dataloader] = train_loaders
[criteron, _, domain_criterion] = criterions
regressor_loss = 0
domain_loss = 0
encoder.train()
regressor.train()
domain_predictor.train()
true_domains = []
pred_domains = []
batches = 0
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (w_data, w_target, w_domain)) in enumerate(zip(b_train_dataloader, o_train_dataloader, w_train_dataloader)):
max_batch = len(b_data)
n1 = np.random.randint(1, max_batch - 2) # Must be at least one from each
n2 = np.random.randint(1, max_batch - n1 - 1)
n3 = max_batch - n1 - n2
if n3 < 1:
assert ValueError('N3 must be greater that zero')
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
w_data = w_data[:n3]
w_target = w_target[:n3]
w_domain = w_domain[:n3]
data = torch.cat((b_data, o_data, w_data), 0)
target = torch.cat((b_target, o_target, w_target), 0)
domain_target = torch.cat((b_domain, o_domain, w_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size :
batches += 1
# First update the encoder and regressor
optimizer.zero_grad()
features = encoder(data)
output_pred = regressor(features)
domain_pred = domain_predictor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:n1+n2], target[n1:n1+n2])
loss_3 = criteron(output_pred[n1+n2:], target[n1+n2:])
r_loss = loss_1 + loss_2 + loss_3
d_loss = domain_criterion(domain_pred, domain_target)
loss = r_loss + args.alpha * d_loss
loss.backward()
optimizer.step()
regressor_loss += r_loss
domain_loss += d_loss
domains = np.argmax(domain_pred.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(domains)
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\t Regressor Loss: {:.6f}'.format(
epoch, (batch_idx+1) * len(data), len(b_train_dataloader.dataset),
100. * (batch_idx+1) / len(b_train_dataloader), r_loss.item()), flush=True)
print('Regressor Loss: {:.4f}'.format(r_loss, flush=True))
print('Domain Loss: {:.4f}'.format(d_loss, flush=True))
del target
del r_loss
del d_loss
del features
av_loss = regressor_loss / batches
av_dom_loss = domain_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nTraining set: Average loss: {:.4f}'.format(av_loss, flush=True))
print('Training set: Average Domain loss: {:.4f}'.format(av_dom_loss, flush=True))
print('Training set: Average Acc: {:.4f}'.format(acc, flush=True))
return av_loss, acc, av_dom_loss, np.NaN
def train_encoder_domain_unlearn_distinct(args, models, train_loaders, optimizers, criterions, epoch):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[optimizer] = optimizers
[b_train_dataloader, o_train_dataloader, _, _] = train_loaders
[criteron, _, domain_criterion] = criterions
regressor_loss = 0
domain_loss = 0
encoder.train()
regressor.train()
domain_predictor.train()
true_domains = []
pred_domains = []
batches = 0
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain)) in enumerate(zip(b_train_dataloader, o_train_dataloader)):
n1 = np.random.randint(1, len(b_data)-1)
n2 = len(b_data) - n1
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
data = torch.cat((b_data, o_data), 0)
target = torch.cat((b_target, o_target), 0)
domain_target = torch.cat((b_domain, o_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size :
batches += 1
# First update the encoder and regressor for now dont improve the domain stuff, just the feature predictions
optimizer.zero_grad()
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:], target[n1:])
loss = loss_1 + loss_2
regressor_loss += loss
output_dm = domain_predictor(features.detach())
loss_dm = domain_criterion(output_dm, domain_target)
loss = loss + loss_dm
loss.backward()
optimizer.step()
domain_loss += loss_dm
output_dm_conf = np.argmax(output_dm.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(np.array(domain_target))
pred_domains.append(np.array(output_dm_conf))
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\t Regressor Loss: {:.6f}'.format(
epoch, (batch_idx+1) * len(data), len(b_train_dataloader.dataset),
100. * (batch_idx+1) / len(b_train_dataloader), loss.item()), flush=True)
del target
del features
del loss
av_loss = regressor_loss / batches
av_dom = domain_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nTraining set: Average loss: {:.4f}'.format(av_loss, flush=True))
print('Training set: Average Dom loss: {:.4f}'.format(av_dom, flush=True))
print('Training set: Average Acc: {:.4f}\n'.format(acc, flush=True))
return av_loss, acc, av_dom, np.NaN
def val_encoder_unlearn_threedatasets(args, models, val_loaders, criterions):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[b_val_dataloader, o_val_dataloader, w_val_dataloader] = val_loaders
[criteron, _, domain_criterion] = criterions
encoder.eval()
regressor.eval()
domain_predictor.eval()
regressor_loss = 0
domain_loss = 0
true_domains = []
pred_domains = []
batches = 0
with torch.no_grad():
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain), (w_data, w_target, w_domain)) in enumerate(zip(b_val_dataloader, o_val_dataloader, w_val_dataloader)):
max_batch = len(b_data)
n1 = np.random.randint(1, max_batch - 2) # Must be at least one from each
n2 = np.random.randint(1, max_batch - n1 - 1)
n3 = max_batch - n1 - n2
if n3 < 1:
assert ValueError('N3 must be greater that zero')
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
w_data = w_data[:n3]
w_target = w_target[:n3]
w_domain = w_domain[:n3]
data = torch.cat((b_data, o_data, w_data), 0)
target = torch.cat((b_target, o_target, w_target), 0)
domain_target = torch.cat((b_domain, o_domain, w_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size:
batches += 1
features = encoder(data)
output_pred = regressor(features)
domain_pred = domain_predictor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:n1+n2], target[n1:n1+n2])
loss_3 = criteron(output_pred[n1+n2:], target[n1+n2:])
r_loss = loss_1 + loss_2 + loss_3
d_loss = domain_criterion(domain_pred, domain_target)
domains = np.argmax(domain_pred.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(domains)
regressor_loss += r_loss
domain_loss += d_loss
val_loss = regressor_loss / batches
dom_loss = domain_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
acc = accuracy_score(true_domains, pred_domains)
print('\nValidation set: Average loss: {:.4f}\n'.format(val_loss, flush=True))
print('Validation set: Average Domain loss: {:.4f}\n'.format(dom_loss, flush=True))
print(' Validation set: Average Acc: {:.4f}'.format(acc, flush=True))
return val_loss, acc
def val_encoder_domain_unlearn_distinct(args, models, val_loaders, criterions):
cuda = torch.cuda.is_available()
[encoder, regressor, domain_predictor] = models
[b_val_dataloader, o_val_dataloader, _, _] = val_loaders
[criteron, _, _] = criterions
encoder.eval()
regressor.eval()
domain_predictor.eval()
val_loss = 0
true_domains = []
pred_domains = []
batches = 0
with torch.no_grad():
for batch_idx, ((b_data, b_target, b_domain), (o_data, o_target, o_domain)) in enumerate(zip(b_val_dataloader, o_val_dataloader)):
n1 = np.random.randint(1, len(b_data) - 1)
n2 = len(b_data) - n1
b_data = b_data[:n1]
b_target = b_target[:n1]
b_domain = b_domain[:n1]
o_data = o_data[:n2]
o_target = o_target[:n2]
o_domain = o_domain[:n2]
data = torch.cat((b_data, o_data), 0)
target = torch.cat((b_target, o_target), 0)
domain_target = torch.cat((b_domain, o_domain), 0)
if cuda:
data, target, domain_target = data.cuda(), target.cuda(), domain_target.cuda()
data, target, domain_target = Variable(data), Variable(target), Variable(domain_target)
if list(data.size())[0] == args.batch_size:
batches += 1
features = encoder(data)
output_pred = regressor(features)
loss_1 = criteron(output_pred[:n1], target[:n1])
loss_2 = criteron(output_pred[n1:], target[n1:] )
loss = loss_1 + loss_2
val_loss += loss
domains = domain_predictor.forward(features)
domains = np.argmax(domains.detach().cpu().numpy(), axis=1)
domain_target = np.argmax(domain_target.detach().cpu().numpy(), axis=1)
true_domains.append(domain_target)
pred_domains.append(domains)
val_loss = val_loss / batches
true_domains = np.array(true_domains).reshape(-1)
pred_domains = np.array(pred_domains).reshape(-1)
val_acc = accuracy_score(true_domains, pred_domains)
print('\nValidation set: Average loss: {:.4f}'.format(val_loss, flush=True))
print('Validation set: Average Acc: {:.4f}\n'.format(val_acc, flush=True))
return val_loss, val_acc