-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
1654 lines (1317 loc) · 65.1 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
import keras.backend as K
import tensorflow as tf
from tensorflow import keras
from keras import layers
import numpy as np
import os
from utils import unnormalize_params, unnormalizeIMG
def calculate_padding(input_shape, target_shape):
# Calculate the padding needed for the first two dimensions
padding_first_dim = (target_shape[0] - input_shape[0]) // 2
mod_first_dim = (target_shape[0] - input_shape[0]) % 2
padding_second_dim = (target_shape[1] - input_shape[1]) // 2
mod_second_dim = (target_shape[1] - input_shape[1]) % 2
# If the padding doesn't divide evenly, add the extra padding to one side
pad_first_dim_left = padding_first_dim + mod_first_dim
pad_second_dim_left = padding_second_dim + mod_second_dim
# Create the padding configuration for np.pad
padding_config = (
# Padding for the first dimension
(pad_first_dim_left, padding_first_dim),
# Padding for the second dimension
(pad_second_dim_left, padding_second_dim),
# (0, 0) # Padding for the third dimension
)
return padding_config
class BaseModel(keras.Model):
def __init__(self, *args, **kwargs):
super().__init__()
self.model = None
def predict(self, x):
return self.model(x)
def load(self, weights_file):
self.model = keras.models.load_model(weights_file)
def save(self, weights_file):
self.model.save(weights_file)
# model definition
class AutoEncoderSkipAhead(BaseModel):
# Pooling can be None, or 'Average' or 'Max'
def __init__(self, output_name='autoencoder',
input_shape=(128, 128, 1), dense_layers=[7],
decoder_dense_layers=[],
cropping=[[0, 0], [0, 0]],
filters=[8, 16, 32], kernel_size=3, conv_padding='same',
strides=[2, 2], activation='relu',
final_activation='linear', final_kernel_size=3,
dropout=0.0, learning_rate=0.001, loss='mse',
metrics=[], use_bias=True, conv_batchnorm=False,
dense_batchnorm=False, **kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
# the kernel_size can be a single int or a list of ints
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * len(filters)
assert len(kernel_size) == len(filters)
# the strides can be a list of two ints, or a list of two-int lists
if isinstance(strides[0], int):
strides = [strides for _ in filters]
assert len(strides) == len(filters)
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
# crop the edges
cropped = keras.layers.Cropping2D(cropping=cropping, name='Crop')(inputs)
x = cropped
skip_layers = []
# For evey Convolutional layer
for i, f in enumerate(filters):
# Add the Convolution
x = keras.layers.Conv2D(
filters=f, kernel_size=kernel_size[i], strides=strides[i],
use_bias=use_bias, padding=conv_padding,
name=f'CNN_{i+1}')(x)
# Apply batchnormalization
if conv_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Apply the activation function
x = keras.activations.get(activation)(x)
# append to skip layers
skip_layers.append(x)
# we have reached the latent space
last_shape = x.shape[1:]
x = keras.layers.Flatten(name='Flatten')(x)
flat_shape = x.shape[1:]
# Now we add the dense layers
for i, units in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'encoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
# a dummy layer just to name it latent space
x = keras.layers.Lambda(lambda x: x, name='LatentSpace')(x)
self.encoder = keras.Model(inputs=inputs, outputs=x, name='encoder')
# Now we add the decoder dense layers
for i, units in enumerate(decoder_dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'decoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
# Now reshape back to last_shape
x = keras.layers.Dense(units=np.prod(flat_shape), activation=activation,
name='decoder_dense_final')(x)
x = keras.layers.Reshape(target_shape=last_shape, name='Reshape')(x)
# Now with transpose convolutions we go back to the original size
for i, f in enumerate(filters[::-1]):
x = keras.layers.Concatenate(name=f'Concatenate_{i+1}')([x, skip_layers[-i-1]])
x = keras.layers.Conv2DTranspose(
filters=f, kernel_size=kernel_size[-i-1],
strides=strides[-i-1],
use_bias=use_bias, padding=conv_padding,
name=f'CNN_Transpose_{i+1}')(x)
# final convolution to get the right number of channels
x = keras.layers.Conv2DTranspose(filters=1, kernel_size=final_kernel_size,
strides=1, use_bias=use_bias, padding='same',
name=f'CNN_Transpose_Final')(x)
x = keras.layers.Activation(activation=final_activation,
name='final_activation')(x)
before_padding = x
# Add zero padding
padding = calculate_padding(
input_shape=before_padding.shape[1:], target_shape=input_shape)
outputs = keras.layers.ZeroPadding2D(
padding=padding, name='Padding')(x)
model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# assert model.layers[-1].output_shape[1:] == input_shape
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
self.model = model
# model definition
# Sampling function
def sampling(args):
z_mean, z_log_var = args
batch = K.shape(z_mean)[0]
dim = K.int_shape(z_mean)[1]
epsilon = K.random_normal(shape=(batch, dim))
return z_mean + K.exp(0.5 * z_log_var) * epsilon
class VariationalAutoEncoder(BaseModel):
# Pooling can be None, or 'Average' or 'Max'
def __init__(self, output_name='vae',
input_shape=(128, 128, 1), dense_layers=[7],
decoder_dense_layers=[], latent_dim=2,
cropping=[[0, 0], [0, 0]],
filters=[8, 16, 32], kernel_size=3, conv_padding='same',
strides=[2, 2], activation='relu',
final_activation='sigmoid', final_kernel_size=3,
dropout=0.0, learning_rate=0.001, loss='mse',
metrics=[], use_bias=True, conv_batchnorm=False,
dense_batchnorm=False, **kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
# the kernel_size can be a single int or a list of ints
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * len(filters)
assert len(kernel_size) == len(filters)
# the strides can be a list of two ints, or a list of two-int lists
if isinstance(strides[0], int):
strides = [strides for _ in filters]
assert len(strides) == len(filters)
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
# crop the edges
cropped = keras.layers.Cropping2D(
cropping=cropping, name='Crop')(inputs)
x = cropped
# For evey Convolutional layer
for i, f in enumerate(filters):
# Add the Convolution
x = keras.layers.Conv2D(
filters=f, kernel_size=kernel_size[i], strides=strides[i],
use_bias=use_bias, padding=conv_padding,
name=f'CNN_{i+1}')(x)
# Apply batchnormalization
if conv_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Apply the activation function
x = keras.activations.get(activation)(x)
# we have reached the latent space
last_shape = x.shape[1:]
x = keras.layers.Flatten(name='Flatten')(x)
flat_shape = x.shape[1:]
# Now we add the dense layers
for i, units in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'encoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
z_mean = keras.layers.Dense(units=latent_dim)(x)
z_log_var = keras.layers.Dense(units=latent_dim)(x)
z = keras.layers.Lambda(sampling, name='LatentSpace')([z_mean, z_log_var])
# a dummy layer just to name it latent space
# x = keras.layers.Lambda(lambda x: x, name='LatentSpace')(x)
# self.encoder = keras.Model(inputs=inputs, outputs=z, name='encoder')
# Decoder network
decoder_inputs = keras.layers.Input(shape=(latent_dim,), name='decoder_input')
# Now we add the decoder dense layers
for i, units in enumerate(decoder_dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'decoder_dense_{i+1}')(decoder_inputs)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
# Now reshape back to last_shape
x = keras.layers.Dense(units=np.prod(flat_shape), activation=activation,
name='decoder_dense_final')(x)
x = keras.layers.Reshape(target_shape=last_shape, name='Reshape')(x)
# Now with transpose convolutions we go back to the original size
for i, f in enumerate(filters[::-1]):
x = keras.layers.Conv2DTranspose(
filters=f, kernel_size=kernel_size[-i-1],
strides=strides[-i-1],
use_bias=use_bias, padding=conv_padding,
name=f'CNN_Transpose_{i+1}')(x)
# final convolution to get the right number of channels
x = keras.layers.Conv2DTranspose(filters=1, kernel_size=final_kernel_size,
strides=1, use_bias=use_bias, padding='same',
name=f'CNN_Transpose_Final')(x)
x = keras.layers.Activation(activation=final_activation,
name='final_activation')(x)
before_padding = x
# Add zero padding
padding = calculate_padding(
input_shape=before_padding.shape[1:], target_shape=input_shape)
outputs = keras.layers.ZeroPadding2D(padding=padding, name='Padding')(x)
self.encoder = keras.Model(inputs=inputs, outputs=[
z_mean, z_log_var, z], name='encoder')
self.decoder = keras.Model(inputs=decoder_inputs, outputs=outputs, name='decoder')
outputs = self.decoder(self.encoder(inputs)[2])
model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# Loss function
# reconstruction_loss = tf.reduce_mean(tf.reduce_sum(tf.keras.losses.binary_crossentropy(inputs, outputs), axis=(1, 2)))
reconstruction_loss = tf.reduce_mean(tf.abs(inputs-outputs))
kl_loss = -0.5 * tf.reduce_mean(tf.reduce_sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1))
vae_loss = reconstruction_loss + kl_loss
# model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# assert model.layers[-1].output_shape[1:] == input_shape
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.add_loss(vae_loss)
model.compile(optimizer=optimizer, metrics=metrics)
self.model = model
# model definition
class AutoEncoderEfficientNet(BaseModel):
def __init__(self, output_name='autoencoder',
input_shape=(128, 128, 1),
cropping=[[0, 0], [0, 0]],
dense_layers=[256], dense_batchnorm=False,
reshape_shape=(13, 13, 1),
filters=[8, 16, 32], kernel_size=3, conv_padding='same',
strides=[2, 2], activation='relu',
final_activation='linear', final_kernel_size=3,
dropout=0.0, learning_rate=0.001, loss='mae',
metrics=[], use_bias=True, **kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
# the kernel_size can be a single int or a list of ints
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * len(filters)
assert len(kernel_size) == len(filters)
# the strides can be a list of two ints, or a list of two-int lists
if isinstance(strides[0], int):
strides = [strides for _ in filters]
assert len(strides) == len(filters)
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
# this is the autoencoder case
# crop the edges
cropped = keras.layers.Cropping2D(
cropping=cropping, name='Crop')(inputs)
x = cropped
efficientnet = tf.keras.Sequential([
keras.applications.EfficientNetV2B0(include_top=False,
pooling='avg',
weights=None,
classifier_activation='relu',
include_preprocessing=False,
input_shape=x.shape[1:])])
x = efficientnet(x)
x = keras.layers.Flatten(name='Flatten')(x)
flat_shape = x.shape[1:]
# Now we add the dense layers
for i, units in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'encoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
# Now reshape back to last_shape
x = keras.layers.Dense(units=np.prod(reshape_shape), activation=activation,
name='encoder_dense_final')(x)
# a dummy layer just to name it latent space
x = keras.layers.Lambda(lambda x: x, name='LatentSpace')(x)
self.encoder = keras.Model(inputs=inputs, outputs=x, name='encoder')
x = keras.layers.Reshape(target_shape=reshape_shape, name='Reshape')(x)
# Now with transpose convolutions we go back to the original size
for i, f in enumerate(filters[::-1]):
x = keras.layers.Conv2DTranspose(
filters=f, kernel_size=kernel_size[-i-1],
strides=strides[-i-1],
use_bias=use_bias, padding=conv_padding,
activation=activation,
name=f'CNN_Transpose_{i+1}')(x)
# final convolution to get the right number of channels
x = keras.layers.Conv2DTranspose(filters=1, kernel_size=final_kernel_size,
strides=1, use_bias=use_bias, padding='same', activation=final_activation,
name=f'CNN_Transpose_Final')(x)
before_padding = x
# Add zero padding
padding = calculate_padding(
input_shape=before_padding.shape[1:], target_shape=input_shape)
outputs = keras.layers.ZeroPadding2D(
padding=padding, name='Padding')(x)
model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# assert model.layers[-1].output_shape[1:] == input_shape
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
self.model = model
# model definition
class AutoEncoderTranspose(BaseModel):
# Pooling can be None, or 'Average' or 'Max'
def __init__(self, output_name='autoencoder',
input_shape=(128, 128, 1), dense_layers=[7],
decoder_dense_layers=[],
cropping=[[0, 0], [0, 0]],
filters=[8, 16, 32], kernel_size=3, conv_padding='same',
strides=[2, 2],
enc_activation='relu',
dec_activation='relu',
conv_activation='relu',
alpha=0.1,
final_activation='linear', final_kernel_size=3,
pooling=None, pooling_size=[2, 2],
pooling_strides=[1, 1], pooling_padding='valid',
dropout=0.0, learning_rate=0.001, loss='mse',
metrics=[], use_bias=True, conv_batchnorm=False,
dense_batchnorm=False, **kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
# the kernel_size can be a single int or a list of ints
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * len(filters)
assert len(kernel_size) == len(filters)
# the strides can be a list of two ints, or a list of two-int lists
if isinstance(strides[0], int):
strides = [strides for _ in filters]
assert len(strides) == len(filters)
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
# this is the autoencoder case
# crop the edges
cropped = keras.layers.Cropping2D(
cropping=cropping, name='Crop')(inputs)
x = cropped
# For evey Convolutional layer
for i, f in enumerate(filters):
# Add the Convolution
x = keras.layers.Conv2D(
filters=f, kernel_size=kernel_size[i], strides=strides[i],
use_bias=use_bias, padding=conv_padding, activation=conv_activation,
name=f'CNN_{i+1}')(x)
# Apply batchnormalization
if conv_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Optional pooling after the convolution
if pooling == 'Max':
x = keras.layers.MaxPooling2D(
pool_size=pooling_size, strides=pooling_strides,
padding=pooling_padding, name=f'MaxPooling_{i+1}')(x)
elif pooling == 'Average':
x = keras.layers.AveragePooling2D(
pool_size=pooling_size, strides=pooling_strides,
padding=pooling_padding, name=f'AveragePooling_{i+1}')(x)
# we have reached the latent space
last_shape = x.shape[1:]
x = keras.layers.Flatten(name='Flatten')(x)
flat_shape = x.shape[1:]
# Now we add the dense layers
for i, units in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=enc_activation,
name=f'encoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'enc_dropout_{i+1}')(x)
# a dummy layer just to name it latent space
x = keras.layers.Lambda(lambda x: x, name='LatentSpace')(x)
self.encoder = keras.Model(inputs=inputs, outputs=x, name='encoder')
# Now we add the decoder dense layers
for i, units in enumerate(decoder_dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=dec_activation,
name=f'decoder_dense_{i+1}')(x)
# Apply batchnormalization
if dense_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dec_dropout_{i+1}')(x)
# Now reshape back to last_shape
x = keras.layers.Dense(units=np.prod(flat_shape), activation=conv_activation,
name='decoder_dense_final')(x)
x = keras.layers.Reshape(target_shape=last_shape, name='Reshape')(x)
# Now with transpose convolutions we go back to the original size
for i, f in enumerate(filters[::-1]):
x = keras.layers.Conv2DTranspose(
filters=f, kernel_size=kernel_size[-i-1],
strides=strides[-i-1],
use_bias=use_bias, padding=conv_padding,
name=f'CNN_Transpose_{i+1}')(x)
# final convolution to get the right number of channels
x = keras.layers.Conv2DTranspose(filters=1, kernel_size=final_kernel_size,
strides=1, use_bias=use_bias, padding='same',
name=f'CNN_Transpose_Final')(x)
x = keras.layers.Activation(activation=final_activation,
name='final_activation')(x)
before_padding = x
# Add zero padding
padding = calculate_padding(
input_shape=before_padding.shape[1:], target_shape=input_shape)
outputs = keras.layers.ZeroPadding2D(
padding=padding, name='Padding')(x)
model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# assert model.layers[-1].output_shape[1:] == input_shape
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
self.model = model
# model definition
class FeatureExtractor(BaseModel):
def __init__(self, input_shape, output_features=1,
output_name='feature_extractor',
dense_layers=[256, 64], activation='relu',
final_activation='linear',
dropout=0.0, learning_rate=1e-3, loss='mse',
metrics=[], use_bias=True, batchnorm=False,
**kwargs):
super().__init__()
self.output_name = output_name
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
x = inputs
# Now we add the dense layers
for i, units in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(units=units, activation=activation,
name=f'dense_{i+1}', use_bias=use_bias)(x)
# Apply batchnormalization
if batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(dropout, name=f'dropout_{i+1}')(x)
# Add the final layer
outputs = keras.layers.Dense(units=output_features,
activation=final_activation,
name='dense_final', use_bias=use_bias)(x)
model = keras.Model(inputs=inputs, outputs=outputs, name=output_name)
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model.compile(optimizer=optimizer, loss=loss, metrics=[])
self.model = model
def downsample(filters, kernel_size, apply_batchnorm=True, apply_dropout=0.0,
use_bias=False, strides=2, padding='same', activation='relu',
name=None):
result = tf.keras.Sequential(name=name)
result.add(
tf.keras.layers.Conv2D(filters, kernel_size, strides=strides, padding=padding,
use_bias=use_bias))
if apply_batchnorm:
result.add(tf.keras.layers.BatchNormalization())
if apply_dropout > 0 and apply_dropout < 1.0:
result.add(tf.keras.layers.Dropout(apply_dropout))
if activation == 'leakyrelu':
result.add(tf.keras.layers.LeakyReLU())
elif activation == 'relu':
result.add(tf.keras.layers.ReLU())
return result
def upsample(filters, kernel_size, apply_dropout=0.5, apply_batchnorm=True,
strides=2, padding='same', activation='relu',
use_bias=False, name=None):
result = tf.keras.Sequential(name=name)
result.add(
tf.keras.layers.Conv2DTranspose(filters, kernel_size, strides=strides,
padding=padding,
use_bias=use_bias))
if apply_batchnorm:
result.add(tf.keras.layers.BatchNormalization())
if apply_dropout > 0 and apply_dropout < 1.0:
result.add(tf.keras.layers.Dropout(apply_dropout))
if activation == 'leakyrelu':
result.add(tf.keras.layers.LeakyReLU())
elif activation == 'relu':
result.add(tf.keras.layers.ReLU())
return result
class Patches(layers.Layer):
def __init__(self, patch_size, crop_size=0):
super().__init__()
self.patch_size = patch_size
if isinstance(self.patch_size, int):
self.patch_size = [self.patch_size] * 2
self.crop_size = crop_size
def get_config(self):
config = super().get_config()
config.update({
"patch_size": self.patch_size,
"crop_size": self.crop_size,
})
return config
def call(self, images):
batch_size = tf.shape(images)[0]
if self.crop_size > 0:
images = images[:, self.crop_size:-self.crop_size,
self.crop_size:-self.crop_size, :]
patches = tf.image.extract_patches(
images=images,
sizes=[1, self.patch_size[0], self.patch_size[1], 1],
strides=[1, self.patch_size[0], self.patch_size[1], 1],
rates=[1, 1, 1, 1],
padding="VALID",
)
# print(patches.shape)
patch_dims = patches.shape[-1]
# print('patch_dims', patch_dims)
patches = tf.reshape(
patches, [batch_size, patches.shape[1] * patches.shape[2], patch_dims])
return patches
# Patch encoding layer
class PatchEncoder(layers.Layer):
def __init__(self, num_patches, projection_dim):
super().__init__()
self.num_patches = num_patches
self.projection = layers.Dense(units=projection_dim)
self.position_embedding = layers.Embedding(
input_dim=num_patches, output_dim=projection_dim
)
def call(self, patch):
positions = tf.range(start=0, limit=self.num_patches, delta=1)
encoded = self.projection(patch) + self.position_embedding(positions)
return encoded
def get_config(self):
config = super().get_config()
config.update({
"num_patches": self.num_patches,
"projection_dim": self.projection,
})
return config
# MLP with dropout
def mlp(x, hidden_units, dropout_rate, activation='relu'):
for units in hidden_units:
x = layers.Dense(units, activation=activation)(x)
x = layers.Dropout(dropout_rate)(x)
return x
class EncoderSingleViT(keras.Model):
def __init__(self, output_name, input_shape=(128, 128, 1), cropping=0,
patch_size=5, projection_dim=16, transformer_layers=4, num_heads=12,
transformer_units=[256, 64], mlp_head_units=[256, 64],
dropout_attention=0.1, dropout_mlp=0.1, dropout_representation=0.5, dropout_final=0.5,
learning_rate=0.001, loss='mse', activation='relu',
final_activation='linear', optimizer='adam',
**kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
inputs = layers.Input(shape=input_shape)
# Create patches.
patches = Patches(patch_size, cropping)(inputs)
# Encode patches.
encoded_patches = PatchEncoder(
patches.shape[1], projection_dim)(patches)
# Create multiple layers of the Transformer block.
for _ in range(transformer_layers):
# Layer normalization 1.
x1 = layers.LayerNormalization(epsilon=1e-6)(encoded_patches)
# Create a multi-head attention layer.
attention_output = layers.MultiHeadAttention(
num_heads=num_heads, key_dim=projection_dim, dropout=dropout_attention)(x1, x1)
# Skip connection 1.
x2 = layers.Add()([attention_output, encoded_patches])
# Layer normalization 2.
x3 = layers.LayerNormalization(epsilon=1e-6)(x2)
# MLP.
x3 = mlp(x3, hidden_units=transformer_units,
dropout_rate=dropout_mlp, activation=activation)
# Skip connection 2.
encoded_patches = layers.Add()([x3, x2])
# Create a [batch_size, projection_dim] tensor.
representation = layers.LayerNormalization(
epsilon=1e-6)(encoded_patches)
representation = layers.Flatten()(representation)
representation = layers.Dropout(dropout_representation)(representation)
# Add MLP.
features = mlp(representation, hidden_units=mlp_head_units,
dropout_rate=dropout_final)
# Classify outputs.
outputs = layers.Dense(
1, activation=final_activation, name=output_name)(features)
# Create the Keras model.
model = keras.Model(inputs=inputs, outputs=outputs)
self.model = model
# Also initialize the optimizer and compile the model
if optimizer == 'adam':
model.compile(optimizer=keras.optimizers.Adam(
learning_rate=learning_rate), loss=loss)
elif optimizer == 'sgd':
model.compile(optimizer=keras.optimizers.SGD(
learning_rate=learning_rate), loss=loss)
elif optimizer == 'adamw':
model.compile(optimizer=keras.optimizers.experimental.AdamW(
learning_rate=learning_rate), loss=loss)
# return model
def predict(self, waterfall):
latent = self.model(waterfall)
return latent
def load(self, weights_file):
self.model = keras.models.load_model(weights_file)
def save(self, weights_file):
self.model.save(weights_file)
class EncoderSingle(keras.Model):
# Pooling can be None, or 'Average' or 'Max'
def __init__(self, output_name, input_shape=(128, 128, 1), dense_layers=[1024, 256, 64],
filters=[8, 16, 32], cropping=[[0, 0], [0, 0]], kernel_size=3,
strides=[2, 2], activation='relu',
pooling=None, pooling_size=[2, 2],
pooling_strides=[1, 1], pooling_padding='same',
dropout=0.0, learning_rate=0.001, loss='mse',
metrics=[], use_bias=True, batchnorm=False,
conv_batchnorm=False, conv_padding='same',
**kwargs):
super().__init__()
self.output_name = output_name
self.inputShape = input_shape
# the kernel_size can be a single int or a list of ints
if isinstance(kernel_size, int):
kernel_size = [kernel_size] * len(filters)
assert len(kernel_size) == len(filters)
# the strides can be a list of two ints, or a list of two-int lists
if isinstance(strides[0], int):
strides = [strides for _ in filters]
assert len(strides) == len(filters)
# set the input size
inputs = keras.Input(shape=input_shape, name='Input')
# crop the edges
cropped = keras.layers.Cropping2D(
cropping=cropping, name='Crop')(inputs)
x = cropped
# For evey Convolutional layer
for i, f in enumerate(filters):
# Add the Convolution
x = keras.layers.Conv2D(
filters=f, kernel_size=kernel_size[i], strides=strides[i],
use_bias=use_bias, padding=conv_padding, activation=activation,
name=f'{output_name}_CNN_{i+1}')(x)
# Apply batchnormalization
if conv_batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Apply the activation function
# x = keras.activations.get(activation)(x)
# Optional pooling after the convolution
if pooling == 'Max':
x = keras.layers.MaxPooling2D(
pool_size=pooling_size, strides=pooling_strides,
padding=pooling_padding, name=f'{output_name}_MaxPooling_{i+1}')(x)
elif pooling == 'Average':
x = keras.layers.AveragePooling2D(
pool_size=pooling_size, strides=pooling_strides,
padding=pooling_padding, name=f'{output_name}_AveragePooling_{i+1}')(x)
# Flatten after the convolutions
x = keras.layers.Flatten(name=f'{output_name}_Flatten')(x)
# For each optional dense layer
for i, layer in enumerate(dense_layers):
# Add the layer
x = keras.layers.Dense(layer, activation=activation,
name=f'{output_name}_Dense_{i+1}')(x)
# Apply batchnormalization
if batchnorm:
x = tf.keras.layers.BatchNormalization()(x)
# Add dropout optionally
if dropout > 0 and dropout < 1:
x = keras.layers.Dropout(
dropout, name=f'{output_name}_Dropout_{i+1}')(x)
# Add the final layers, one for each output
outputs = keras.layers.Dense(1, name=output_name)(x)
# Also initialize the optimizer and compile the model
optimizer = keras.optimizers.Adam(learning_rate=learning_rate)
model = keras.Model(inputs=inputs, outputs=outputs)
model.compile(optimizer=optimizer, loss=loss, metrics=metrics)
self.model = model
def predict(self, waterfall):
latent = self.model(waterfall)
return latent
def load(self, weights_file):
self.model = keras.models.load_model(weights_file)
def save(self, weights_file):
self.model.save(weights_file)
class EncoderMulti:
var_names = ['phEr', 'enEr', 'bl',
'inten', 'Vrf', 'mu',
'VrfSPS']
# By default, the model does not predict the intensity variable
def __init__(self, enc_list=[]):
# If a list of models is provided, use it. Otherwise, default initialize models.
if len(enc_list) > 0:
self.model = enc_list
else:
self.model = [
EncoderSingle(output_name='phEr', kernel_size=[3, 3],
filters=[4, 8]),
EncoderSingle(output_name='enEr', cropping=[6, 6]),
EncoderSingle(output_name='bl', cropping=[12, 12],
kernel_size=[(13, 3), (7, 3), (3, 3)]),
EncoderSingle(output_name='inten'),
EncoderSingle(output_name='Vrf', cropping=[6, 6],
kernel_size=[13, 7, 3]),
EncoderSingle(output_name='mu', kernel_size=[5, 5, 5]),
EncoderSingle(output_name='VrfSPS', cropping=[6, 6],
kernel_size=[5, 5, 5]),
]
self.inputShape = self.model[0].inputShape
def load(self, weights_dir):
weights_dir_files = os.listdir(weights_dir)
for model in self.model:
# For every model load parameters from weights dir
var = model.output_name
fname = f'encoder_{var}.h5'
if fname in weights_dir_files:
model.load(os.path.join(weights_dir, fname))
else:
pass
# raise FileNotFoundError(
# f'File {fname} not found in {weights_dir}')
def save(self, model_path):
# Save all individual models
for model in self.model:
var = model.output_name
file_path = os.path.join(model_path, f'encoder_{var}.h5')
model.save(file_path)
def predict(self, waterfall, unnormalize=False, normalization='minmax'):
# collect the latents
latent = tf.concat([m.predict(waterfall)
for m in self.model], axis=1)
# optionally normallize them
if unnormalize:
latent = unnormalize_params(
latent[:, 0], latent[:, 1], latent[:, 2],
latent[:, 3], latent[:, 4], latent[:, 5],
latent[:, 6], normalization=normalization)
latent = np.array(latent).T
return latent
def summary(self):
for model in self.model:
model.model.summary()
print()
class Decoder(keras.Model):
def __init__(self, output_shape=(128, 128, 1), dense_layers=[8, 64, 1024],
filters=[32, 16, 8, 1],
kernel_size=3, strides=[2, 2],
activation='relu', final_kernel_size=3,
final_activation='linear',
dropout=0.0, learning_rate=0.001, loss='mse',
**kwargs):
super().__init__()
assert filters[-1] == 1
# assert dense_layers[0] == 8
# I calculate the dimension if I was moving:
# output_shape --> filter[-1] --> filter[-2] .. filter[0]
# Generate the inverse model (encoder) to find the t_shape