-
Notifications
You must be signed in to change notification settings - Fork 1
/
gan_src.py
1953 lines (1607 loc) · 77.4 KB
/
gan_src.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
from __future__ import print_function
import os, sys, time, argparse
from datetime import date
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import matplotlib.pyplot as plt
import math
from absl import app
from absl import flags
import json
import glob
from sklearn.manifold import TSNE
from tqdm.autonotebook import tqdm
import shutil
import tensorflow_probability as tfp
tfd = tfp.distributions
# import tensorflow_gan as tfgan
# import prd_score as prd
##FOR FID
from numpy import cov
from numpy import trace
from scipy.linalg import sqrtm
import scipy as sp
from numpy import iscomplexobj
# from gan_data import *
# from arch_mnist import *
# from arch_u1 import *
####NOTE : 15thJune2020 - Cleaned up KLD calculator. sorted folder creation ops here. Need to remove them elsewheres. Need to clean print KLD,FID function.
# FLAGS = flags.FLAGS
# FLAGS(sys.argv)
# # tf.keras.backend.set_floatx('float64')
# if FLAGS.loss == 'deq':
# from arch/arch_deq import *
# elif FLAGS.topic == 'CycleGAN':
# from arch_CycleGAN import *
# elif FLAGS.topic == 'RumiGAN':
# from arch_RumiGAN import *
# else:
from arch import *
from ops import *
from gan_metrics import *
'''
GAN_ARCH Consists of the common parts of GAN architectures, speficially, the calls to the sub architecture classes from the respective files, and the calls for FID evaluations. Each ARCH_data_* class has archtectures corresponding to that dataset learning and for the loss case ( Autoencoder structures for DEQ case, etc.)
'''
'''***********************************************************************************
********** GAN Source Class -- All the basics and metrics ****************************
***********************************************************************************'''
class GAN_SRC(eval('ARCH_'+FLAGS.data), GAN_Metrics):
def __init__(self,FLAGS_dict):
''' Defines anything common to te diofferent GAN approaches. Architectures of Gen and Disc, all flags,'''
for name,val in FLAGS_dict.items():
exec('self.'+name+' = val')
# if self.colab:
# if self.pbar_flag:
# warnings.warn("Repeated updation of the tqdm progress bar on Colab can cause OOM on Colab, resulting in pkill, or OOM on the local system, causing the browser to hang.",ResourceWarning)
# if self.latex_plot_flag:
# warnings.warn("Plotting latex on colab require insalling the texlive library in your colab instance. Not doing so will case errors while plotting.",ImportWarning)
# if self.colab and (self.data in ['mnist', 'celeba', 'cifar10']):
# self.bar_flag = 0
# else:
# self.bar_flag = 1
if self.device == '-1':
self.device = '/CPU'
elif self.device == '':
self.device = '/CPU'
else:
self.device = '/GPU:'+self.device
print(self.device)
# if self.device!='-1':
# gpus = tf.config.list_logical_devices('GPU')
# print(gpus)
# gpus = ['GPU:0', 'GPU:1']
# self.strategy = tf.distribute.experimental.CentralStorageStrategy(gpus)
# self.strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(gpus)
# self.strategy = tf.distribute.MirroredStrategy()
# self.strategy = tf.distribute.OneDeviceStrategy(device=self.device)
# self.strategy = tf.distribute.MirroredStrategy(gpus, cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
# with tf.device(self.device):
# with self.strategy.scope():
self.batch_size = tf.constant(self.batch_size,dtype='int64')
self.fid_batch_size = tf.constant(100,dtype='int64')
self.num_epochs = tf.constant(self.num_epochs,dtype='int64')
self.Dloop = tf.constant(self.Dloop,dtype='int64')
self.Gloop = tf.constant(self.Gloop,dtype='int64')
self.lr_D = tf.constant(self.lr_D)
self.lr_G = tf.constant(self.lr_G)
self.beta1 = tf.constant(self.beta1)
self.total_count = tf.Variable(0,dtype='int64')
## with was till here
eval('ARCH_'+self.data+'.__init__(self)')
if self.topic == 'GANdem':
self.num_to_print = 8
else:
self.num_to_print = int(min(10,np.sqrt(self.batch_size)))
if self.mode in ['test','metrics']:
self.num_test_images = 20
else:
self.num_test_images = 10
if self.data in ['mnist']:
self.test_steps = 500
else:
self.test_steps = 1000
if self.gan in ['WAE', 'MMDGAN']:
self.postfix = {0: f'{0:3.0f}', 1: f'{0:2.3e}', 2: f'{0:2.3e}', 3: f'{0:2.3e}'}
self.bar_format = '{n_fmt}/{total_fmt} |{bar}| {rate_fmt} Batch: {postfix[0]} ETA: {remaining} Time: {elapsed} D_Loss: {postfix[1]} G_Loss: {postfix[2]} AE_Loss: {postfix[3]}'
else:
self.postfix = {0: f'{0:3.0f}', 1: f'{0:2.3e}', 2: f'{0:2.3e}'}
self.bar_format = '{n_fmt}/{total_fmt} |{bar}| {rate_fmt} Batch: {postfix[0]} ETA: {remaining} Elapsed Time: {elapsed} D_Loss: {postfix[1]} G_Loss: {postfix[2]}'
if self.log_folder == 'default':
today = date.today()
self.log_dir = 'logs/Log_Folder_'+today.strftime("%d%m%Y")+'/'
else:
self.log_dir = self.log_folder
if self.log_dir[-1] != '/':
self.log_dir += '/'
self.run_id_flag = self.run_id
self.create_run_location()
# self.timestr = time.strftime("%Y%m%d-%H%M%S")
if self.res_flag == 1:
self.res_file = open(self.run_loc+'/'+self.run_id+'_Results.txt','a')
FLAGS.append_flags_into_file(self.run_loc+'/'+self.run_id+'_Flags.txt')
print(self.run_id, self.log_folder, self.log_dir)
# with self.strategy.scope():
GAN_Metrics.__init__(self)
def create_run_location(self):
''' If resuming, locate the file to resule and set the current running direcrtory. Else, create one based on the data cases given.'''
''' Create for/ Create base logs folder'''
pwd = os.popen('pwd').read().strip('\n')
if not os.path.exists(pwd+'/logs'):
os.mkdir(pwd+'/logs')
''' Create log folder / Check for existing log folder'''
if os.path.exists(self.log_dir):
print("Directory " , self.log_dir , " already exists")
else:
os.mkdir(self.log_dir)
print("Directory " , self.log_dir , " Created ")
if self.resume:
self.run_loc = self.log_dir + self.run_id
print("Resuming from folder {}".format(self.run_loc))
else:
print("No RunID specified. Logs will be saved in a folder based on FLAGS")
today = date.today()
d1 = today.strftime("%d%m%Y")
if self.topic == 'SpiderGAN':
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + self.noise_data + '_' + self.data + '_' + self.arch + '_' + self.gan + '_' + self.loss
elif self.topic == 'PolyGAN':
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + 'RBFm' + str(self.rbf_m) + '_' + self.data + str(self.latent_dims) + '_' + self.arch + '_' + self.gan + '_' + self.loss
elif self.topic == 'ScoreGAN' and self.gan in ['WGAN', 'WGANFlow']:
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + 'RBFm' + str(self.rbf_m) + '_' + self.data + str(self.latent_dims) + '_' + self.arch + '_' + self.gan + '_' + self.loss_norm + 'Norm' + '_' + self.loss
elif self.topic == 'SnakeGAN':
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + 'SnakeIters' + str(self.num_snake_iters) + self.snake_kind + '_' + self.data + str(self.latent_dims) + '_' + self.arch + '_' + self.gan + '_' + self.loss
elif self.topic == 'ELeGANt':
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + self.data + str(self.latent_dims) + '_' + self.arch + '_L' +str(self.L) + '_Sigma' + str(int(self.sigma)) + '_Terms' + str(self.terms) + '_' + self.gan + '_' + self.loss
else:
self.run_id = d1 +'_'+ self.topic + '_' + self.noise_kind + '_' + self.data + '_' + self.arch + '_' + self.gan + '_' + self.loss
# self.run_id = d1 +'_'+ self.topic + '_' + self.data + '_' + self.gan + '_' + self.loss
self.run_loc = self.log_dir + self.run_id
runs = sorted(glob.glob(self.run_loc+'*/'))
print(runs)
if len(runs) == 0:
curnum = 0
else:
curnum = int(runs[-1].split('_')[-1].split('/')[0])
print(curnum)
if self.run_id_flag == 'new':
self.curnum = curnum+1
else:
self.curnum = curnum
if self.run_id_flag != 'same' and os.path.exists(self.run_loc + '_' + str(self.curnum).zfill(2)):
x = input("You will be OVERWRITING existing DATA. ENTER to continue, type N to create new ")
if x in ['N','n']:
self.curnum += 1
self.run_loc += '_'+str(self.curnum).zfill(2)
if os.path.exists(self.run_loc):
print("Directory " , self.run_loc , " already exists")
else:
if self.resume:
print("Cannot resume. Specified log does not exist")
else:
os.mkdir(self.run_loc)
print("Directory " , self.run_loc , " Created ")
self.checkpoint_dir = self.run_loc+'/checkpoints'
if os.path.exists(self.checkpoint_dir):
print("Checkpoint directory " , self.checkpoint_dir , " already exists")
else:
os.mkdir(self.checkpoint_dir)
print("Checkpoint directory " , self.checkpoint_dir , " Created ")
self.im_dir = self.run_loc+'/Images'
if os.path.exists(self.im_dir):
print("Images directory " , self.im_dir , " already exists")
else:
os.mkdir(self.im_dir)
print("Images directory " , self.im_dir , " Created ")
self.impath = self.im_dir + '/Images_'
self.metric_dir = self.run_loc+'/Metrics'
if os.path.exists(self.metric_dir):
print("Metrics directory " , self.metric_dir , " already exists")
else:
os.mkdir(self.metric_dir)
print("Metrics directory " , self.metric_dir , " Created ")
self.metricpath = self.metric_dir + '/Metrics_'
if self.FID_kind == 'clean':
self.FIDreals_dir = self.run_loc+'/FID_reals_'+self.mode
if os.path.exists(self.FIDreals_dir):
print("FID Reals directory " , self.FIDreals_dir , " already exists")
else:
os.mkdir(self.FIDreals_dir)
print("FID Reals directory " , self.FIDreals_dir , " Created ")
self.FIDRealspath = self.FIDreals_dir + '/Image_'
if self.FID_kind == 'clean':
self.FIDfakes_dir = self.run_loc+'/FID_fakes_'+self.mode
if os.path.exists(self.FIDfakes_dir):
print("FID Fakes directory " , self.FIDfakes_dir , " already exists")
else:
os.mkdir(self.FIDfakes_dir)
print("FID Fakes directory " , self.FIDfakes_dir , " Created ")
self.FIDFakespath = self.FIDfakes_dir + '/Image_'
if 'ReconFID' in self.metrics:
self.ReconFIDreals_dir = self.run_loc+'/ReconFID_reals_'+self.mode
if os.path.exists(self.ReconFIDreals_dir):
print("ReconFID Reals directory " , self.ReconFIDreals_dir , " already exists")
else:
os.mkdir(self.ReconFIDreals_dir)
print("ReconFID Reals directory " , self.ReconFIDreals_dir , " Created ")
self.ReconFIDRealspath = self.ReconFIDreals_dir + '/Image_'
if 'ReconFID' in self.metrics:
self.ReconFIDfakes_dir = self.run_loc+'/ReconFID_fakes_'+self.mode
if os.path.exists(self.ReconFIDfakes_dir):
print("ReconFID Fakes directory " , self.ReconFIDfakes_dir , " already exists")
else:
os.mkdir(self.ReconFIDfakes_dir)
print("ReconFID Fakes directory " , self.ReconFIDfakes_dir , " Created ")
self.ReconFIDFakespath = self.ReconFIDfakes_dir + '/Image_'
if 'interpol_figs' in self.metrics:
self.FIDinterpol_dir = self.run_loc+'/FID_interpol2_'+self.mode
if os.path.exists(self.FIDinterpol_dir):
print("FID Interpol directory " , self.FIDinterpol_dir , " already exists")
else:
os.mkdir(self.FIDinterpol_dir)
print("FID Interol directory " , self.FIDinterpol_dir , " Created ")
self.FIDInterpolpath = self.FIDinterpol_dir + '/Image_'
if 'DatasetFID' in self.metrics and self.mode == 'metrics':
self.DIDsrc_dir = self.run_loc+'/DID_src_'+self.mode
if os.path.exists(self.DIDsrc_dir):
print("DID Source directory " , self.DIDsrc_dir , " already exists")
else:
os.mkdir(self.DIDsrc_dir)
print("DID Source directory " , self.DIDsrc_dir , " Created ")
self.DIDsrcpath = self.DIDsrc_dir + '/Image_'
self.DIDtar_dir = self.run_loc+'/DID_tar_'+self.mode
if os.path.exists(self.DIDtar_dir):
print("DID Target directory " , self.DIDtar_dir , " already exists")
else:
os.mkdir(self.DIDtar_dir)
print("DID Target directory " , self.DIDtar_dir , " Created ")
self.DIDtarpath = self.DIDtar_dir + '/Image_'
if self.models_for_metrics or self.mode == 'model_metrics':
self.models_dir = self.run_loc+'/Metrics_Models'
if os.path.exists(self.models_dir):
print("FID Models directory " , self.models_dir , " already exists")
else:
os.mkdir(self.models_dir)
print("FID Models directory " , self.models_dir , " Created ")
self.modelspath = self.models_dir + '/Model_'
def get_terminal_width(self):
width = shutil.get_terminal_size(fallback=(200, 24))[0]
if width == 0:
width = 200
return width
def pbar(self, epoch):
bar = tqdm(total=(int(self.train_dataset_size*self.reps) // int(self.batch_size.numpy())) * int(self.batch_size.numpy()), ncols=int(self.get_terminal_width() * .9), desc=tqdm.write(f' \n Epoch {int(epoch)}/{int(self.num_epochs.numpy())}'), postfix=self.postfix, bar_format=self.bar_format, unit = ' Samples')
return bar
def generate_NeurIPS22_bias(self):
# print(self.fixed_images, self.fixed_images.shape)
path_in = self.impath + '_Current_Inputs.png'
path_out = self.impath + '_Current_Outputs.png'
for batch in self.fixed_image_dataset:
print_noise_ims = (batch + 1.0)/2.0
self.save_image_batch(images = print_noise_ims, label ='Input to Biased GAN', path = path_in)
predictions = self.generator(batch, training = False)
predictions = (predictions + 1.0)/2.0
self.save_image_batch(images = predictions, label ='Outputs of Biased GAN', path = path_out)
return
def generate_and_save_batch(self,epoch = 999):
### Setup path and label for images
if epoch == 51004:
label = 'Itertion {0}'.format(self.total_count.numpy()).zfill(10)
path = self.impath + '_Current_Output'
else:
label = 'Epoch {0}'.format(epoch)
path = self.impath + str(self.total_count.numpy()).zfill(10)
# noise = tf.random.normal([self.num_to_print*self.num_to_print, self.noise_dims], mean = self.noise_mean, stddev = self.noise_stddev)
if self.topic != 'GANdem' and self.gan not in ['WAE', 'Langevin']:
## flag that identifies that were updating same fig
if epoch != 51004:
noise = self.get_noise([self.num_to_print*self.num_to_print, self.noise_dims])
else:
noise = self.fixed_noise
### Generate the images to print based on the kind of GAN being trained
if self.topic in ['cGAN', 'ACGAN']:
class_vec = []
for i in range(self.num_classes):
class_vec.append(i*np.ones(int((self.num_to_print**2)/self.num_classes)))
class_final = np.expand_dims(np.concatenate(class_vec,axis = 0),axis = 1)
if self.label_style == 'base':
class_final = tf.one_hot(np.squeeze(class_final), depth = self.num_classes)
predictions = self.generator([noise,class_final], training=False)
elif self.gan in ['WAE','Langevin']:
#### AAE are Autoencoders, not generative models.
predictions = self.Decoder(self.Encoder(self.reals[0:self.num_to_print*self.num_to_print], training = False), training = False)
elif self.topic in ['SpiderGAN']:
for noise_batch in self.noise_dataset:
if not self.BaseTanGAN_flag:
path_noise = path.split('.')[0]+'_GAN_IPNoise.png'
print_noise_ims = (noise_batch + 1.0)/2.0
self.save_image_batch(images = print_noise_ims, label =label, path = path_noise, size = 7)
else:
self.noise_dims = 100
noise_batch = self.get_noise([self.batch_size, self.noise_dims])
# noise_batch = self.TanGAN_generator(noise_ip, training = False)
if self.TanGAN_flag == 1 or self.BaseTanGAN_flag == 1:
noise_batch = self.TanGAN_generator(noise_batch, training = False)
path_noise = path.split('.')[0]+'_GAN1_OP.png'
print_noise_ims = (noise_batch + 1.0)/2.0
self.save_image_batch(images = print_noise_ims, label =label, path = path_noise, size = 7)
predictions = self.generator(noise_batch, training = False)
break
elif self.topic in ['CondSpiderGAN']:
print('printing')
path_noise = path.split('.')[0]+'_GAN_IPNoise.png'
print_noise_ims = (self.plotfig_images + 1.0)/2.0
self.save_image_batch(images = print_noise_ims, label =label, path = path_noise, size = 7)
predictions = self.generator([self.plotfig_images, self.plotfig_labels], training = False)
# predictions = self.generator(self.plotfig_images, training = False)
elif self.topic in ['GANdem']:
for noise_batch in self.noise_dataset:
path_noise = path.split('.')[0]+'_GAN_IPNoise.png'
print_noise_ims = (noise_batch + 1.0)/2.0
self.save_image_batch(images = print_noise_ims, label =label, path = path_noise, size = 7)
# with tf.device('/GPU:0'):
# with self.strategy.scope():
# GAN1_op, GAN2_op, predictions = self.generator_full(noise_batch, training = False)
GAN1_op = self.generator_1(noise_batch, training = False)
# GAN2_op = self.generator_2(GAN1_op, training = False)
predictions = self.generator(GAN1_op, training = False)
## with was till here
path_GAN1op = path.split('.')[0]+'_GAN1_OP.png'
print_GAN1_ims = (GAN1_op + 1.0)/2.0
self.save_image_batch(images = print_GAN1_ims, label =label, path = path_GAN1op, size = 10)
# path_GAN2op = path.split('.')[0]+'_GAN2_OP.png'
# print_GAN2_ims = (GAN2_op + 1.0)/2.0
# self.save_image_batch(images = print_GAN2_ims, label =label, path = path_GAN2op, size = 14)
break
elif self.gan in ["WGAN_AE"]:
predictions = self.Decoder(self.generator(noise,training = False), training = False)
elif self.gan not in ["WGANFlow"]:
predictions = self.generator(noise, training=False)
else:
predictions = tf.zeros_like(noise)
if self.loss == 'FS' and self.data in ['mnist', 'svhn']:
predictions = tf.reshape(predictions, [predictions.shape[0],self.output_size,self.output_size,self.output_dims])
### Fix image ranges when relavant
if self.data != 'celeba' or self.gan in ['WAE','MMDGAN', 'WGAN_AE', 'Langevin'] or self.topic in ['CondSpiderGAN','SpiderGAN','GANdem']:
#### Baseline varinant's CelebA images, and all WAE output images are in [-1,1]
predictions = (predictions + 1.0)/2.0
### Call the corresponding display function based on the kind of GAN being trained
if self.data in ['g1', 'g2', 'gmm8', 'gmm2', 'gN', 'gmmN']:
eval(self.show_result_func)
elif self.topic == 'GANdem':
self.save_image_batch(images = predictions, label =label, path = path, size = 28)
else:
self.save_image_batch(images = predictions, label =label, path = path)
if self.gan in ['WAE', 'Langevin']:
if self.data == 'mnist' and self.latent_dims == 2:
self.print_mnist_latent(path = path)
else:
if epoch > self.AE_pretrain_epochs and self.gaussian_stats_flag:
self.print_gaussian_stats()
if epoch <= 2:
# path_reals = path.split('.')[0]+'gt.png'
path_reals = self.impath + str(self.total_count.numpy())+'gt.png'
reals_to_display = (self.reals[0:self.num_to_print*self.num_to_print] + 1.0)/2.0
self.save_image_batch(images = reals_to_display, label = label, path = path_reals)
def save_image_batch(self, images = None, label = 'Default Image Label', path = 'result.png', size = 14):
images_on_grid = self.image_grid(input_tensor = images[0:self.num_to_print*self.num_to_print], grid_shape = (self.num_to_print,self.num_to_print), image_shape=(images.shape[1], images.shape[2]),num_channels=images.shape[3])
fig1 = plt.figure(figsize=(size,size))
ax1 = fig1.add_subplot(111)
ax1.cla()
ax1.axis("off")
if images_on_grid.shape[2] == 3:
ax1.imshow(np.clip(images_on_grid,0.,1.))
else:
ax1.imshow(np.clip(images_on_grid[:,:,0],0.,1.), cmap='gray')
plt.title(label, fontsize=12)
plt.tight_layout()
plt.savefig(path)
plt.close()
def image_grid(self,input_tensor, grid_shape, image_shape=(32, 32), num_channels=3):
"""Arrange a minibatch of images into a grid to form a single image.
Args:
input_tensor: Tensor. Minibatch of images to format, either 4D
([batch size, height, width, num_channels]) or flattened
([batch size, height * width * num_channels]).
grid_shape: Sequence of int. The shape of the image grid,
formatted as [grid_height, grid_width].
image_shape: Sequence of int. The shape of a single image,
formatted as [image_height, image_width].
num_channels: int. The number of channels in an image.
Returns:
Tensor representing a single image in which the input images have been
arranged into a grid.
Raises:
ValueError: The grid shape and minibatch size don't match, or the image
shape and number of channels are incompatible with the input tensor.
"""
num_padding = int(np.ceil(0.02*image_shape[0]))
paddings = tf.constant([[0, 0], [num_padding, num_padding], [num_padding, num_padding], [0, 0]])
image_shape = (image_shape[0]+(2*num_padding), image_shape[1]+(2*num_padding))
input_tensor = tf.pad(input_tensor, paddings, "CONSTANT", constant_values = 1.0)
if grid_shape[0] * grid_shape[1] != int(input_tensor.shape[0]):
raise ValueError("Grid shape %s incompatible with minibatch size %i." %
(grid_shape, int(input_tensor.shape[0])))
if len(input_tensor.shape) == 2:
num_features = image_shape[0] * image_shape[1] * num_channels
if int(input_tensor.shape[1]) != num_features:
raise ValueError("Image shape and number of channels incompatible with "
"input tensor.")
elif len(input_tensor.shape) == 4:
if (int(input_tensor.shape[1]) != image_shape[0] or \
int(input_tensor.shape[2]) != image_shape[1] or \
int(input_tensor.shape[3]) != num_channels):
raise ValueError("Image shape and number of channels incompatible with input tensor. %s vs %s" % (input_tensor.shape, (image_shape[0], image_shape[1],num_channels)))
else:
raise ValueError("Unrecognized input tensor format.")
height, width = grid_shape[0] * image_shape[0], grid_shape[1] * image_shape[1]
input_tensor = tf.reshape(input_tensor, tuple(grid_shape) + tuple(image_shape) + (num_channels,))
input_tensor = tf.transpose(a = input_tensor, perm = [0, 1, 3, 2, 4])
input_tensor = tf.reshape(input_tensor, [grid_shape[0], width, image_shape[0], num_channels])
input_tensor = tf.transpose(a = input_tensor, perm = [0, 2, 1, 3])
input_tensor = tf.reshape(input_tensor, [1, height, width, num_channels])
return input_tensor[0]
#### SHIFT to WAE's MNIST arch function.
def print_mnist_latent(self, path = 'temp.png'):
print("Gaussian Stats : True mean {} True Cov {} \n Fake mean {} Fake Cov {}".format(np.mean(self.fakes_enc,axis = 0), np.cov(self.fakes_enc,rowvar = False), np.mean(self.reals_enc, axis = 0), np.cov(self.reals_enc,rowvar = False) ))
if self.res_flag:
self.res_file.write("Gaussian Stats : True mean {} True Cov {} \n Fake mean {} Fake Cov {}".format(np.mean(self.reals_enc, axis = 0), np.cov(self.reals_enc,rowvar = False), np.mean(self.fakes_enc, axis = 0), np.cov(self.fakes_enc,rowvar = False) ))
if self.colab==1 or self.latex_plot_flag==0:
from matplotlib.backends.backend_pdf import PdfPages
plt.rc('text', usetex=False)
else:
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
from matplotlib.backends.backend_pgf import PdfPages
plt.rcParams.update({
"pgf.texsystem": "pdflatex",
"font.family": "serif", # use serif/main font for text elements
"font.size":10,
"font.serif": [],
"text.usetex": True, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fonts from rc parameters
})
with PdfPages(path+'_distribution.pdf') as pdf:
fig1 = plt.figure(figsize=(3.5, 3.5))
ax1 = fig1.add_subplot(111)
ax1.cla()
ax1.get_xaxis().set_visible(False)
ax1.get_yaxis().set_visible(False)
ax1.set_xlim([-3,3])
ax1.set_ylim([-3,3])
ax1.scatter(self.fakes_enc[:,0], self.fakes_enc[:,1], c='r', linewidth = 1.5, label='Target Class Data', marker = '.')
ax1.scatter(self.reals_enc[:,0], self.reals_enc[:,1], c='b', linewidth = 1.5, label='Source Class Data', marker = '.')
ax1.legend(loc = 'upper right')
fig1.tight_layout()
pdf.savefig(fig1)
plt.close(fig1)
def print_gaussian_stats(self):
## Uncomment if you need Image Latent space statitics printed
print("Gaussian Stats : True mean {} True Cov {} \n Fake mean {} Fake Cov {}".format(np.mean(self.fakes_enc,axis = 0), np.cov(self.fakes_enc,rowvar = False), np.mean(self.reals_enc, axis = 0), np.cov(self.reals_enc,rowvar = False)))
if self.res_flag:# and num_epoch>self.AE_count:
self.res_file.write("Gaussian Stats : True mean {} True Cov {} \n Fake mean {} Fake Cov {}".format(np.mean(self.reals_enc, axis = 0), np.cov(self.reals_enc,rowvar = False), np.mean(self.fakes_enc, axis = 0), np.cov(self.fakes_enc,rowvar = False) ))
return
def h5_for_metrics(self):
if self.gan in ['WAE','Langevin']:
### WAEs have an Encoder and a Decoder instead of a generator
self.Encoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Encoder.h5', overwrite = True)
self.Decoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Decoder.h5', overwrite = True)
elif self.gan in ['WGA_AE']:
self.Encoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Encoder.h5', overwrite = True)
self.Decoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Decoder.h5', overwrite = True)
self.generator.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_generator.h5', overwrite = True)
else:
self.generator.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_generator.h5', overwrite = True)
if self.loss == 'FS':
### WGAN-FS's discriminator is 2 part: Disc-A and Disc-B
self.discriminator_A.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_discriminator_A.h5', overwrite = True)
self.discriminator_B.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_discriminator_B.h5', overwrite = True)
elif self.loss in ['RBF','score','snake']:
self.discriminator_RBF.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_discriminator_RBF.h5', overwrite = True)
if self.gan == 'MMDGAN':
self.Encoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Encoder.h5', overwrite = True)
self.Decoder.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_Decoder.h5', overwrite = True)
elif self.gan not in 'MMDGAN':
self.discriminator.save(self.modelspath + 'Iter'+str(self.total_count.numpy()).zfill(6)+'_discriminator.h5', overwrite = True)
return
def h5_from_checkpoint(self):
self.generate_and_save_batch(999)
if self.gan in ['WAE', 'Langevin']:
### WAEs have an Encoder and a Decoder instead of a generator
self.Encoder.save(self.checkpoint_dir + '/model_Encoder.h5', overwrite = True)
self.Decoder.save(self.checkpoint_dir + '/model_Decoder.h5', overwrite = True)
else:
self.generator.save(self.checkpoint_dir + '/model_generator.h5', overwrite = True)
if self.loss != 'FS':
### WGAN-FS's discriminator is 2 part: Disc-A and Disc-B
self.discriminator_A.save(self.checkpoint_dir + '/model_discriminator_A.h5', overwrite = True)
self.discriminator_B.save(self.checkpoint_dir + '/model_discriminator_B.h5', overwrite = True)
else:
self.discriminator.save(self.checkpoint_dir + '/model_discriminator.h5', overwrite = True)
return
# '''***********************************************************************************
# ********** GAN Arch ******************************************************************
# ***********************************************************************************'''
# class GAN_ARCH( eval('ARCH_'+FLAGS.data)): #mnist, ARCH_celeba, ARCG_g1, ARCH_g2, ARCH_gmm8, ARCH_comma): eval('ARCH_'+FLAGS.data),
# def __init__(self,FLAGS_dict):
# ''' Defines anything common to te diofferent GAN approaches. Architectures of Gen and Disc, all flags,'''
# for name,val in FLAGS_dict.items():
# exec('self.'+name+' = val')
# # self.topic = topic
# # self.data = data
# # self.loss = loss
# # self.gan_name = gan
# # self.mode = mode
# # self.colab = colab
# if self.colab and (self.data in ['mnist', 'svhn', 'celeba', 'cifar10', 'ukiyoe']):
# self.bar_flag = 0
# else:
# self.bar_flag = 1
# # self.metrics = metrics
# # self.num_parallel_calls = num_parallel_calls
# # self.saver = saver
# # self.resume = resume
# # self.res_flag = res_file
# # self.save_all = save_all_models
# # self.paper = paper
# if self.device == '-1':
# self.device = '/CPU'
# elif self.device == '-2':
# self.device = '/TPU'
# elif self.device == '':
# self.device = '/GPU'
# else:
# self.device = '/GPU:'+self.device
# print(self.device)
# with tf.device(self.device):
# self.batch_size = tf.constant(self.batch_size,dtype='int64')
# self.fid_batch_size = tf.constant(100,dtype='int64')
# self.num_epochs = tf.constant(self.num_epochs,dtype='int64')
# self.Dloop = tf.constant(self.Dloop,dtype='int64')
# self.Gloop = tf.constant(self.Gloop,dtype='int64')
# self.lr_D = tf.constant(self.lr_D)
# self.lr_G = tf.constant(self.lr_G)
# self.beta1 = tf.constant(self.beta1)
# self.total_count = tf.Variable(0,dtype='int64')
# ''' Sort out local special conditions. Higher learning rates for 1DG and DEQ. If printing for paper PDF, set up saving KLD for gaussians. '''
# if self.data in ['g1', 'g2', 'gmm2']:
# self.batch_size = tf.constant(500, dtype='int64')
# if self.data in ['gmm8' ]:
# self.batch_size = tf.constant(500, dtype='int64')
# eval('ARCH_'+FLAGS.data+'.__init__(self)')
# if self.data in ['g1', 'g2', 'gmm8', 'gmm2']:
# self.num_to_print = 1000
# else:
# self.num_to_print = 10
# if self.mode in ['test','metrics']:
# self.num_test_images = 20
# else:
# self.num_test_images = 10
# # if self.topic in['ACGAN', 'cGAN']:
# # ### Need to FIX
# # self.num_to_print = 10
# # if self.data != 'celeba':
# # self.num_to_print = self.num_classes**2
# # else:
# # self.num_to_print = self.num_classes*50
# if self.gan == 'WAE':
# self.postfix = {0: f'{0:3.0f}', 1: f'{0:2.3e}', 2: f'{0:2.3e}', 3: f'{0:2.3e}'}
# self.bar_format = '{n_fmt}/{total_fmt} |{bar}| {rate_fmt} Batch: {postfix[0]} ETA: {remaining} Time: {elapsed} D_Loss: {postfix[1]} G_Loss: {postfix[2]} AE_Loss: {postfix[3]}'
# else:
# self.postfix = {0: f'{0:3.0f}', 1: f'{0:2.3e}', 2: f'{0:2.3e}'}
# self.bar_format = '{n_fmt}/{total_fmt} |{bar}| {rate_fmt} Batch: {postfix[0]} ETA: {remaining} Elapsed Time: {elapsed} D_Loss: {postfix[1]} G_Loss: {postfix[2]}'
# # self.log_dir = 'logs/NIPS_May2020/RumiGAN_Cifar10_Compare/'
# # self.log_dir = 'logs/NIPS_May2020/RumiGAN_Fashion_Compare/RandomClasses/NewJUne/'#'logs/NIPS_May2020/RumiGAN_MNIST_Compares/Singles5MAny/' #'logs/NIPS_May2020/RumiGAN_CelebA_Compare/Males/'#'logs/NIPS_Mar2020/RumiGAN_Compares/Compare_Sharps/'
# ### NEEDS FIXING...NEEDS A FLAG
# # log_dir = 'logs/Log_Folder_03072020/'
# # log_dir = None
# if self.log_folder == 'default':
# today = date.today()
# self.log_dir = 'logs/Log_Folder_'+today.strftime("%d%m%Y")+'/'
# else:
# self.log_dir = self.log_folder#'logs/NIPS_June2020/'
# if self.log_dir[-1] != '/':
# self.log_dir += '/'
# self.run_id_flag = self.run_id
# self.create_run_location()
# self.setup_metrics()
# self.timestr = time.strftime("%Y%m%d-%H%M%S")
# if self.res_flag == 1:
# self.res_file = open(self.run_loc+'/'+self.run_id+'_Results.txt','a')
# FLAGS.append_flags_into_file(self.run_loc+'/'+self.run_id+'_Flags.txt')
# # js = json.dumps(flags.FLAGS.flag_values_dict())
# # f.write(js)
# # f.close()
# def create_run_location(self):
# ''' If resuming, locate the file to resule and set the current running direcrtory. Else, create one based on the data cases given.'''
# ''' Create log folder / Check for existing log folder'''
# if os.path.exists(self.log_dir):
# print("Directory " , self.log_dir , " already exists")
# else:
# os.mkdir(self.log_dir)
# print("Directory " , self.log_dir , " Created ")
# if self.resume:
# self.run_loc = self.log_dir + self.run_id
# print("Resuming from folder {}".format(self.run_loc))
# else:
# print("No RunID specified. Logs will be saved in a folder based on FLAGS")
# today = date.today()
# d1 = today.strftime("%d%m%Y")
# self.run_id = d1 +'_'+ self.topic + '_' + self.data + '_' + self.gan + '_' + self.loss
# self.run_loc = self.log_dir + self.run_id
# runs = sorted(glob.glob(self.run_loc+'*/'))
# print(runs)
# if len(runs) == 0:
# curnum = 0
# else:
# curnum = int(runs[-1].split('_')[-1].split('/')[0])
# print(curnum)
# if self.run_id_flag == 'new':
# self.curnum = curnum+1
# else:
# self.curnum = curnum
# if self.run_id_flag != 'same' and os.path.exists(self.run_loc + '_' + str(self.curnum).zfill(2)):
# x = input("You will be OVERWRITING existing DATA. ENTER to continue, type N to create new ")
# if x in ['N','n']:
# self.curnum += 1
# self.run_loc += '_'+str(self.curnum).zfill(2)
# if os.path.exists(self.run_loc):
# print("Directory " , self.run_loc , " already exists")
# else:
# if self.resume:
# print("Cannot resume. Specified log does not exist")
# else:
# os.mkdir(self.run_loc)
# print("Directory " , self.run_loc , " Created ")
# self.checkpoint_dir = self.run_loc+'/checkpoints'
# if os.path.exists(self.checkpoint_dir):
# print("Checkpoint directory " , self.checkpoint_dir , " already exists")
# else:
# os.mkdir(self.checkpoint_dir)
# print("Checkpoint directory " , self.checkpoint_dir , " Created ")
# self.im_dir = self.run_loc+'/Images'
# if os.path.exists(self.im_dir):
# print("Images directory " , self.im_dir , " already exists")
# else:
# os.mkdir(self.im_dir)
# print("Images directory " , self.im_dir , " Created ")
# self.impath = self.im_dir + '/Images_'
# if self.loss == 'FS' and self.gan != 'WAE':
# self.impath += self.latent_kind+'_'
# self.metric_dir = self.run_loc+'/Metrics'
# if os.path.exists(self.metric_dir):
# print("Metrics directory " , self.metric_dir , " already exists")
# else:
# os.mkdir(self.metric_dir)
# print("Metrics directory " , self.metric_dir , " Created ")
# self.metricpath = self.metric_dir + '/Metrics_'
# def get_terminal_width(self):
# width = shutil.get_terminal_size(fallback=(200, 24))[0]
# if width == 0:
# width = 120
# return width
# def pbar(self, epoch):
# bar = tqdm(total=(int(self.train_dataset_size*self.reps) // int(self.batch_size.numpy())) * int(self.batch_size.numpy()), ncols=int(self.get_terminal_width() * .9), desc=tqdm.write(f' \n Epoch {int(epoch)}/{int(self.num_epochs.numpy())}'), postfix=self.postfix, bar_format=self.bar_format, unit = ' Samples')
# return bar
# def generate_and_save_batch(self,epoch):
# noise = tf.random.normal([self.num_to_print*self.num_to_print, self.noise_dims], mean = self.noise_mean, stddev = self.noise_stddev)
# if self.topic == 'ImNoise2Im':
# for noise_batch in self.noise_dataset:
# noise = noise_batch[0:(self.num_to_print*self.num_to_print)]
# break
# path = self.impath + str(self.total_count.numpy())
# #### AAE are Autoencoders, not generative models.
# if self.gan == 'WAE':
# predictions = self.Decoder(self.Encoder(self.reals[0:self.num_to_print*self.num_to_print], training = False), training = False)
# elif self.topic in ['cGAN', 'ACGAN']:
# class_vec = []
# for i in range(self.num_classes):
# class_vec.append(i*np.ones(int((self.num_to_print**2)/self.num_classes)))
# class_final = np.expand_dims(np.concatenate(class_vec,axis = 0),axis = 1)
# if self.label_style == 'base':
# class_final = tf.one_hot(np.squeeze(class_final), depth = self.num_classes)
# predictions = self.generator([noise,class_final], training=False)
# else:
# predictions = self.generator(noise, training=False)
# if self.loss == 'FS':
# if self.latent_kind in ['AE','AAE']:
# predictions = self.Decoder(predictions, training= False)
# # if self.mode == 'test':
# # self.fakes = predictions
# # if not self.paper:
# if self.gan == 'WAE' or self.data not in ['celeba', 'ukiyoe']:
# predictions = (predictions + 1.0)/2.0
# eval(self.show_result_func)
# def image_grid(self,input_tensor, grid_shape, image_shape=(32, 32), num_channels=3):
# """Arrange a minibatch of images into a grid to form a single image.
# Args:
# input_tensor: Tensor. Minibatch of images to format, either 4D
# ([batch size, height, width, num_channels]) or flattened
# ([batch size, height * width * num_channels]).
# grid_shape: Sequence of int. The shape of the image grid,
# formatted as [grid_height, grid_width].
# image_shape: Sequence of int. The shape of a single image,
# formatted as [image_height, image_width].
# num_channels: int. The number of channels in an image.
# Returns:
# Tensor representing a single image in which the input images have been
# arranged into a grid.
# Raises:
# ValueError: The grid shape and minibatch size don't match, or the image
# shape and number of channels are incompatible with the input tensor.
# """
# num_padding = int(np.ceil(0.02*image_shape[0]))
# paddings = tf.constant([[0, 0], [num_padding, num_padding], [num_padding, num_padding], [0, 0]])
# image_shape = (image_shape[0]+(2*num_padding), image_shape[1]+(2*num_padding))
# input_tensor = tf.pad(input_tensor, paddings, "CONSTANT", constant_values = 1.0)
# if grid_shape[0] * grid_shape[1] != int(input_tensor.shape[0]):
# raise ValueError("Grid shape %s incompatible with minibatch size %i." %
# (grid_shape, int(input_tensor.shape[0])))
# if len(input_tensor.shape) == 2:
# num_features = image_shape[0] * image_shape[1] * num_channels
# if int(input_tensor.shape[1]) != num_features:
# raise ValueError("Image shape and number of channels incompatible with "
# "input tensor.")
# elif len(input_tensor.shape) == 4:
# if (int(input_tensor.shape[1]) != image_shape[0] or \
# int(input_tensor.shape[2]) != image_shape[1] or \
# int(input_tensor.shape[3]) != num_channels):
# raise ValueError("Image shape and number of channels incompatible with input tensor. %s vs %s" % (input_tensor.shape, (image_shape[0], image_shape[1],num_channels)))
# else:
# raise ValueError("Unrecognized input tensor format.")
# height, width = grid_shape[0] * image_shape[0], grid_shape[1] * image_shape[1]
# input_tensor = tf.reshape(input_tensor, tuple(grid_shape) + tuple(image_shape) + (num_channels,))
# input_tensor = tf.transpose(a = input_tensor, perm = [0, 1, 3, 2, 4])
# input_tensor = tf.reshape(input_tensor, [grid_shape[0], width, image_shape[0], num_channels])
# input_tensor = tf.transpose(a = input_tensor, perm = [0, 2, 1, 3])
# input_tensor = tf.reshape(input_tensor, [1, height, width, num_channels])
# return input_tensor[0]
# def model_saver(self):
# self.generate_and_save_batch(999)
# self.generator.save(self.checkpoint_dir + '/model_generator.h5', overwrite = True)
# self.discriminator.save(self.checkpoint_dir + '/model_discriminator.h5', overwrite = True)
# def setup_metrics(self):
# self.KLD_flag = 0
# self.FID_flag = 0
# self.PR_flag = 0
# self.lambda_flag = 0
# self.recon_flag = 0
# self.GradGrid_flag = 0
# self.class_prob_flag = 0
# self.metric_counter_vec = []
# if self.loss == 'FS' and self.mode != 'metrics':
# self.lambda_flag = 1
# self.lambda_vec = []
# if 'KLD' in self.metrics:
# self.KLD_flag = 1
# self.KLD_vec = []
# if self.data in ['g1', 'g2', 'gmm2', 'gmm8', 'gN', 'u1']:
# self.KLD_steps = 10
# if self.data == 'gN':
# self.KLD_steps = 50
# if self.data in ['gmm2', 'gmm8', 'u1']:#, 'gN']:
# self.KLD_func = self.KLD_sample_estimate
# else:
# self.KLD_func = self.KLD_Gaussian
# else:
# self.KLD_flag = 1
# self.KLD_steps = 100
# if self.loss == 'FS' and self.gan != 'WAE':
# if self.distribution == 'gaussian' or self.data in ['g1','g2']:
# self.KLD_func = self.KLD_Gaussian
# else:
# self.KLD_func = self.KLD_sample_estimate
# if self.gan == 'WAE':
# if 'gaussian' in self.noise_kind:
# self.KLD_func = self.KLD_Gaussian
# else:
# self.KLD_func = self.KLD_sample_estimate
# print('KLD is not an accurate metric on this datatype')
# if 'FID' in self.metrics:
# self.FID_flag = 1
# self.FID_load_flag = 0
# self.FID_vec = []
# self.FID_vec_new = []
# if self.data in ['mnist', 'svhn']:
# self.FID_steps = 500
# if self.mode == 'metrics':
# self.FID_num_samples = 1000
# else:
# self.FID_num_samples = 15000#5000 #EL used 15000 , Rumi used 5000
# elif self.data in ['cifar10']: