-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
1593 lines (1253 loc) · 50.2 KB
/
models.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 tensorflow.keras.optimizers import Adam
from tensorflow.keras.models import Model
from tensorflow.keras.models import model_from_json
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Reshape, Flatten
from tensorflow.keras.layers import Conv2D, Conv3D, Conv2DTranspose, Conv3DTranspose
from tensorflow.keras.layers import UpSampling2D, UpSampling3D
from tensorflow.keras.layers import MaxPooling2D, MaxPooling3D
from tensorflow.keras.layers import Cropping2D, Cropping3D
from tensorflow.keras.layers import LeakyReLU
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.layers import Dropout
from tensorflow.keras.initializers import RandomNormal
from functools import partial
import matplotlib.pylab as plt
import numpy as np
from tensorflow.keras.utils import plot_model
import seaborn as sns
from layers import *
from utils import *
from data_generator import *
plt.rc('font', **{'size':14, 'family':'serif'})
class PIX2PIX():
def __init__(self,
image_shape=(128, 128, 128, 3),
n_classes = 1,
batchsize = 1,
batchsize_eval =5,
lr = 0.0002,
gf = 64,
n_res = -1,
filters_d = [32, 64, 128, 256, 256],
norm = 'instance',
out_activation="tanh",
leakiness=0.02,
loss = 'mse',
dis_weight =.5,
adv_weight = 1.,
recon_weight = 100.,
pool_size = 50,
init_weights=0.02,
noise=False,
noise_decay=0.01,
decay = 0,
dropoutrate=0,
out_dir="."
):
self.image_shape = np.array(image_shape)
self.input_shape = np.array(image_shape)
self.input_shape[-1] = n_classes
self.BATCH_SIZE = batchsize
self.BATCH_SIZE_EVAL = batchsize_eval
self.lr = lr
self.dropout = dropoutrate
self.steps = 0
self.gf = gf
self.filters_d = filters_d
self.out_activation="tanh"
self.leakiness=0.02,
self.out_dir = out_dir
#Normalization Layer
if 'instance' in norm or 'Instance' in norm:
self.norm_layer = InstanceNormalization
else:
self.norm_layer = BatchNormalization
#adversarial loss type
if 'jens' in loss:
self.loss = jens_loss
elif 'wasserstein' in loss or 'Wasserstein' in loss:
self.loss = wasserstein
else:
self.loss = 'mse'
#loss weights
self.dis_weight = dis_weight
self.adv_weight = adv_weight
self.recon_weight = recon_weight
#discriminator fake pool size
self.pool_size = pool_size
#initializers' standard deviation
self.init_weights = init_weights
#initialize the Gaussian noise
self.noise = noise
self.noise_decay = noise_decay
#use residual blocks (n_res>0) or U-Net n_res<0
self.n_res = n_res
opt = Adam(lr=self.lr, beta_1=0.5, decay = decay)
# generator
self.g_model = self.define_generator()
# discriminator: [real/fake]
self.d_model = self.define_discriminator(opt)
self.d_model.compile(loss='mse',
optimizer=opt,
metrics=['accuracy'])
self.composite_model = self.define_composite_model(self.g_model, self.d_model, opt)
self.d_loss = []
self.g_loss = []
self.d_loss_eval = [[0, 0]]
self.g_loss_eval = [[0, 0, 0]]
self.epochs = [0]
# define the standalone generator model
def define_generator(self):
init = RandomNormal(stddev=self.init_weights)
# Image input
in_image = Input(shape=tuple(self.input_shape))
#use U-Net
if self.n_res < 0:
d = []
# Downsampling
d1 = conv_d(in_image, self.gf, norm=False, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d1)
d2 = conv_d(d1, self.gf * 2, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d2)
d3 = conv_d(d2, self.gf * 4, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d3)
d4 = conv_d(d3, self.gf * 8, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d4)
if self.image_shape[-2] > 64:
d5 = conv_d(d4, self.gf * 8, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d5)
if self.image_shape[-2] > 96:
d6 = conv_d(d5, self.gf * 8, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d6)
if self.image_shape[-2] > 128:
d7 = conv_d(d6, self.gf * 8, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
d.append(d7)
# Upsampling
if self.image_shape[-2] > 128:
u = deconv_d(d[-1], d[-2], self.gf * 8, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
else:
u = d[-1]
d.append(u)
if self.image_shape[-2] > 96:
u = deconv_d(u, d[-3], self.gf * 8, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
else:
u = d[-2]
d.append(u)
if self.image_shape[-2] > 64:
u = deconv_d(u, d[-4], self.gf * 8, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
else:
u = d[-3]
d.append(u)
u = deconv_d(u, d3, self.gf * 4, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
u = deconv_d(u, d2, self.gf * 2, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
u = deconv_d(u, d1, self.gf, dropout_rate=self.dropout, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness)
if len(self.image_shape[:-1]) == 3:
u = UpSampling3D(size=2)(u)
out_img = Conv3D(self.image_shape[-1], kernel_size=4, strides=1, padding='same', activation=self.out_activation)(u)
elif len(self.image_shape[:-1]) == 2:
u = UpSampling2D(size=2)(u)
out_img = Conv2D(self.image_shape[-1], kernel_size=4, strides=1, padding='same', activation=self.out_activation)(u)
else:
raise ValueError("Data must be 2D or 3D")
#use ResNet blocks
else:
#check dimensionality of image data
if len(self.image_shape[:-1]) == 3:
conv_layer = Conv3D
upsampling_layer = UpSampling3D
elif len(self.image_shape[:-1]) == 2:
conv_layer = Conv2D
upsampling_layer = UpSampling2D
else:
raise ValueError("Data must be 2D or 3D")
filters_g = [2**i * self.gf for i in range(3)]
g = conv_layer(filters_g[0], kernel_size=7, padding='same', kernel_initializer=init)(in_image)
g = self.norm_layer()(g)
g = LeakyReLU(0.2)(g)
for fil in filters_g[1:]:
g = conv_layer(fil, kernel_size=3, strides=2, padding='same', kernel_initializer=init)(g)
g = self.norm_layer()(g)
g = LeakyReLU(0.2)(g)
res_blocks = [g]
for i in range(self.n_res):
in_res = res_blocks[-1]
res_blocks.append(resnet_block(filters_g[-1], in_res, dim=len(self.image_shape[:-1]), init=init, norm_layer=self.norm_layer, leakiness=self.leakiness))
g = res_blocks[-1]
for fil in filters_g[::-1][1:]:
# g = conv_transpose_layer(fil, kernel_size=4, strides=2, padding='same', kernel_initializer=init)(g)
g = conv_layer(fil, kernel_size=3, strides=1, padding='same', kernel_initializer=init)(g)
g = upsampling_layer()(g)
g = self.norm_layer()(g)
g = LeakyReLU(self.leakiness)(g)
n_filters = self.image_shape[-1]
g = conv_layer(n_filters, kernel_size=7, padding='same', kernel_initializer=init)(g)
g = Dropout(self.dropout)(g)
g = self.norm_layer()(g)
out_img = Activation(self.out_activation)(g)
model = Model(in_image, out_img, name="PIX2PIX_generator")
plot_model(model, to_file=self. out_dir + "/generator.png", show_shapes=True, show_layer_names=True)
# model.summary()
return model
# define the discriminator model
def define_discriminator(self, opt):
# weight initialization
init = RandomNormal(stddev=self.init_weights)
#keep the patch size < image size:
max_index = int(np.argwhere(self.filters_d == np.array([self.image_shape[1]]))[0])
max_index += 1
self.filters_d = self.filters_d[:max_index]
if self.image_shape[1] < 256:
d_filters = self.filters_d
else:
d_filters = self.filters_d
#check dimensionality of image data
if len(self.image_shape[:-1]) == 3:
conv_layer = Conv3D
conv_transpose_layer = Conv3DTranspose
elif len(self.image_shape[:-1]) == 2:
conv_layer = Conv2D
else:
raise ValueError("Data must be 2D or 3D")
# source image input
in_map = Input(shape=tuple(self.input_shape))
in_image = Input(shape=tuple(self.image_shape))
d = Concatenate(axis=-1)([in_image,in_map])
if self.noise:
d = GaussianNoiseAnneal(0.2, self.noise_decay)(d)
for fil in d_filters:
d = conv_layer(fil, kernel_size=4, strides=2, padding='same', kernel_initializer=init)(d)
d = self.norm_layer()(d)
d = LeakyReLU(alpha=0.2)(d)
d = conv_layer(self.filters_d[-1], kernel_size=4, padding='same', kernel_initializer=init)(d)
d = self.norm_layer()(d)
d = LeakyReLU(alpha=0.2)(d)
# patch output
patch_out = conv_layer(1, kernel_size=4, padding='same', kernel_initializer=init)(d)
# define model
model = Model([in_map, in_image], patch_out, name="discriminator")
# compile model with weighting of least squares loss
model.compile(loss=self.loss, optimizer=opt, loss_weights=[self.dis_weight])
# model.summary()
plot_model(model, to_file=self. out_dir + "/discriminator.png", show_shapes=True, show_layer_names=True)
return model
# define a composite model for updating generators by adversarial and cycle loss
def define_composite_model(self, g_model, d_model, opt):
# ensure the model we're updating is trainable
g_model.trainable = True
# mark discriminator as not trainable
d_model.trainable = False
# Input images and their conditioning images
img_A = Input(shape=tuple(self.input_shape))
img_B = Input(shape=tuple(self.image_shape))
# By conditioning on A generate a fake version of B
fake_B = g_model(img_A)
# Discriminators determines validity of translated images / condition pairs
valid = d_model([img_A, fake_B])
model = Model(inputs=[img_A, img_B], outputs=[valid, fake_B], name='composite_model')
model.compile(loss=[self.loss, 'mae'],
loss_weights=[self.adv_weight, self.recon_weight],
optimizer=opt)
# model.summary()
plot_model(model, to_file=self. out_dir + "/composite_model.png", show_shapes=True, show_layer_names=True)
return model
def train_on_batch(self, trainGenerator, testGenerator):
# determine the output square shape of the discriminator
patch_shape = self.d_model.output_shape[1:]
# unpack dataset
trainA, trainB = next(trainGenerator)
pool = list()
# ---------------------
# Train Discriminator
# ---------------------
imgs_A, valid = generate_real_samples(trainA, self.BATCH_SIZE, patch_shape)
imgs_B, _ = generate_real_samples(trainB, self.BATCH_SIZE, patch_shape)
#check which channels to use
if imgs_A.shape[-1] > self.input_shape[-1]:
imgs_A = imgs_A[...,:self.input_shape[-1]]
if imgs_B.shape[-1] > self.image_shape[-1]:
imgs_B = imgs_B[..., :self.image_shape[-1]]
#generate fake samples and patch labels
fake_B, fake = generate_fake_samples(self.g_model, imgs_A, patch_shape)
fake_B = update_image_pool(pool, fake_B, max_size=self.pool_size)
# Train the discriminators (original images = real / generated = Fake)
d_loss_real = self.d_model.train_on_batch([imgs_A, imgs_B], valid)
d_loss_fake = self.d_model.train_on_batch([imgs_A, fake_B], fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
self.d_loss.append(d_loss)
# -----------------
# Train Generator
# -----------------
# Train the generator
g_loss = self.composite_model.train_on_batch([imgs_A, imgs_B], [valid, imgs_B])
self.g_loss.append(g_loss)
self.steps +=1
# summarize performance every 50 batches
if self.steps % 50 == 0:
print("[Epoch %d] [Batch %d] [D loss: %f, acc: %3d%%] [G loss: %1.3f = %1.1f * %1.3f + %1.1f * %1.3f]" % (
len(self.epochs),
self.steps,
d_loss[0],
100 * d_loss[1],
g_loss[0],
self.adv_weight,
g_loss[1],
self.recon_weight,
g_loss[2]))
#evaluate and validate the performance after each epoch, the save
if self.steps % len(trainGenerator) == 0:
self.save_loss()
self.epochs.append(self.steps)
self.visualize(testGenerator)
self.evaluate(testGenerator)
self.save(len(self.epochs)-1)
np.save(self.out_dir + '/res/epochs.npy', self.epochs)
def save_loss(self, name='training'):
"""Plot the loss functions and save plots."""
d_loss, g_loss = np.asarray(self.d_loss), np.asarray(self.g_loss)
f = plt.figure(figsize=(16, 8))
ax = f.add_subplot(1, 2, 1)
ax.plot(np.arange(1,self.steps+1), d_loss.T[0], c='r', label='discriminator loss')
ax.plot(np.arange(1,self.steps+1), d_loss.T[1], c='b', label='discriminator accuracy')
if len(self.d_loss_eval) > 1 and name == 'evaluation':
ax.plot(np.asarray(self.epochs), np.asarray(self.d_loss_eval).T[0], 'r--')
ax.plot(np.asarray(self.epochs), np.asarray(self.d_loss_eval).T[1], 'b--')
ax.set_yscale('log')
ax.legend()
ax.set_title('Discriminator error')
ax = f.add_subplot(1, 2, 2)
ax.plot(np.arange(1,self.steps+1), g_loss.T[0], c='r', label=r'total generator loss')
ax.plot(np.arange(1,self.steps+1), g_loss.T[1], c='b', label=r'adversarial loss')
ax.plot(np.arange(1,self.steps+1), g_loss.T[2], c='g', label=r'reconstruction loss')
if len(self.g_loss_eval) > 1 and name == 'evaluation':
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[0], 'r--')
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[1], 'b--')
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[2], 'g--')
ax.set_yscale('log')
ax.legend()
ax.set_title('Generator loss')
plt.savefig(self.out_dir + '/res/' + name + '.png')
plt.close()
np.save(self.out_dir + '/res/d_loss.npy', d_loss)
np.save(self.out_dir + '/res/g_loss.npy', g_loss)
def evaluate(self, testGenerator):
"""Plot the loss and evaluation errors."""
# determine the output square shape of the discriminator
patch_shape = self.d_model.output_shape[1:]
# unpack dataset
i = 0
d_loss = 0
g_loss = 0
while i < len(testGenerator):
testA, testB = next(testGenerator)
i += 1
# select a batch of real samples
imgs_A, valid = generate_real_samples(testA, self.BATCH_SIZE, patch_shape)
imgs_B, _ = generate_real_samples(testB, self.BATCH_SIZE, patch_shape)
#check which channels to use
if imgs_A.shape[-1] > self.input_shape[-1]:
imgs_A = imgs_A[...,:self.input_shape[-1]]
if imgs_B.shape[-1] > self.image_shape[-1]:
imgs_B = imgs_B[..., :self.image_shape[-1]]
#generate fake samples and patch labels
fake_B, fake = generate_fake_samples(self.g_model, imgs_A, patch_shape)
#evaluate discriminator
d_loss_real = self.d_model.evaluate([imgs_A, imgs_B], valid, verbose=0)
d_loss_fake = self.d_model.evaluate([imgs_A, fake_B], fake, verbose=0)
d_loss += 0.5 * np.add(d_loss_real, d_loss_fake)
# evaluate generator
g_loss += np.asarray(self.composite_model.evaluate([imgs_A, imgs_B], [valid, imgs_B], verbose=0))
self.d_loss_eval.append(d_loss / len(testGenerator))
self.g_loss_eval.append(g_loss / len(testGenerator))
np.save(self.out_dir + '/res/d_loss_eval.npy', self.d_loss_eval)
np.save(self.out_dir + '/res/g_loss_eval.npy', self.g_loss_eval)
self.save_loss(name='evaluation')
def visualize(self, testGen):
"""Plot a volume, cycled to domain B and then back to domain A"""
imgs_A, imgs_B = next(testGen)
idx = np.random.randint(len(imgs_A))
image_A = imgs_A[idx]
image_B = imgs_B[idx]
n_classes = self.input_shape[-1]
cols = sns.color_palette("pastel", n_classes - 2)
# background is transparent
cols.insert(0, 'none')
# Add stroke class
cols.append((1,0,0))
fake_B = self.g_model.predict(imgs_A)
if len(self.image_shape) > 3:
fake_B = fake_B[idx]
image_A = np.transpose(image_A, (2,1,0,3))
image_B = np.transpose(image_B, (2,1,0,3))
fake_B = np.transpose(fake_B, (2,1,0,3))
non_zero_slices = np.argwhere(np.any(image_B[..., 0] > 0, axis=(1, 2))).T[0]
else:
image_A = np.transpose(imgs_A, (0,2,1,3))
image_B = np.transpose(imgs_B, (0,2,1,3))
fake_B = np.transpose(fake_B, (0,2,1,3))
non_zero_slices = np.argwhere(np.any(image_B[...,0] > 0, axis=(1, 2))).T[0]
image_A = np.flip(image_A, axis=(1,2))
image_B = np.flip(image_B, axis=(1,2))
fake_B = np.flip(fake_B, axis=(1,2))
num_ims = min(10, len(non_zero_slices))
fig, ax_arr = plt.subplots(num_ims, 3, figsize=(9, 3*num_ims))
ax_arr = ax_arr.reshape((num_ims, 3))
for i in range(0,num_ims):
(ax1, ax2, ax3) = ax_arr[i]
idx = (len(non_zero_slices)) // num_ims
ax1.contourf(np.argmax(image_A[non_zero_slices[i*idx],::-1,:],axis=-1),
levels = np.arange(n_classes + 1) - 0.5,
colors = cols)
ax1.set_xticks([], [])
ax1.set_yticks([], [])
ax1.set_aspect(1)
ax2.imshow(fake_B[non_zero_slices[i*idx], :, :, 0],
cmap='bone',
vmin=-1,
vmax=1)
if self.image_shape[-1] > 1:
ax2.contour(fake_B[non_zero_slices[i*idx], :, :, 1],
linewidths=0.5,
levels=[0.],
colors=['r'])
else:
ax2.contour(np.argmax(image_A[non_zero_slices[i*idx], :, :, :], axis=-1),
levels = np.arange(n_classes + 1) - 0.5,
colors=cols,
linewidths=0.5)
ax2.set_xticks([], [])
ax2.set_yticks([], [])
ax3.imshow(image_B[non_zero_slices[i*idx], :, :, 0],
cmap='bone',
vmin=-1,
vmax=1)
if self.image_shape[-1] > 1:
ax3.contour(image_B[non_zero_slices[i*idx], :, :, 1],
linewidths=0.5,
levels=[0.],
colors=['r'])
else:
ax3.contour(np.argmax(image_A[non_zero_slices[i*idx], :, :, :], axis=-1),
levels = np.arange(n_classes + 1) - 0.5,
colors=cols,
linewidths=0.5)
ax3.set_xticks([], [])
ax3.set_yticks([], [])
if i==0:
ax1.set_title('segmentation map')
ax2.set_title('generated image')
ax3.set_title('ground truth')
plt.savefig(self.out_dir + '/res/output_sample' + str(len(self.epochs) - 1) + '.png')
plt.close()
def saveModel(self, model, name): # Save a Model
"""Save a model."""
model.save(name + ".h5")
def save(self, num=-1):
"""Save the GAN's submodels individually.
Input:
int; identifier for a given model.
"""
if num < 0:
num = str(self.steps)
else:
num = str(num)
self.saveModel(self.g_model, self.out_dir + "/Models/gen_" + num)
self.saveModel(self.d_model, self.out_dir + "/Models/dis_" + num)
def load(self, location, num=-1):
"""Load the GAN's submodels.
Input:
int; identifier for the desired model.
"""
opt = Adam(lr=self.lr, beta_1=0.5)
self.g_model.load_weights(location + "/Models/gen_" + str(num) + '.h5')
self.d_model.load_weights(location + "/Models/dis_" + str(num) + '.h5')
self.composite_model = self.define_composite_model(self.g_model, self.d_model, opt)
self.epochs = list(np.load(location + '/res/epochs.npy')[:int(num) + 1])
self.steps = self.epochs[-1]
self.d_loss = list(np.load(location + '/res/d_loss.npy')[:self.steps])
self.d_loss_eval = list(np.load(location + '/res/d_loss_eval.npy')[:(int(num)+1)])
self.g_loss = list(np.load(location + '/res/g_loss.npy')[:self.steps])
self.g_loss_eval = list(np.load(location + '/res/g_loss_eval.npy')[:(int(num)+1)])
os.system("rm -r " + self.out_dir)
self.out_dir = location
class SPADE():
def __init__(self,
image_shape=(128, 128, 128, 3),
n_classes=1,
batchsize=1,
batchsize_eval=5,
lr=0.0002,
gf=64,
latent_dim=100,
filters_d=[32, 64, 128, 256, 256],
norm = 'instance',
out_activation="tanh",
leakiness=0.02,
loss = 'mse',
dis_weight =.5,
adv_weight = 1.,
recon_weight = 100.,
pool_size = 50,
init_weights=0.02,
noise=False,
noise_decay=0.01,
decay = 0,
dropoutrate=0,
out_dir=".",
):
self.image_shape = np.array(image_shape)
self.input_shape = np.array(image_shape)
self.input_shape[-1] = n_classes
self.BATCH_SIZE = batchsize
self.BATCH_SIZE_EVAL = batchsize_eval
self.lr = lr
self.dropout = dropoutrate
self.steps = 0
self.gf = gf
self.latent_dim = latent_dim
self.filters_d = filters_d
self.out_dir = out_dir
self.out_activation=out_activation
self.leakiness=leakiness
#Normalization Layer
if 'instance' in norm or 'Instance' in norm:
self.norm_layer = InstanceNormalization
else:
self.norm_layer = BatchNormalization
#adversarial loss type
if 'jens' in loss:
self.loss = jens_loss
elif 'wasserstein' in loss or 'Wasserstein' in loss:
self.loss = wasserstein
else:
self.loss = 'mse'
#loss weights
self.dis_weight = dis_weight
self.adv_weight = adv_weight
self.recon_weight = recon_weight
#discriminator fake pool size
self.pool_size = pool_size
#initializers' standard deviation
self.init_weights = init_weights
#initialize the Gaussian noise
self.noise = noise
self.noise_decay = noise_decay
opt = Adam(lr=self.lr, beta_1=0.5, decay = decay)
# generator
self.g_model = self.define_generator()
# discriminator: [real/fake]
self.d_model = self.define_discriminator(opt)
self.d_model.compile(loss='mse',
optimizer=opt,
metrics=['accuracy'])
self.composite_model = self.define_composite_model(self.g_model, self.d_model, opt)
self.d_loss = []
self.g_loss = []
self.d_loss_eval = [[0, 0]]
self.g_loss_eval = [[0, 0, 0]]
self.epochs = [0]
# define the standalone generator model
def define_generator(self):
init = RandomNormal(stddev=self.init_weights)
# Image input
latent_in = Input(shape=(self.latent_dim))
mask_in = Input(shape=tuple(self.input_shape))
g = Dense(1 * 4 * 4 * self.gf)(latent_in)
dim = len(self.image_shape[:-1])
if dim == 2:
g = Reshape((4, 4, self.gf))(g)
pooling_layer = MaxPooling2D
upsampling_layer = UpSampling2D
conv_layer = Conv2D
elif dim == 3:
g = Reshape((4, 4, 1, self.gf))(g)
pooling_layer = MaxPooling3D
upsampling_layer = UpSampling3D
conv_layer = Conv3D
res = mask_in.shape[1]
masks = {str(res):mask_in}
while res > 4:
key = str(res // 2)
masks[key] = pooling_layer()(masks[str(res)])
res = res // 2
print(masks.keys())
fil = self.gf
while g.shape[1] < self.image_shape[1]:
if fil == g.shape[-1]:
g = Add()([g, spade_res_block(fil, g, masks[str(g.shape[1])], dim=dim, init=init, leakiness=self.leakiness)])
else:
g = Add()([spade_res_block(fil, g, masks[str(g.shape[1])], dim=dim, init=init, rectify=True, leakiness=self.leakiness),
spade_res_block(fil, g, masks[str(g.shape[1])], dim=dim, init=init, leakiness=self.leakiness)])
g = upsampling_layer()(g)
fil = fil // 2
g = conv_layer(1, kernel_size=7, strides=1, padding='same', kernel_initializer=init)(g)
out_img = Activation(self.out_activation)(g)
model = Model([latent_in, mask_in], out_img, name="SPADE_generator")
# plot_model(model, to_file=self. out_dir + "/generator.png", show_shapes=True, show_layer_names=True)
model.summary()
return model
# define the discriminator model
def define_discriminator(self, opt):
# weight initialization
init = RandomNormal(stddev=self.init_weights)
#keep the patch size < image size:
max_index = int(np.argwhere(self.filters_d == np.array([self.image_shape[1]]))[0])
max_index += 1
self.filters_d = self.filters_d[:max_index]
if self.image_shape[1] < 256:
d_filters = self.filters_d
else:
d_filters = self.filters_d
#check dimensionality of image data
if len(self.image_shape[:-1]) == 3:
conv_layer = Conv3D
conv_transpose_layer = Conv3DTranspose
elif len(self.image_shape[:-1]) == 2:
conv_layer = Conv2D
else:
raise ValueError("Data must be 2D or 3D")
# source image input
in_map = Input(shape=tuple(self.input_shape))
in_image = Input(shape=tuple(self.image_shape))
d = Concatenate(axis=-1)([in_image,in_map])
if self.noise:
d = GaussianNoiseAnneal(0.2, self.noise_decay)(d)
for fil in d_filters:
d = conv_layer(fil, kernel_size=4, strides=2, padding='same', kernel_initializer=init)(d)
d = self.norm_layer()(d)
d = LeakyReLU(alpha=0.2)(d)
d = conv_layer(self.filters_d[-1], kernel_size=4, padding='same', kernel_initializer=init)(d)
d = self.norm_layer()(d)
d = LeakyReLU(alpha=0.2)(d)
# patch output
patch_out = conv_layer(1, kernel_size=4, padding='same', kernel_initializer=init)(d)
# define model
model = Model([in_map, in_image], patch_out, name="discriminator")
# compile model with weighting of least squares loss
model.compile(loss=self.loss, optimizer=opt, loss_weights=[self.dis_weight])
model.summary()
# plot_model(model, to_file=self. out_dir + "/discriminator.png", show_shapes=True, show_layer_names=True)
return model
# define a composite model for updating generators by adversarial and cycle loss
def define_composite_model(self, g_model, d_model, opt):
# ensure the model we're updating is trainable
g_model.trainable = True
# mark discriminator as not trainable
d_model.trainable = False
# Input images and their conditioning images
latent_in = Input(shape=self.latent_dim)
mask = Input(shape=tuple(self.input_shape))
img = Input(shape=tuple(self.image_shape))
# By conditioning on A generate a fake version of B
fake = g_model([latent_in, mask])
# Discriminators determines validity of translated images / condition pairs
valid = d_model([mask, fake])
model = Model(inputs=[latent_in, mask, img], outputs=[valid, fake], name='composite_model')
model.compile(loss=[self.loss, 'mae'],
loss_weights=[self.adv_weight, self.recon_weight],
optimizer=opt)
# model.summary()
# plot_model(model, to_file=self. out_dir + "/composite_model.png", show_shapes=True, show_layer_names=True)
return model
def train_on_batch(self, trainGenerator, testGenerator):
# determine the output square shape of the discriminator
patch_shape = self.d_model.output_shape[1:]
# unpack dataset
trainA, trainB = next(trainGenerator)
pool = list()
# ---------------------
# Train Discriminator
# ---------------------
imgs_A, valid = generate_real_samples(trainA, self.BATCH_SIZE, patch_shape)
imgs_B, _ = generate_real_samples(trainB, self.BATCH_SIZE, patch_shape)
#check which channels to use
if imgs_A.shape[-1] > self.input_shape[-1]:
imgs_A = imgs_A[...,:self.input_shape[-1]]
if imgs_B.shape[-1] > self.image_shape[-1]:
imgs_B = imgs_B[..., :self.image_shape[-1]]
#generate fake samples and patch labels
fake_B, fake = generate_fake_samples(self.g_model, imgs_A, patch_shape)
fake_B = update_image_pool(pool, fake_B, max_size=self.pool_size)
# Train the discriminators (original images = real / generated = Fake)
d_loss_real = self.d_model.train_on_batch([imgs_A, imgs_B], valid)
d_loss_fake = self.d_model.train_on_batch([imgs_A, fake_B], fake)
d_loss = 0.5 * np.add(d_loss_real, d_loss_fake)
self.d_loss.append(d_loss)
# -----------------
# Train Generator
# -----------------
# Train the generator
latent = np.random.normal(0, 1, (self.BATCH_SIZE, self.latent_dim))
g_loss = self.composite_model.train_on_batch([latent, imgs_A, imgs_B], [valid, imgs_B])
self.g_loss.append(g_loss)
self.steps +=1
# summarize performance every 50 batches
if self.steps % 1 == 0:
print("[Epoch %d] [Batch %d] [D loss: %f, acc: %3d%%] [G loss: %1.3f = %1.1f * %1.3f + %1.1f * %1.3f]" % (
len(self.epochs),
self.steps,
d_loss[0],
100 * d_loss[1],
g_loss[0],
self.adv_weight,
g_loss[1],
self.recon_weight,
g_loss[2]))
#evaluate and validate the performance after each epoch, the save
if self.steps % len(trainGenerator) == 0:
self.save_loss()
self.epochs.append(self.steps)
self.visualize(testGenerator)
self.evaluate(testGenerator)
self.save(len(self.epochs)-1)
np.save(self.out_dir + '/res/epochs.npy', self.epochs)
def save_loss(self, name='training'):
"""Plot the loss functions and save plots."""
d_loss, g_loss = np.asarray(self.d_loss), np.asarray(self.g_loss)
f = plt.figure(figsize=(16, 8))
ax = f.add_subplot(1, 2, 1)
ax.plot(np.arange(1,self.steps+1), d_loss.T[0], c='r', label='discriminator loss')
ax.plot(np.arange(1,self.steps+1), d_loss.T[1], c='b', label='discriminator accuracy')
if len(self.d_loss_eval) > 1 and name == 'evaluation':
ax.plot(np.asarray(self.epochs), np.asarray(self.d_loss_eval).T[0], 'r--')
ax.plot(np.asarray(self.epochs), np.asarray(self.d_loss_eval).T[1], 'b--')
ax.set_yscale('log')
ax.legend()
ax.set_title('Discriminator error')
ax = f.add_subplot(1, 2, 2)
ax.plot(np.arange(1,self.steps+1), g_loss.T[0], c='r', label=r'total generator loss')
ax.plot(np.arange(1,self.steps+1), g_loss.T[1], c='b', label=r'adversarial loss')
ax.plot(np.arange(1,self.steps+1), g_loss.T[2], c='g', label=r'reconstruction loss')
if len(self.g_loss_eval) > 1 and name == 'evaluation':
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[0], 'r--')
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[1], 'b--')
ax.plot(np.asarray(self.epochs), np.asarray(self.g_loss_eval).T[2], 'g--')
ax.set_yscale('log')
ax.legend()
ax.set_title('Generator loss')
plt.savefig(self.out_dir + '/res/' + name + '.png')
plt.close()
np.save(self.out_dir + '/res/d_loss.npy', d_loss)
np.save(self.out_dir + '/res/g_loss.npy', g_loss)
def evaluate(self, testGenerator):
"""Plot the loss and evaluation errors."""
# determine the output square shape of the discriminator
patch_shape = self.d_model.output_shape[1:]
# unpack dataset
i = 0
d_loss = 0
g_loss = 0
while i < len(testGenerator):
testA, testB = next(testGenerator)
i += 1
# select a batch of real samples
imgs_A, valid = generate_real_samples(testA, self.BATCH_SIZE, patch_shape)
imgs_B, _ = generate_real_samples(testB, self.BATCH_SIZE, patch_shape)
#check which channels to use
if imgs_A.shape[-1] > self.input_shape[-1]:
imgs_A = imgs_A[...,:self.input_shape[-1]]
if imgs_B.shape[-1] > self.image_shape[-1]:
imgs_B = imgs_B[..., :self.image_shape[-1]]
#generate fake samples and patch labels
fake_B, fake = generate_fake_samples(self.g_model, imgs_A, patch_shape)
#evaluate discriminator
d_loss_real = self.d_model.evaluate([imgs_A, imgs_B], valid, verbose=0)
d_loss_fake = self.d_model.evaluate([imgs_A, fake_B], fake, verbose=0)
d_loss += 0.5 * np.add(d_loss_real, d_loss_fake)
# evaluate generator
latent = np.random.normal(0, 1, (self.BATCH_SIZE, self.latent_dim))
g_loss += np.asarray(self.composite_model.evaluate([latent, imgs_A, imgs_B], [valid, imgs_B], verbose=0))
self.d_loss_eval.append(d_loss / len(testGenerator))
self.g_loss_eval.append(g_loss / len(testGenerator))
np.save(self.out_dir + '/res/d_loss_eval.npy', self.d_loss_eval)
np.save(self.out_dir + '/res/g_loss_eval.npy', self.g_loss_eval)
self.save_loss(name='evaluation')
def visualize(self, testGen):
"""Plot a volume, cycled to domain B and then back to domain A"""
imgs_A, imgs_B = next(testGen)
idx = np.random.randint(len(imgs_A))
image_A = imgs_A[idx]
image_B = imgs_B[idx]
n_classes = self.input_shape[-1]
cols = sns.color_palette("pastel", n_classes - 2)
# background is transparent
cols.insert(0, 'none')
# Add stroke class
cols.append('r')
latent = np.random.normal(0, 1, (self.BATCH_SIZE_EVAL, self.latent_dim))
fake_B = self.g_model.predict([latent, imgs_A])
if len(self.image_shape) > 3:
fake_B = fake_B[idx]
image_A = np.transpose(image_A, (2,1,0,3))
image_B = np.transpose(image_B, (2,1,0,3))
fake_B = np.transpose(fake_B, (2,1,0,3))
non_zero_slices = np.argwhere(np.any(image_B[..., 0] > 0, axis=(1, 2))).T[0]
else:
image_A = np.transpose(imgs_A, (0,2,1,3))
image_B = np.transpose(imgs_B, (0,2,1,3))
fake_B = np.transpose(fake_B, (0,2,1,3))
non_zero_slices = np.argwhere(np.any(image_B[...,0] > 0, axis=(1, 2))).T[0]
image_A = np.flip(image_A, axis=(1,2))
image_B = np.flip(image_B, axis=(1,2))
fake_B = np.flip(fake_B, axis=(1,2))
num_ims = min(10, len(non_zero_slices))