-
Notifications
You must be signed in to change notification settings - Fork 1
/
ACDC_Ablation_B.py
1323 lines (1203 loc) · 76.3 KB
/
ACDC_Ablation_B.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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Marcus Vinicius Sousa Leite de Carvalho
# marcus.decarvalho@ntu.edu.sg
# ivsucram@gmail.com
#
# NANYANG TECHNOLOGICAL UNIVERSITY - NTUITIVE PTE LTD Dual License Agreement
# Non-Commercial Use Only
# This NTUITIVE License Agreement, including all exhibits ("NTUITIVE-LA") is a legal agreement between you and NTUITIVE (or “we”) located at 71 Nanyang Drive, NTU Innovation Centre, #01-109, Singapore 637722, a wholly owned subsidiary of Nanyang Technological University (“NTU”) for the software or data identified above, which may include source code, and any associated materials, text or speech files, associated media and "online" or electronic documentation and any updates we provide in our discretion (together, the "Software").
#
# By installing, copying, or otherwise using this Software, found at https://github.com/Ivsucram/ATL_Matlab, you agree to be bound by the terms of this NTUITIVE-LA. If you do not agree, do not install copy or use the Software. The Software is protected by copyright and other intellectual property laws and is licensed, not sold. If you wish to obtain a commercial royalty bearing license to this software please contact us at marcus.decarvalho@ntu.edu.sg.
#
# SCOPE OF RIGHTS:
# You may use, copy, reproduce, and distribute this Software for any non-commercial purpose, subject to the restrictions in this NTUITIVE-LA. Some purposes which can be non-commercial are teaching, academic research, public demonstrations and personal experimentation. You may also distribute this Software with books or other teaching materials, or publish the Software on websites, that are intended to teach the use of the Software for academic or other non-commercial purposes.
# You may not use or distribute this Software or any derivative works in any form for commercial purposes. Examples of commercial purposes would be running business operations, licensing, leasing, or selling the Software, distributing the Software for use with commercial products, using the Software in the creation or use of commercial products or any other activity which purpose is to procure a commercial gain to you or others.
# If the Software includes source code or data, you may create derivative works of such portions of the Software and distribute the modified Software for non-commercial purposes, as provided herein.
# If you distribute the Software or any derivative works of the Software, you will distribute them under the same terms and conditions as in this license, and you will not grant other rights to the Software or derivative works that are different from those provided by this NTUITIVE-LA.
# If you have created derivative works of the Software, and distribute such derivative works, you will cause the modified files to carry prominent notices so that recipients know that they are not receiving the original Software. Such notices must state: (i) that you have changed the Software; and (ii) the date of any changes.
#
# You may not distribute this Software or any derivative works.
# In return, we simply require that you agree:
# 1. That you will not remove any copyright or other notices from the Software.
# 2. That if any of the Software is in binary format, you will not attempt to modify such portions of the Software, or to reverse engineer or decompile them, except and only to the extent authorized by applicable law.
# 3. That NTUITIVE is granted back, without any restrictions or limitations, a non-exclusive, perpetual, irrevocable, royalty-free, assignable and sub-licensable license, to reproduce, publicly perform or display, install, use, modify, post, distribute, make and have made, sell and transfer your modifications to and/or derivative works of the Software source code or data, for any purpose.
# 4. That any feedback about the Software provided by you to us is voluntarily given, and NTUITIVE shall be free to use the feedback as it sees fit without obligation or restriction of any kind, even if the feedback is designated by you as confidential.
# 5. THAT THE SOFTWARE COMES "AS IS", WITH NO WARRANTIES. THIS MEANS NO EXPRESS, IMPLIED OR STATUTORY WARRANTY, INCLUDING WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ANY WARRANTY AGAINST INTERFERENCE WITH YOUR ENJOYMENT OF THE SOFTWARE OR ANY WARRANTY OF TITLE OR NON-INFRINGEMENT. THERE IS NO WARRANTY THAT THIS SOFTWARE WILL FULFILL ANY OF YOUR PARTICULAR PURPOSES OR NEEDS. ALSO, YOU MUST PASS THIS DISCLAIMER ON WHENEVER YOU DISTRIBUTE THE SOFTWARE OR DERIVATIVE WORKS.
# 6. THAT NEITHER NTUITIVE NOR NTU NOR ANY CONTRIBUTOR TO THE SOFTWARE WILL BE LIABLE FOR ANY DAMAGES RELATED TO THE SOFTWARE OR THIS NTUITIVE-LA, INCLUDING DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL OR INCIDENTAL DAMAGES, TO THE MAXIMUM EXTENT THE LAW PERMITS, NO MATTER WHAT LEGAL THEORY IT IS BASED ON. ALSO, YOU MUST PASS THIS LIMITATION OF LIABILITY ON WHENEVER YOU DISTRIBUTE THE SOFTWARE OR DERIVATIVE WORKS.
# 7. That we have no duty of reasonable care or lack of negligence, and we are not obligated to (and will not) provide technical support for the Software.
# 8. That if you breach this NTUITIVE-LA or if you sue anyone over patents that you think may apply to or read on the Software or anyone's use of the Software, this NTUITIVE-LA (and your license and rights obtained herein) terminate automatically. Upon any such termination, you shall destroy all of your copies of the Software immediately. Sections 3, 4, 5, 6, 7, 8, 11 and 12 of this NTUITIVE-LA shall survive any termination of this NTUITIVE-LA.
# 9. That the patent rights, if any, granted to you in this NTUITIVE-LA only apply to the Software, not to any derivative works you make.
# 10. That the Software may be subject to U.S. export jurisdiction at the time it is licensed to you, and it may be subject to additional export or import laws in other places. You agree to comply with all such laws and regulations that may apply to the Software after delivery of the software to you.
# 11. That all rights not expressly granted to you in this NTUITIVE-LA are reserved.
# 12. That this NTUITIVE-LA shall be construed and controlled by the laws of the Republic of Singapore without regard to conflicts of law. If any provision of this NTUITIVE-LA shall be deemed unenforceable or contrary to law, the rest of this NTUITIVE-LA shall remain in full effect and interpreted in an enforceable manner that most nearly captures the intent of the original language.
#
# Copyright (c) NTUITIVE. All rights reserved.
from ACDCDataManipulator import DataManipulator
from NeuralNetwork import NeuralNetwork
from AutoEncoder import DenoisingAutoEncoder
from MySingletons import MyDevice
from colorama import Fore, Back, Style
from itertools import cycle
import numpy as np
import matplotlib.pylab as plt
import math
import torch
import time
def __copy_weights(source: NeuralNetwork, targets: list, layer_numbers=None, copy_moment: bool = True):
if layer_numbers is None:
layer_numbers = [1]
if type(targets) is not list:
targets = [targets]
for layer_number in layer_numbers:
layer_number -= 1
for target in targets:
if layer_number >= source.number_hidden_layers:
target.output_weight = source.output_weight.detach()
target.output_bias = source.output_bias.detach()
if copy_moment:
target.output_momentum = source.output_momentum.detach()
target.output_bias_momentum = source.output_bias_momentum.detach()
else:
target.weight[layer_number] = source.weight[layer_number].detach()
target.bias[layer_number] = source.bias[layer_number].detach()
if copy_moment:
target.momentum[layer_number] = source.momentum[layer_number].detach()
target.bias_momentum[layer_number] = source.bias_momentum[layer_number].detach()
def __grow_nodes(*networks):
origin = networks[0]
if origin.growable[origin.number_hidden_layers]:
nodes = 1
for i in range(nodes):
for network in networks:
network.grow_node(origin.number_hidden_layers)
return True
else:
return False
def __prune_nodes(*networks):
origin = networks[0]
if origin.prunable[origin.number_hidden_layers][0] >= 0:
nodes_to_prune = origin.prunable[origin.number_hidden_layers].tolist()
for network in networks:
for node_to_prune in nodes_to_prune[::-1]:
network.prune_node(origin.number_hidden_layers, node_to_prune)
return True
return False
def __width_evolution(network: NeuralNetwork, x: torch.tensor, y: torch.tensor = None):
if y is None:
y = x
network.feedforward(x, y)
network.width_adaptation_stepwise(y)
def __discriminative(network: NeuralNetwork, x: torch.tensor, y: torch.tensor = None, is_neg_grad: bool = False):
y = x.detach() if y is None else y
network.train(x=x, y=y, is_neg_grad=is_neg_grad)
def __generative(network: DenoisingAutoEncoder, x: torch.tensor, y: torch.tensor = None,
is_tied_weight=True, noise_ratio=0.1, glw_epochs: int = 1):
y = x.detach() if y is None else y
network.greedy_layer_wise_pretrain(x=x, number_epochs=glw_epochs, noise_ratio=noise_ratio)
network.train(x=x, y=y, noise_ratio=noise_ratio, is_tied_weight=is_tied_weight)
def __test(network: NeuralNetwork, x: torch.tensor, y: torch.tensor = None,
is_source: bool = False, is_discriminative: bool = False, metrics=None):
with torch.no_grad():
y = x.detach() if y is None else y
network.test(x=x, y=y)
if is_source:
if is_discriminative:
metrics['classification_rate_source'].append(network.classification_rate)
metrics['classification_source_loss'].append(float(network.loss_value))
metrics['classification_source_misclassified'].append(float(network.misclassified))
else:
metrics['reconstruction_source_loss'].append(float(network.loss_value))
else:
if is_discriminative:
metrics['classification_rate_target'].append(network.classification_rate)
metrics['classification_target_loss'].append(float(network.loss_value))
metrics['classification_target_misclassified'].append(float(network.misclassified))
else:
metrics['reconstruction_target_loss'].append(float(network.loss_value))
def __force_same_size(a_tensor, b_tensor, shuffle=True, strategy='max'):
common = np.min([a_tensor.shape[0], b_tensor.shape[0]])
if shuffle:
a_tensor = a_tensor[torch.randperm(a_tensor.shape[0])]
b_tensor = b_tensor[torch.randperm(b_tensor.shape[0])]
if strategy == 'max':
if math.ceil(a_tensor.shape[0] / common) <= math.ceil(b_tensor.shape[0] / common):
b_tensor = torch.stack(list(target for target, source
in zip(b_tensor[torch.randperm(b_tensor.shape[0])],
cycle(a_tensor[torch.randperm(a_tensor.shape[0])]))))
a_tensor = torch.stack(list(source for target, source
in zip(b_tensor[torch.randperm(b_tensor.shape[0])],
cycle(a_tensor[torch.randperm(a_tensor.shape[0])]))))
else:
b_tensor = torch.stack(list(target for target, source
in zip(cycle(b_tensor[torch.randperm(b_tensor.shape[0])]),
a_tensor[torch.randperm(a_tensor.shape[0])])))
a_tensor = torch.stack(list(source for target, source
in zip(cycle(b_tensor[torch.randperm(b_tensor.shape[0])]),
a_tensor[torch.randperm(a_tensor.shape[0])])))
elif strategy == 'min':
a_tensor = a_tensor[:common]
b_tensor = b_tensor[:common]
if shuffle:
a_tensor = a_tensor[torch.randperm(a_tensor.shape[0])]
b_tensor = b_tensor[torch.randperm(b_tensor.shape[0])]
return a_tensor, b_tensor
def __print_annotation(lst):
def custom_range(xx):
step = int(len(xx) * 0.25) - 1
return range(0, len(xx), 1 if step == 0 else step)
for idx in custom_range(lst):
pos = lst[idx] if isinstance(lst[idx], (int, float, np.int32)) else lst[idx][0]
plt.annotate(format(pos, '.2f'), (idx, pos))
pos = lst[-1] if isinstance(lst[-1], (int, float, np.int32)) else lst[-1][0]
plt.annotate(format(pos, '.2f'), (len(lst), pos))
def __plot_time(train_time: np.ndarray,
test_time: np.ndarray,
annotation=True):
plt.title('Processing time')
plt.ylabel('Seconds')
plt.xlabel('Minibatches')
plt.plot(train_time, linewidth=1,
label=('Train time: %f (Mean) %f (Accumulated)' %
(np.nanmean(train_time), np.sum(train_time))))
plt.plot(test_time, linewidth=1,
label=('Test time: %f (Mean) %f (Accumulated)' %
(np.nanmean(test_time), np.sum(test_time))))
plt.legend()
if annotation:
__print_annotation(train_time)
__print_annotation(test_time)
plt.tight_layout()
plt.show()
def __plot_node_evolution(nodes_discriminator: np.ndarray,
nodes_domain_classifier: np.ndarray,
nodes_feature_extraction: np.ndarray,
annotation=True):
plt.title('Node evolution')
plt.ylabel('Nodes')
plt.xlabel('Minibatches')
plt.plot(nodes_discriminator, linewidth=1,
label=('Discriminator HL nodes: %f (Mean) %d (Final)' %
(np.nanmean(nodes_discriminator), nodes_discriminator[-1])))
plt.plot(nodes_domain_classifier, linewidth=1,
label=('Domain Classifier HL nodes: %f (Mean) %d (Final)' %
(np.nanmean(nodes_domain_classifier), nodes_domain_classifier[-1])))
plt.plot(nodes_feature_extraction, linewidth=1,
label=('Feature Extraction HL nodes: %f (Mean) %d (Final)' %
(np.nanmean(nodes_feature_extraction), nodes_feature_extraction[-1])))
plt.legend()
if annotation:
__print_annotation(nodes_discriminator)
__print_annotation(nodes_domain_classifier)
__print_annotation(nodes_feature_extraction)
plt.tight_layout()
plt.show()
def __plot_losses(classification_source_loss: np.ndarray,
classification_target_loss: np.ndarray,
reconstruction_source_loss: np.ndarray,
reconstruction_target_loss: np.ndarray,
domain_classifier_loss: np.ndarray,
annotation=True):
plt.title('Losses evolution')
plt.ylabel('Loss value')
plt.xlabel('Minibatches')
plt.plot(classification_source_loss, linewidth=1,
label=('Classification Source Loss mean: %f' %
(np.nanmean(classification_source_loss))))
plt.plot(classification_target_loss, linewidth=1,
label=('Classification Target Loss mean: %f' %
(np.nanmean(classification_target_loss))))
plt.plot(reconstruction_source_loss, linewidth=1,
label=('Reconstruction Source Loss mean: %f' %
(np.nanmean(reconstruction_source_loss))))
plt.plot(reconstruction_target_loss, linewidth=1,
label=('Reconstruction Target Loss mean: %f' %
(np.nanmean(reconstruction_target_loss))))
plt.plot(domain_classifier_loss, linewidth=1,
label=('Domain Classifier Loss mean: %f' %
(np.nanmean(domain_classifier_loss))))
plt.legend()
if annotation:
__print_annotation(classification_source_loss)
__print_annotation(classification_target_loss)
__print_annotation(reconstruction_source_loss)
__print_annotation(reconstruction_target_loss)
__print_annotation(domain_classifier_loss)
plt.tight_layout()
plt.show()
def __plot_classification_rates(source_rate: np.ndarray,
target_rate: np.ndarray,
domain_rate: np.ndarray,
total_source_rate: float,
total_target_rate: float,
total_domain_classification_rate: float,
annotation=True,
class_number=None):
plt.title('Source and Target Classification Rates')
plt.ylabel('Classification Rate')
plt.xlabel('Minibatches')
plt.plot(source_rate, linewidth=1, label=('Source CR: %f (batch) | %f (dataset)' %
(np.nanmean(source_rate), total_source_rate)))
plt.plot(target_rate, linewidth=1, label=('Target CR: %f (batch) | %f (dataset)' %
(np.nanmean(target_rate), total_target_rate)))
plt.plot(domain_rate, linewidth=1, label=('Domain CR: %f (batch) | %f (dataset)' %
(np.nanmean(domain_rate), total_domain_classification_rate)))
if annotation:
__print_annotation(source_rate)
__print_annotation(target_rate)
__print_annotation(domain_rate)
if class_number is not None:
plt.plot(np.ones(len(source_rate)) * 1 / class_number,
linewidth=1, label='Random Classification Threshold: %f' % (1 / class_number))
plt.plot(np.ones(len(source_rate)) * 1 / 2,
linewidth=1, label='Random Domain Classification Threshold: %f' % (1 / 2))
plt.legend()
plt.tight_layout()
plt.show()
def __plot_ns(bias, var, ns, annotation=True):
plt.plot(bias, linewidth=1, label=('Bias mean: %f' % (np.nanmean(bias))))
plt.plot(var, linewidth=1, label=('Variance mean: %f' % (np.nanmean(var))))
plt.plot(ns, linewidth=1, label=('NS (Bias + Variance) mean: %f' % (np.nanmean(ns))))
plt.legend()
if annotation:
__print_annotation(bias)
__print_annotation(var)
__print_annotation(ns)
plt.tight_layout()
plt.show()
def __plot_discriminative_network_significance(bias, var, annotation=True):
plt.title('Discriminative Network Significance')
plt.ylabel('Value')
plt.xlabel('Sample')
__plot_ns(bias, var, (np.array(bias) + np.array(var)).tolist(), annotation)
def __plot_domain_classifier_network_significance(bias, var, annotation=True):
plt.title('Domain Classifier Network Significance')
plt.ylabel('Value')
plt.xlabel('Sample')
__plot_ns(bias, var, (np.array(bias) + np.array(var)).tolist(), annotation)
def __plot_feature_extractor_network_significance(bias, var, annotation=True):
plt.title('Feature Extractor Network Significance')
plt.ylabel('Value')
plt.xlabel('Sample')
__plot_ns(bias, var, (np.array(bias) + np.array(var)).tolist(), annotation)
def __load_source_target(source: str, target: str, n_source_concept_drift: int = 1, n_target_concept_drift: int = 1):
dm_s = DataManipulator()
dm_t = DataManipulator()
source = source.replace('_', '-').replace(' ', '-').lower()
target = target.replace('_', '-').replace(' ', '-').lower()
if source == 'mnist-28':
dm_s.load_mnist(resize=28, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-26':
dm_s.load_mnist(resize=26, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-24':
dm_s.load_mnist(resize=24, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-22':
dm_s.load_mnist(resize=22, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-20':
dm_s.load_mnist(resize=20, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-18':
dm_s.load_mnist(resize=18, n_concept_drifts=n_source_concept_drift)
elif source == 'mnist-16':
dm_s.load_mnist(resize=16, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-28':
dm_s.load_usps(resize=28, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-26':
dm_s.load_usps(resize=26, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-24':
dm_s.load_usps(resize=24, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-22':
dm_s.load_usps(resize=22, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-20':
dm_s.load_usps(resize=20, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-18':
dm_s.load_usps(resize=18, n_concept_drifts=n_source_concept_drift)
elif source == 'usps-16':
dm_s.load_usps(resize=16, n_concept_drifts=n_source_concept_drift)
elif source == 'cifar10':
dm_s.load_cifar10(n_concept_drifts=n_source_concept_drift)
elif source == 'stl10':
dm_s.load_stl10(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-fashion':
dm_s.load_amazon_review_fashion(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-all-beauty':
dm_s.load_amazon_review_all_beauty(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-appliances':
dm_s.load_amazon_review_appliances(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-arts-crafts-sewing':
dm_s.load_amazon_review_arts_crafts_sewing(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-automotive':
dm_s.load_amazon_review_automotive(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-books':
dm_s.load_amazon_review_books(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-cds-vinyl':
dm_s.load_amazon_review_cds_vinyl(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-cellphones_accessories':
dm_s.load_amazon_review_cellphones_accessories(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-clothing-shoes-jewelry':
dm_s.load_amazon_review_clothing_shoes_jewelry(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-digital-music':
dm_s.load_amazon_review_digital_music(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-electronics':
dm_s.load_amazon_review_electronics(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-gift-card':
dm_s.load_amazon_review_gift_card(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-grocery-gourmet-food':
dm_s.load_amazon_review_grocery_gourmet_food(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-home-kitchen':
dm_s.load_amazon_review_home_kitchen(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-industrial-scientific':
dm_s.load_amazon_review_industrial_scientific(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-kindle-store':
dm_s.load_amazon_review_kindle_store(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-luxury-beauty':
dm_s.load_amazon_review_luxury_beauty(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-magazine-subscription':
dm_s.load_amazon_review_magazine_subscription(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-movies-tv':
dm_s.load_amazon_review_movies_tv(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-musical-instruments':
dm_s.load_amazon_review_musical_instruments(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-office-products':
dm_s.load_amazon_review_office_products(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-patio-lawn-garden':
dm_s.load_amazon_review_patio_lawn_garden(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-pet-supplies':
dm_s.load_amazon_review_pet_supplies(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-prime-pantry':
dm_s.load_amazon_review_prime_pantry(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-software':
dm_s.load_amazon_review_software(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-sports-outdoors':
dm_s.load_amazon_review_sports_outdoors(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-tools-home-improvements':
dm_s.load_amazon_review_tools_home_improvements(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-toys-games':
dm_s.load_amazon_review_toys_games(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-video-games':
dm_s.load_amazon_review_video_games(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-nips-books':
dm_s.load_amazon_review_nips_books(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-nips-dvd':
dm_s.load_amazon_review_nips_dvd(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-nips-electronics':
dm_s.load_amazon_review_nips_electronics(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-nips-kitchen':
dm_s.load_amazon_review_nips_kitchen(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-apparel':
dm_s.load_amazon_review_acl_apparel(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-automotive':
dm_s.load_amazon_review_acl_automotive(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-baby':
dm_s.load_amazon_review_acl_baby(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-beauty':
dm_s.load_amazon_review_acl_beauty(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-books':
dm_s.load_amazon_review_acl_books(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-camera_photo':
dm_s.load_amazon_review_acl_camera_photo(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-cell_phones_service':
dm_s.load_amazon_review_acl_cell_phones_service(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-computer_video_games':
dm_s.load_amazon_review_acl_computer_video_games(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-dvd':
dm_s.load_amazon_review_acl_dvd(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-electronics':
dm_s.load_amazon_review_acl_electronics(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-gourmet_food':
dm_s.load_amazon_review_acl_gourmet_food(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-grocery':
dm_s.load_amazon_review_acl_grocery(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-health_personal_care':
dm_s.load_amazon_review_acl_health_personal_care(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-jewelry_watches':
dm_s.load_amazon_review_acl_jewelry_watches(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-kitchen_housewares':
dm_s.load_amazon_review_acl_kitchen_housewares(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-magazines':
dm_s.load_amazon_review_acl_magazines(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-music':
dm_s.load_amazon_review_acl_music(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-musical_instruments':
dm_s.load_amazon_review_acl_musical_instruments(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-office_products':
dm_s.load_amazon_review_acl_office_products(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-outdoor_living':
dm_s.load_amazon_review_acl_outdoor_living(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-software':
dm_s.load_amazon_review_acl_software(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-sports_outdoors':
dm_s.load_amazon_review_acl_sports_outdoors(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-tools_hardware':
dm_s.load_amazon_review_acl_tools_hardware(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-toys_games':
dm_s.load_amazon_review_acl_toys_games(n_concept_drifts=n_source_concept_drift)
elif source == 'amazon-review-acl-video':
dm_s.load_amazon_review_acl_video(n_concept_drifts=n_source_concept_drift)
elif source == 'news-obama-all':
dm_s.load_news_popularity_obama_all(n_concept_drifts=n_source_concept_drift)
elif source == 'news-economy-all':
dm_s.load_news_popularity_economy_all(n_concept_drifts=n_source_concept_drift)
elif source == 'news-microsoft-all':
dm_s.load_news_popularity_microsoft_all(n_concept_drifts=n_source_concept_drift)
elif source == 'news-palestine-all':
dm_s.load_news_popularity_palestine_all(n_concept_drifts=n_source_concept_drift)
elif source == 'news-obama-facebook':
dm_s.load_news_popularity_obama_facebook(n_concept_drifts=n_source_concept_drift)
elif source == 'news-economy-facebook':
dm_s.load_news_popularity_economy_facebook(n_concept_drifts=n_source_concept_drift)
elif source == 'news-microsoft-facebook':
dm_s.load_news_popularity_microsoft_facebook(n_concept_drifts=n_source_concept_drift)
elif source == 'news-palestine-facebook':
dm_s.load_news_popularity_palestine_facebook(n_concept_drifts=n_source_concept_drift)
elif source == 'news-obama-googleplus':
dm_s.load_news_popularity_obama_googleplus(n_concept_drifts=n_source_concept_drift)
elif source == 'news-economy-googleplus':
dm_s.load_news_popularity_economy_googleplus(n_concept_drifts=n_source_concept_drift)
elif source == 'news-microsoft-googleplus':
dm_s.load_news_popularity_microsoft_googleplus(n_concept_drifts=n_source_concept_drift)
elif source == 'news-palestine-googleplus':
dm_s.load_news_popularity_palestine_googleplus(n_concept_drifts=n_source_concept_drift)
elif source == 'news-obama-linkedin':
dm_s.load_news_popularity_obama_linkedin(n_concept_drifts=n_source_concept_drift)
elif source == 'news-economy-linkedin':
dm_s.load_news_popularity_economy_linkedin(n_concept_drifts=n_source_concept_drift)
elif source == 'news-microsoft-linkedin':
dm_s.load_news_popularity_microsoft_linkedin(n_concept_drifts=n_source_concept_drift)
elif source == 'news-palestine-linkedin':
dm_s.load_news_popularity_palestine_linkedin(n_concept_drifts=n_source_concept_drift)
if target == 'mnist-28':
dm_t.load_mnist(resize=28, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-26':
dm_t.load_mnist(resize=26, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-24':
dm_t.load_mnist(resize=24, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-22':
dm_t.load_mnist(resize=22, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-20':
dm_t.load_mnist(resize=20, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-18':
dm_t.load_mnist(resize=18, n_concept_drifts=n_target_concept_drift)
elif target == 'mnist-16':
dm_t.load_mnist(resize=16, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-28':
dm_t.load_usps(resize=28, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-26':
dm_t.load_usps(resize=26, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-24':
dm_t.load_usps(resize=24, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-22':
dm_t.load_usps(resize=22, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-20':
dm_t.load_usps(resize=20, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-18':
dm_t.load_usps(resize=18, n_concept_drifts=n_target_concept_drift)
elif target == 'usps-16':
dm_t.load_usps(resize=16, n_concept_drifts=n_target_concept_drift)
elif target == 'cifar10':
dm_t.load_cifar10(n_concept_drifts=n_target_concept_drift)
elif target == 'stl10':
dm_t.load_stl10(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-fashion':
dm_t.load_amazon_review_fashion(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-all-beauty':
dm_t.load_amazon_review_all_beauty(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-appliances':
dm_t.load_amazon_review_appliances(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-arts-crafts-sewing':
dm_t.load_amazon_review_arts_crafts_sewing(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-automotive':
dm_t.load_amazon_review_automotive(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-books':
dm_t.load_amazon_review_books(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-cds-vinyl':
dm_t.load_amazon_review_cds_vinyl(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-cellphones_accessories':
dm_t.load_amazon_review_cellphones_accessories(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-clothing-shoes-jewelry':
dm_t.load_amazon_review_clothing_shoes_jewelry(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-digital-music':
dm_t.load_amazon_review_digital_music(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-electronics':
dm_t.load_amazon_review_electronics(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-gift-card':
dm_t.load_amazon_review_gift_card(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-grocery-gourmet-food':
dm_t.load_amazon_review_grocery_gourmet_food(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-home-kitchen':
dm_t.load_amazon_review_home_kitchen(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-industrial-scientific':
dm_t.load_amazon_review_industrial_scientific(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-kindle-store':
dm_t.load_amazon_review_kindle_store(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-luxury-beauty':
dm_t.load_amazon_review_luxury_beauty(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-magazine-subscription':
dm_t.load_amazon_review_magazine_subscription(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-movies-tv':
dm_t.load_amazon_review_movies_tv(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-musical-instruments':
dm_t.load_amazon_review_musical_instruments(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-office-products':
dm_t.load_amazon_review_office_products(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-patio-lawn-garden':
dm_t.load_amazon_review_patio_lawn_garden(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-pet-supplies':
dm_t.load_amazon_review_pet_supplies(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-prime-pantry':
dm_t.load_amazon_review_prime_pantry(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-software':
dm_t.load_amazon_review_software(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-sports-outdoors':
dm_t.load_amazon_review_sports_outdoors(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-tools-home-improvements':
dm_t.load_amazon_review_tools_home_improvements(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-toys-games':
dm_t.load_amazon_review_toys_games(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-video-games':
dm_t.load_amazon_review_video_games(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-nips-books':
dm_t.load_amazon_review_nips_books(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-nips-dvd':
dm_t.load_amazon_review_nips_dvd(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-nips-electronics':
dm_t.load_amazon_review_nips_electronics(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-nips-kitchen':
dm_t.load_amazon_review_nips_kitchen(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-apparel':
dm_t.load_amazon_review_acl_apparel(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-automotive':
dm_t.load_amazon_review_acl_automotive(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-baby':
dm_t.load_amazon_review_acl_baby(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-beauty':
dm_t.load_amazon_review_acl_beauty(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-books':
dm_t.load_amazon_review_acl_books(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-camera_photo':
dm_t.load_amazon_review_acl_camera_photo(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-cell_phones_service':
dm_t.load_amazon_review_acl_cell_phones_service(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-computer_video_games':
dm_t.load_amazon_review_acl_computer_video_games(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-dvd':
dm_t.load_amazon_review_acl_dvd(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-electronics':
dm_t.load_amazon_review_acl_electronics(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-gourmet_food':
dm_t.load_amazon_review_acl_gourmet_food(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-grocery':
dm_t.load_amazon_review_acl_grocery(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-health_personal_care':
dm_t.load_amazon_review_acl_health_personal_care(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-jewelry_watches':
dm_t.load_amazon_review_acl_jewelry_watches(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-kitchen_housewares':
dm_t.load_amazon_review_acl_kitchen_housewares(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-magazines':
dm_t.load_amazon_review_acl_magazines(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-music':
dm_t.load_amazon_review_acl_music(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-musical_instruments':
dm_t.load_amazon_review_acl_musical_instruments(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-office_products':
dm_t.load_amazon_review_acl_office_products(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-outdoor_living':
dm_t.load_amazon_review_acl_outdoor_living(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-software':
dm_t.load_amazon_review_acl_software(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-sports_outdoors':
dm_t.load_amazon_review_acl_sports_outdoors(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-tools_hardware':
dm_t.load_amazon_review_acl_tools_hardware(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-toys_games':
dm_t.load_amazon_review_acl_toys_games(n_concept_drifts=n_target_concept_drift)
elif target == 'amazon-review-acl-video':
dm_t.load_amazon_review_acl_video(n_concept_drifts=n_target_concept_drift)
elif target == 'news-obama-all':
dm_t.load_news_popularity_obama_all(n_concept_drifts=n_target_concept_drift)
elif target == 'news-economy-all':
dm_t.load_news_popularity_economy_all(n_concept_drifts=n_target_concept_drift)
elif target == 'news-microsoft-all':
dm_t.load_news_popularity_microsoft_all(n_concept_drifts=n_target_concept_drift)
elif target == 'news-palestine-all':
dm_t.load_news_popularity_palestine_all(n_concept_drifts=n_target_concept_drift)
elif target == 'news-obama-facebook':
dm_t.load_news_popularity_obama_facebook(n_concept_drifts=n_target_concept_drift)
elif target == 'news-economy-facebook':
dm_t.load_news_popularity_economy_facebook(n_concept_drifts=n_target_concept_drift)
elif target == 'news-microsoft-facebook':
dm_t.load_news_popularity_microsoft_facebook(n_concept_drifts=n_target_concept_drift)
elif target == 'news-palestine-facebook':
dm_t.load_news_popularity_palestine_facebook(n_concept_drifts=n_target_concept_drift)
elif target == 'news-obama-googleplus':
dm_t.load_news_popularity_obama_googleplus(n_concept_drifts=n_target_concept_drift)
elif target == 'news-economy-googleplus':
dm_t.load_news_popularity_economy_googleplus(n_concept_drifts=n_target_concept_drift)
elif target == 'news-microsoft-googleplus':
dm_t.load_news_popularity_microsoft_googleplus(n_concept_drifts=n_target_concept_drift)
elif target == 'news-palestine-googleplus':
dm_t.load_news_popularity_palestine_googleplus(n_concept_drifts=n_target_concept_drift)
elif target == 'news-obama-linkedin':
dm_t.load_news_popularity_obama_linkedin(n_concept_drifts=n_target_concept_drift)
elif target == 'news-economy-linkedin':
dm_t.load_news_popularity_economy_linkedin(n_concept_drifts=n_target_concept_drift)
elif target == 'news-microsoft-linkedin':
dm_t.load_news_popularity_microsoft_linkedin(n_concept_drifts=n_target_concept_drift)
elif target == 'news-palestine-linkedin':
dm_t.load_news_popularity_palestine_linkedin(n_concept_drifts=n_target_concept_drift)
return dm_s, dm_t
def acdc(source, target,
n_source_concept_drift: int = 5,
n_target_concept_drift: int = 7,
internal_epochs: int = 1, is_gpu=False):
def print_metrics(minibatch, metrics, DMs, DMt, NN, DAEt, DA):
print('Minibatch: %d | Execution time (dataset load/pre-processing + model run): %f' % (
minibatch, time.time() - metrics['start_execution_time']))
if minibatch > 1:
print((
'Total of samples:' + Fore.BLUE + ' %d + %d = %d/%d (%.2f%%) Source' + Style.RESET_ALL + ' |' + Fore.RED + ' %d + %d = %d/%d (%.2f%%) Target' + Style.RESET_ALL + ' | %d/%d (%.2f%%) Samples in total') % (
metrics['number_evaluated_samples_source'][-2],
metrics['number_evaluated_samples_source'][-1] - metrics['number_evaluated_samples_source'][-2],
metrics['number_evaluated_samples_source'][-1],
DMs.number_samples(),
float(metrics['number_evaluated_samples_source'][-1] / DMs.number_samples()) * 100,
metrics['number_evaluated_samples_target'][-2],
metrics['number_evaluated_samples_target'][-1] - metrics['number_evaluated_samples_target'][-2],
metrics['number_evaluated_samples_target'][-1],
DMt.number_samples(),
float(metrics['number_evaluated_samples_target'][-1] / DMt.number_samples()) * 100,
metrics['number_evaluated_samples_source'][-1] + metrics['number_evaluated_samples_target'][-1],
DMs.number_samples() + DMt.number_samples(),
float((metrics['number_evaluated_samples_source'][-1] +
metrics['number_evaluated_samples_target'][-1]) / (
DMs.number_samples() + DMt.number_samples())) * 100))
else:
print((
'Total of samples:' + Fore.BLUE + ' %d/%d (%.2f%%) Source' + Style.RESET_ALL + ' |' + Fore.RED + ' %d/%d (%.2f%%) Target' + Style.RESET_ALL + ' | %d/%d (%.2f%%) Samples in total') % (
metrics['number_evaluated_samples_source'][-1],
DMs.number_samples(),
float(metrics['number_evaluated_samples_source'][-1] / DMs.number_samples()) * 100,
metrics['number_evaluated_samples_target'][-1],
DMt.number_samples(),
float(metrics['number_evaluated_samples_target'][-1] / DMt.number_samples()) * 100,
metrics['number_evaluated_samples_source'][-1] + metrics['number_evaluated_samples_target'][-1],
DMs.number_samples() + DMt.number_samples(),
float((metrics['number_evaluated_samples_source'][-1] +
metrics['number_evaluated_samples_target'][-1]) / (
DMs.number_samples() + DMt.number_samples())) * 100))
if minibatch > 1:
string_max = '' + Fore.GREEN + 'Max' + Style.RESET_ALL
string_mean = '' + Fore.YELLOW + 'Mean' + Style.RESET_ALL
string_min = '' + Fore.RED + 'Min' + Style.RESET_ALL
string_now = '' + Fore.BLUE + 'Now' + Style.RESET_ALL
string_accu = '' + Fore.MAGENTA + 'Accu' + Style.RESET_ALL
print((
'%s %s %s %s %s Training time:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Fore.MAGENTA + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now, string_accu,
np.max(metrics['train_time']),
np.nanmean(metrics['train_time']),
np.min(metrics['train_time']),
metrics['train_time'][-1],
np.sum(metrics['train_time'])))
print((
'%s %s %s %s %s Testing time:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Fore.MAGENTA + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now, string_accu,
np.max(metrics['test_time']),
np.nanmean(metrics['test_time']),
np.min(metrics['test_time']),
metrics['test_time'][-1],
np.sum(metrics['test_time'])))
print((
'%s %s %s %s CR Source:' + Fore.GREEN + ' %f%% ' + Back.BLUE + Fore.YELLOW + Style.BRIGHT + '%f%%' + Style.RESET_ALL + Fore.RED + ' %f%%' + Fore.BLUE + ' %f%%' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['classification_rate_source']) * 100,
np.nanmean(metrics['classification_rate_source']) * 100,
np.min(metrics['classification_rate_source']) * 100,
metrics['classification_rate_source'][-1] * 100))
print((
'%s %s %s %s CR Target:' + Fore.GREEN + ' %f%% ' + Back.RED + Fore.YELLOW + Style.BRIGHT + '%f%%' + Style.RESET_ALL + Fore.RED + ' %f%%' + Fore.BLUE + ' %f%%' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['classification_rate_target']) * 100,
np.nanmean(metrics['classification_rate_target']) * 100,
np.min(metrics['classification_rate_target']) * 100,
metrics['classification_rate_target'][-1] * 100))
print((
'%s %s %s %s CR Domain Discriminator:' + Fore.GREEN + ' %f%% ' + Fore.YELLOW + '%f%%' + Style.RESET_ALL + Fore.RED + ' %f%%' + Fore.BLUE + ' %f%%' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['classification_rate_domain']) * 100,
np.nanmean(metrics['classification_rate_domain']) * 100,
np.min(metrics['classification_rate_domain']) * 100,
metrics['classification_rate_domain'][-1] * 100))
print((
'%s %s %s %s Classification Source Loss:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['classification_source_loss']),
np.nanmean(metrics['classification_source_loss']),
np.min(metrics['classification_source_loss']),
metrics['classification_source_loss'][-1]))
print((
'%s %s %s %s Classification Target Loss:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['classification_target_loss']),
np.nanmean(metrics['classification_target_loss']),
np.min(metrics['classification_target_loss']),
metrics['classification_target_loss'][-1]))
print((
'%s %s %s %s Domain Discriminator Loss:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['domain_regression_loss']),
np.nanmean(metrics['domain_regression_loss']),
np.min(metrics['domain_regression_loss']),
metrics['domain_regression_loss'][-1]))
print((
'%s %s %s %s Reconstruction Source Loss:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['reconstruction_source_loss']),
np.nanmean(metrics['reconstruction_source_loss']),
np.min(metrics['reconstruction_source_loss']),
metrics['reconstruction_source_loss'][-1]))
print((
'%s %s %s %s Reconstruction Target Loss:' + Fore.GREEN + ' %f' + Fore.YELLOW + ' %f' + Fore.RED + ' %f' + Fore.BLUE + ' %f' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['reconstruction_target_loss']),
np.nanmean(metrics['reconstruction_target_loss']),
np.min(metrics['reconstruction_target_loss']),
metrics['reconstruction_target_loss'][-1]))
print((
'%s %s %s %s Discriminator Nodes:' + Fore.GREEN + ' %d' + Fore.YELLOW + ' %f' + Fore.RED + ' %d' + Fore.BLUE + ' %d' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['node_evolution_discriminator']),
np.nanmean(metrics['node_evolution_discriminator']),
np.min(metrics['node_evolution_discriminator']),
metrics['node_evolution_discriminator'][-1]))
print((
'%s %s %s %s Denoising Autoencoder Nodes:' + Fore.GREEN + ' %d' + Fore.YELLOW + ' %f' + Fore.RED + ' %d' + Fore.BLUE + ' %d' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['node_evolution_feature_extraction']),
np.nanmean(metrics['node_evolution_feature_extraction']),
np.min(metrics['node_evolution_feature_extraction']),
metrics['node_evolution_feature_extraction'][-1]))
print((
'%s %s %s %s Domain Classifier Nodes:' + Fore.GREEN + ' %d' + Fore.YELLOW + ' %f' + Fore.RED + ' %d' + Fore.BLUE + ' %d' + Style.RESET_ALL) % (
string_max, string_mean, string_min, string_now,
np.max(metrics['node_evolution_domain_classifier']),
np.nanmean(metrics['node_evolution_domain_classifier']),
np.min(metrics['node_evolution_domain_classifier']),
metrics['node_evolution_domain_classifier'][-1]))
print(('Network structure:' + Fore.BLUE + ' %s' + Style.RESET_ALL) % (
" ".join(map(str, NN.layers))))
print(('Domain Discriminator structure:' + Fore.GREEN + ' %s' + Style.RESET_ALL) % (
" ".join(map(str, DA.layers))))
print(('Denoising Auto Encoder:' + Fore.RED + ' %s' + Style.RESET_ALL) % (
" ".join(map(str, DAEt.layers))))
print(Style.RESET_ALL)
metrics = {'classification_rate_source': [],
'classification_rate_target': [],
'classification_rate_domain': [],
'number_evaluated_samples_source': [],
'number_evaluated_samples_target': [],
'train_time': [],
'test_time': [],
'node_evolution_discriminator': [],
'node_evolution_domain_classifier': [],
'node_evolution_feature_extraction': [],
'classification_target_loss': [],
'classification_source_loss': [],
'reconstruction_source_loss': [],
'reconstruction_target_loss': [],
'domain_regression_loss': [],
'classification_source_misclassified': [],
'classification_target_misclassified': [],
'domain_classification_misclassified': [],
'start_execution_time': time.time()}
MyDevice().set(is_gpu=is_gpu)
internal_epochs = internal_epochs if internal_epochs >= 1 else 1
SOURCE_DOMAIN_LABEL = torch.tensor([[1, 0]], dtype=torch.float, device=MyDevice().get())
TARGET_DOMAIN_LABEL = torch.tensor([[0, 1]], dtype=torch.float, device=MyDevice().get())
dm_s, dm_t = __load_source_target(source, target, n_source_concept_drift, n_target_concept_drift)
dae = DenoisingAutoEncoder([dm_s.number_features(),
100,
dm_s.number_features()])
nn = NeuralNetwork([dm_s.number_features(),
dae.layers[1],
100,
dm_s.number_classes()])
da = NeuralNetwork([dm_s.number_features(),
dae.layers[1],
100,
2])
count_source = 0
count_target = 0
count_window = 0
window_size = 1000
batch_counter = 0
x_source = []
y_source = []
x_target = []
y_target = []
while count_source < dm_s.number_samples() \
or count_target < dm_t.number_samples():
if count_window < window_size \
and (count_source < dm_s.number_samples()
or count_target < dm_t.number_samples()):
source_prob = (dm_s.number_samples() - count_source) / (
dm_s.number_samples() - count_source + dm_t.number_samples() - count_target + 0.)
if (np.random.rand() <= source_prob and count_source < dm_s.number_samples()) or (
count_target >= dm_t.number_samples() and count_source < dm_s.number_samples()):
x, y = dm_s.get_x_y(count_source)
x_source.append(x)
y_source.append(y)
count_source += 1
count_window += 1
elif count_target < dm_t.number_samples():
x, y = dm_t.get_x_y(count_target)
x_target.append(x)
y_target.append(y)
count_target += 1
count_window += 1
else:
batch_counter += 1
metrics['number_evaluated_samples_source'].append(count_source)
metrics['number_evaluated_samples_target'].append(count_target)
# Workaround to avoid empty stream
if batch_counter > 1:
if (count_source - metrics['number_evaluated_samples_source'][-2] == 0):
x, y = dm_s.get_x_y(np.random.randint(0, count_source))
x_source.append(x)
y_source.append(y)
if (count_target - metrics['number_evaluated_samples_target'][-2] == 0):
x, y = dm_t.get_x_y(np.random.randint(0, count_target))
x_target.append(x)
y_target.append(y)
# Workaround to avoid empty stream
x_source = torch.tensor(x_source, dtype=torch.float, device=MyDevice().get())
y_source = torch.tensor(y_source, dtype=torch.float, device=MyDevice().get())
x_target = torch.tensor(x_target, dtype=torch.float, device=MyDevice().get())
y_target = torch.tensor(y_target, dtype=torch.float, device=MyDevice().get())
# TEST
if batch_counter > 1:
metrics['test_time'].append(time.time())
__test(network=nn, x=x_source, y=y_source,
is_source=True, is_discriminative=True, metrics=metrics)
__test(network=nn, x=x_target, y=y_target,
is_source=False, is_discriminative=True, metrics=metrics)
__test(network=dae, x=x_source,
is_source=True, is_discriminative=False, metrics=metrics)
__test(network=dae, x=x_target,
is_source=False, is_discriminative=False, metrics=metrics)
da.test(x=torch.cat([x_source, x_target]),
y=torch.cat([SOURCE_DOMAIN_LABEL.repeat(x_source.shape[0], 1),
TARGET_DOMAIN_LABEL.repeat(x_target.shape[0], 1)]))
metrics['domain_regression_loss'].append(float(da.loss_value))
metrics['classification_rate_domain'].append(da.classification_rate)
metrics['domain_classification_misclassified'].append(da.misclassified)
metrics['test_time'][-1] = time.time() - metrics['test_time'][-1]
# TRAIN
metrics['train_time'].append(time.time())
common_source, x_target = __force_same_size(torch.cat((x_source.T, y_source.T)).T, x_target)
x_source, y_source = common_source.T.split(x_source.shape[1])
x_source, y_source = x_source.T, y_source.T
epoch = 1
while epoch <= internal_epochs:
for xs, xt, ys in [(xs.view(1, xs.shape[0]), xt.view(1, xt.shape[0]), ys.view(1, ys.shape[0]))
for xs, xt, ys in zip(x_source, x_target, cycle(y_source))]:
# Evolving
# if epoch == 1:
# # Evolving Feature Extraction
# for j in range(0, 2):
# if j == 0:
# __width_evolution(network=dae, x=xs, y=xt)
# elif i == 1:
# __width_evolution(network=dae, x=xt, y=xs)
# if __grow_nodes(dae, da, nn):
# __copy_weights(source=dae, targets=[da, nn], layer_numbers=[1], copy_moment=False)