-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel_zoo.py
More file actions
2726 lines (2142 loc) · 133 KB
/
model_zoo.py
File metadata and controls
2726 lines (2142 loc) · 133 KB
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
###########################################################################################################
## IMPORTS
###########################################################################################################
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import math
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
import pickle
from keras.layers.advanced_activations import LeakyReLU, ELU, ReLU
from keras.models import Sequential, Model, model_from_json
from keras.layers import Activation, Convolution2D, Conv2D, LocallyConnected2D, MaxPooling2D, AveragePooling2D, GlobalAveragePooling2D, BatchNormalization, Flatten, Dense, Dropout, Input, concatenate, add, Add, ZeroPadding2D, GlobalMaxPooling2D, DepthwiseConv2D
from keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping
from keras.optimizers import Adam
from keras.regularizers import l2
#from keras.activations import linear, elu, tanh, relu
from keras import metrics, losses, initializers, backend
from keras.utils import multi_gpu_model
from keras.initializers import glorot_uniform, Constant, lecun_uniform
from keras import backend as K
os.environ["PATH"] += os.pathsep + "C:/ProgramData/Anaconda3/GraphViz/bin/"
os.environ["PATH"] += os.pathsep + "C:/Anaconda/Graphviz2.38/bin/"
from keras.utils.vis_utils import plot_model
from sklearn.model_selection import train_test_split
import tensorflow as tf
np.random.seed(42)
tf.random.set_seed(42)
tf.get_logger().setLevel('ERROR')
physical_devices = tf.config.list_physical_devices('GPU')
for pd_dev in range(len(physical_devices)):
tf.config.experimental.set_memory_growth(physical_devices[pd_dev], True)
##from tensorflow.compat.v1.keras.backend import set_session
##config = tf.compat.v1.ConfigProto()
##config.gpu_options.per_process_gpu_memory_fraction = 0.9
##config.gpu_options.allow_growth = True
##config.log_device_placement = True
##set_session(config)
#config = tf.compat.v1.ConfigProto()
#config.gpu_options.allow_growth = True
#config.log_device_placement = True
#sess = tf.compat.v1.InteractiveSession(config = config)
#set_session(sess)
#backend.set_session(sess)
###########################################################################################################
## PLOTTING PALETTE
###########################################################################################################
# Create a dict object containing U.C. Berkeley official school colors for plot palette
# reference : https://alumni.berkeley.edu/brand/color-palette
berkeley_palette = {'berkeley_blue' : '#003262',
'california_gold' : '#FDB515',
'metallic_gold' : '#BC9B6A',
'founders_rock' : '#2D637F',
'medalist' : '#E09E19',
'bay_fog' : '#C2B9A7',
'lawrence' : '#00B0DA',
'sather_gate' : '#B9D3B6',
'pacific' : '#53626F',
'soybean' : '#9DAD33',
'california_purple' : '#5C3160',
'south_hall' : '#6C3302'}
###########################################################################################################
## CLASS CONTAINING MODEL ZOO
###########################################################################################################
class Models(object):
def __init__(self, model_path, **kwargs):
super(Models, self).__init__(** kwargs)
# validate that the constructor parameters were provided by caller
if (not model_path):
raise RuntimeError('path to model files must be provided on initialization.')
# ensure all are string snd leading/trailing whitespace removed
model_path = str(model_path).replace('\\', '/').strip()
if (not model_path.endswith('/')): model_path = ''.join((model_path, '/'))
# validate the existence of the data path
if (not os.path.isdir(model_path)):
raise RuntimeError("Models path specified'%s' is invalid." % model_path)
self.__models_path = model_path
self.__GPU_count = len(tf.config.list_physical_devices('GPU'))
self.__MIN_early_stopping = 10
#------------------------------------------------
# Private Methods
#------------------------------------------------
# plotting method for keras history arrays
def __plot_keras_history(self, history, metric, model_name, feature_name, file_name, verbose = False):
# Plot the performance of the model training
fig = plt.figure(figsize=(15,8),dpi=80)
ax = fig.add_subplot(121)
ax.plot(history.history[metric][1:], color = berkeley_palette['founders_rock'], label = 'Train',
marker = 'o', markersize = 4, alpha = 0.9)
ax.plot(history.history["".join(["val_",metric])][1:], color = berkeley_palette['medalist'], label = 'Validation',
marker = 'o', markersize = 4, alpha = 0.9)
ax.set_title(" ".join(['Model Performance',"(" + model_name + ")"]) + "\n" + feature_name,
color = berkeley_palette['berkeley_blue'], fontsize = 15, fontweight = 'bold')
ax.spines["top"].set_alpha(.0)
ax.spines["bottom"].set_alpha(.3)
ax.spines["right"].set_alpha(.0)
ax.spines["left"].set_alpha(.3)
ax.set_xlabel("Epoch", fontsize = 12, horizontalalignment='right', x = 1.0, color = berkeley_palette['berkeley_blue'])
ax.set_ylabel(metric, fontsize = 12, horizontalalignment='right', y = 1.0, color = berkeley_palette['berkeley_blue'])
plt.legend(loc = 'upper right')
ax = fig.add_subplot(122)
ax.plot(history.history['loss'][1:], color = berkeley_palette['founders_rock'], label = 'Train',
marker = 'o', markersize = 4, alpha = 0.9)
ax.plot(history.history["".join(["val_loss"])][1:], color = berkeley_palette['medalist'], label = 'Validation',
marker = 'o', markersize = 4, alpha = 0.9)
ax.set_title(" ".join(['Model Performance',"(" + model_name + ")"]) + "\n" + feature_name,
color = berkeley_palette['berkeley_blue'], fontsize = 15, fontweight = 'bold')
ax.spines["top"].set_alpha(.0)
ax.spines["bottom"].set_alpha(.3)
ax.spines["right"].set_alpha(.0)
ax.spines["left"].set_alpha(.3)
ax.set_xlabel("Epoch", fontsize = 12, horizontalalignment='right', x = 1.0, color = berkeley_palette['berkeley_blue'])
ax.set_ylabel("Loss", fontsize = 12, horizontalalignment='right', y = 1.0, color = berkeley_palette['berkeley_blue'])
plt.legend(loc = 'upper right')
plt.tight_layout()
plt.savefig(file_name, dpi=300)
if verbose: print("Training plot file saved to '%s'." % file_name)
plt.close()
# load Keras model files from json / h5
def __load_keras_model(self, model_name, model_file, model_json, verbose = False):
"""Loads a Keras model from disk"""
if not os.path.isfile(model_file):
raise RuntimeError("Model file '%s' does not exist; exiting inferencing." % model_file)
if not os.path.isfile(model_json):
raise RuntimeError("Model file '%s' does not exist; exiting inferencing." % model_json)
# load model file
if verbose: print("Retrieving model: %s..." % model_name)
json_file = open(model_json, "r")
model_json_data = json_file.read()
json_file.close()
model = model_from_json(model_json_data)
model.load_weights(model_file)
return model
# Performs standard scaling on a 4D image
def __4d_Scaler(self, arr, ss, fit = False, verbose = False):
"""Performs standard scaling of the 4D array with the 'ss' model provided by caller"""
#Unwinds a (instances, rows, columns, layers) array to 2D for standard scaling
num_instances, num_rows, num_columns, num_layers = arr.shape
arr_copy = np.reshape(arr, (-1, num_columns))
# fit the standard scaler
if fit:
if verbose: print("Fitting SCALER and transforming...")
arr_copy = ss.fit_transform(arr_copy)
else:
if verbose: print("Transforming SCALER only...")
arr_copy = ss.transform(arr_copy)
arr = np.reshape(arr_copy, (num_instances, num_rows, num_columns, num_layers))
return arr
# resnet identity block builder
def __identity_block(self, model, kernel_size, filters, stage, block):
"""modularized identity block for resnet"""
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
x = Conv2D(filters1, (1, 1),
kernel_initializer='he_normal',
name=conv_name_base + '2a')(model)
x = BatchNormalization(axis=3, name=bn_name_base + '2a')(x)
x = Activation('relu')(x)
x = Conv2D(filters2, kernel_size,
padding='same',
kernel_initializer='he_normal',
name=conv_name_base + '2b')(x)
x = BatchNormalization(axis=3, name=bn_name_base + '2b')(x)
x = Activation('relu')(x)
x = Conv2D(filters3, (1, 1),
kernel_initializer='he_normal',
name=conv_name_base + '2c')(x)
x = BatchNormalization(axis=3, name=bn_name_base + '2c')(x)
x = add([x, model])
x = Activation('relu')(x)
return x
# resnet conv block builder
def __conv_block(self, model, kernel_size, filters, stage, block, strides=(2, 2)):
"""conv block builder for resnet"""
filters1, filters2, filters3 = filters
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
x = Conv2D(filters1, (1, 1), strides=strides,
kernel_initializer='he_normal',
name=conv_name_base + '2a')(model)
x = BatchNormalization(axis=3, name=bn_name_base + '2a')(x)
x =Activation('relu')(x)
x = Conv2D(filters2, kernel_size, padding='same',
kernel_initializer='he_normal',
name=conv_name_base + '2b')(x)
x = BatchNormalization(axis=3, name=bn_name_base + '2b')(x)
x = Activation('relu')(x)
x = Conv2D(filters3, (1, 1),
kernel_initializer='he_normal',
name=conv_name_base + '2c')(x)
x = BatchNormalization(axis=3, name=bn_name_base + '2c')(x)
shortcut = Conv2D(filters3, (1, 1), strides=strides,
kernel_initializer='he_normal',
name=conv_name_base + '1')(model)
shortcut = BatchNormalization(
axis=3, name=bn_name_base + '1')(shortcut)
x = add([x, shortcut])
x = Activation('relu')(x)
return x
# create a layerable inception module
def __inception_module(self, model, filters_1x1, filters_3x3_reduce, filters_3x3,
filters_5x5_reduce, filters_5x5, filters_pool_proj, kernel_init, bias_init, name = None):
"""modularized inception block for layering"""
# Connection Layer 1 (1x1)
conv_1x1 = Convolution2D(filters_1x1, (1, 1), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (model)
# Connection Layer 2 (3x3)
conv_3x3 = Convolution2D(filters_3x3_reduce, (1, 1), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (model)
conv_3x3 = Convolution2D(filters_3x3, (3, 3), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (conv_3x3)
# Connection Layer 3 (5x5)
conv_5x5 = Convolution2D(filters_5x5_reduce, (1, 1), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (model)
conv_5x5 = Convolution2D(filters_5x5, (5, 5), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (conv_5x5)
# Connection Layer 4 (pool)
pool_proj = MaxPooling2D((3, 3), strides = (1, 1), padding = 'same') (model)
pool_proj = Convolution2D(filters_pool_proj, (1, 1), padding = 'same', activation = 'relu',
kernel_initializer = kernel_init, bias_initializer = bias_init) (pool_proj)
# Concatenation layer
output = concatenate(inputs = [conv_1x1, conv_3x3, conv_5x5, pool_proj], axis = 3, name = name)
return output
# return an InceptionV3 output tensor after applying Conv2D and BatchNormalization
def __conv2d_bn(self, x, filters, num_row, num_col, padding = 'same', strides = (1, 1), name = None):
if name is not None:
bn_name = name + '_bn'
conv_name = name + '_conv'
else:
bn_name = None
conv_name = None
bn_axis = 3
x = Convolution2D(filters, (num_row, num_col), strides = strides,
padding = padding, use_bias = False, name = conv_name) (x)
x = BatchNormalization(axis = bn_axis, scale = False, name = bn_name) (x)
x = ReLU(name = name) (x)
return x
# a residual block for resnext
def __resnext_block(self, x, filters, kernel_size = 3, stride = 1, groups = 32, conv_shortcut = True, name = None):
if conv_shortcut is True:
shortcut = Conv2D((64 // groups) * filters, 1, strides = stride, use_bias = False, name = name + '_0_conv') (x)
shortcut = BatchNormalization(axis = 3, epsilon=1.001e-5, name = name + '_0_bn') (shortcut)
else:
shortcut = x
x = Conv2D(filters, 1, use_bias = False, name = name + '_1_conv') (x)
x = BatchNormalization(axis = 3, epsilon = 1.001e-5, name = name + '_1_bn') (x)
x = Activation('relu', name = name + '_1_relu') (x)
c = filters // groups
x = ZeroPadding2D(padding=((1, 1), (1, 1)), name=name + '_2_pad')(x)
x = DepthwiseConv2D(kernel_size, strides = stride, depth_multiplier = c, use_bias = False, name = name + '_2_conv') (x)
kernel = np.zeros((1, 1, filters * c, filters), dtype = np.float32)
for i in range(filters):
start = (i // c) * c * c + i % c
end = start + c * c
kernel[:, :, start:end:c, i] = 1.
x = Conv2D(filters, 1, use_bias = False, trainable = False, kernel_initializer = {'class_name': 'Constant','config': {'value': kernel}}, name = name + '_2_gconv') (x)
x = BatchNormalization(axis=3, epsilon = 1.001e-5, name = name + '_2_bn') (x)
x = Activation('relu', name=name + '_2_relu') (x)
x = Conv2D((64 // groups) * filters, 1, use_bias = False, name = name + '_3_conv') (x)
x = BatchNormalization(axis = 3, epsilon=1.001e-5, name = name + '_3_bn') (x)
x = Add(name = name + '_add') ([shortcut, x])
x = Activation('relu', name = name + '_out') (x)
return x
# a set of stacked residual blocks for ResNeXt
def __resnext_stack(self, x, filters, blocks, stride1 = 2, groups = 32, name = None, dropout = None):
x = self.__resnext_block(x, filters, stride = stride1, groups = groups, name = name + '_block1')
for i in range(2, blocks + 1):
x = self.__resnext_block(x, filters, groups = groups, conv_shortcut = False,
name = name + '_block' + str(i))
if not dropout is None:
x = Dropout(dropout) (x)
return x
def __bn_relu(self, x, bn_name = None, relu_name = None):
norm = BatchNormalization(axis = 3, name = bn_name) (x)
return Activation("relu", name = relu_name) (norm)
def __bn_relu_conv(self, **conv_params):
filters = conv_params["filters"]
kernel_size = conv_params["kernel_size"]
strides = conv_params.setdefault("strides", (1, 1))
dilation_rate = conv_params.setdefault("dilation_rate", (1, 1))
conv_name = conv_params.setdefault("conv_name", None)
bn_name = conv_params.setdefault("bn_name", None)
relu_name = conv_params.setdefault("relu_name", None)
kernel_initializer = conv_params.setdefault("kernel_initializer", "he_normal")
padding = conv_params.setdefault("padding", "same")
kernel_regularizer = conv_params.setdefault("kernel_regularizer", l2(1.e-4))
def f(x):
activation = self.__bn_relu(x, bn_name = bn_name, relu_name = relu_name)
return Conv2D(filters = filters, kernel_size = kernel_size,
strides = strides, padding = padding,
dilation_rate = dilation_rate,
kernel_initializer = kernel_initializer,
kernel_regularizer = kernel_regularizer,
name = conv_name) (activation)
return f
def __conv_bn_relu(self, **conv_params):
filters = conv_params["filters"]
kernel_size = conv_params["kernel_size"]
strides = conv_params.setdefault("strides", (1, 1))
dilation_rate = conv_params.setdefault("dilation_rate", (1, 1))
conv_name = conv_params.setdefault("conv_name", None)
bn_name = conv_params.setdefault("bn_name", None)
relu_name = conv_params.setdefault("relu_name", None)
kernel_initializer = conv_params.setdefault("kernel_initializer", "he_normal")
padding = conv_params.setdefault("padding", "same")
kernel_regularizer = conv_params.setdefault("kernel_regularizer", l2(1.e-4))
def f(x):
x = Conv2D(filters = filters, kernel_size = kernel_size,
strides = strides, padding = padding,
dilation_rate = dilation_rate,
kernel_initializer = kernel_initializer,
kernel_regularizer = kernel_regularizer,
name = conv_name) (x)
return self.__bn_relu(x, bn_name = bn_name, relu_name = relu_name)
return f
def __block_name_base(self, stage, block):
if block < 27:
block = '%c' % (block + 97) # 97 is the ascii number for lowercase 'a'
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
return conv_name_base, bn_name_base
def __shortcut(self, input_feature, residual, conv_name_base = None, bn_name_base = None):
input_shape = K.int_shape(input_feature)
residual_shape = K.int_shape(residual)
stride_width = int(round(input_shape[1] / residual_shape[1]))
stride_height = int(round(input_shape[2] / residual_shape[2]))
equal_channels = input_shape[3] == residual_shape[3]
shortcut = input_feature
# 1 X 1 conv if shape is different. Else identity.
if stride_width > 1 or stride_height > 1 or not equal_channels:
print('reshaping via a convolution...')
if conv_name_base is not None:
conv_name_base = conv_name_base + '1'
shortcut = Conv2D(filters=residual_shape[3],
kernel_size=(1, 1),
strides=(stride_width, stride_height),
padding="valid",
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
name=conv_name_base)(input_feature)
if bn_name_base is not None:
bn_name_base = bn_name_base + '1'
shortcut = BatchNormalization(axis=3,
name=bn_name_base)(shortcut)
return add([shortcut, residual])
def __basic_block(self, filters, stage, block, transition_strides = (1, 1),
dilation_rate = (1, 1), is_first_block_of_first_layer = False, dropout = None,
residual_unit = None):
def f(input_features):
conv_name_base, bn_name_base = self.__block_name_base(stage, block)
if is_first_block_of_first_layer:
# don't repeat bn->relu since we just did bn->relu->maxpool
x = Conv2D(filters = filters, kernel_size = (3, 3),
strides = transition_strides, dilation_rate = dilation_rate,
padding = "same", kernel_initializer = "he_normal", kernel_regularizer = l2(1e-4),
name = conv_name_base + '2a') (input_features)
else:
x = residual_unit(filters = filters, kernel_size = (3, 3),
strides = transition_strides,
dilation_rate = dilation_rate,
conv_name_base = conv_name_base + '2a',
bn_name_base = bn_name_base + '2a') (input_features)
if dropout is not None:
x = Dropout(dropout) (x)
x = residual_unit(filters = filters, kernel_size = (3, 3),
conv_name_base = conv_name_base + '2b',
bn_name_base = bn_name_base + '2b') (x)
return self.__shortcut(input_features, x)
return f
def __bottleneck(self, filters, stage, block, transition_strides = (1, 1),
dilation_rate = (1, 1), is_first_block_of_first_layer = False, dropout = None,
residual_unit = None):
"""Bottleneck architecture for > 34 layer resnet.
Follows improved proposed scheme in http://arxiv.org/pdf/1603.05027v2.pdf
Returns:
A final conv layer of filters * 4
"""
def f(input_feature):
conv_name_base, bn_name_base = self.__block_name_base(stage, block)
if is_first_block_of_first_layer:
# don't repeat bn->relu since we just did bn->relu->maxpool
x = Conv2D(filters=filters, kernel_size=(1, 1),
strides=transition_strides,
dilation_rate=dilation_rate,
padding="same",
kernel_initializer="he_normal",
kernel_regularizer=l2(1e-4),
name=conv_name_base + '2a')(input_feature)
else:
x = residual_unit(filters=filters, kernel_size=(1, 1),
strides=transition_strides,
dilation_rate=dilation_rate,
conv_name_base=conv_name_base + '2a',
bn_name_base=bn_name_base + '2a')(input_feature)
if dropout is not None:
x = Dropout(dropout)(x)
x = residual_unit(filters=filters, kernel_size=(3, 3),
conv_name_base=conv_name_base + '2b',
bn_name_base=bn_name_base + '2b')(x)
if dropout is not None:
x = Dropout(dropout)(x)
x = residual_unit(filters=filters * 4, kernel_size=(1, 1),
conv_name_base=conv_name_base + '2c',
bn_name_base=bn_name_base + '2c')(x)
return self.__shortcut(input_feature, x)
return f
# builds a residual block for resnet with repeating bottleneck blocks
def __residual_block(self, block_function, filters, blocks, stage, transition_strides = None, transition_dilation_rates = None,
dilation_rates = None, is_first_layer = False, dropout = None, residual_unit = None):
if transition_dilation_rates is None:
transition_dilation_rates = [(1, 1)] * blocks
if transition_strides is None:
transition_strides = [(1, 1)] * blocks
if dilation_rates is None:
dilation_rates = [1] * blocks
def f(x):
for i in range(blocks):
is_first_block = is_first_layer and i == 0
x = block_function(filters=filters, stage=stage, block=i,
transition_strides=transition_strides[i],
dilation_rate=dilation_rates[i],
is_first_block_of_first_layer=is_first_block,
dropout=dropout,
residual_unit=residual_unit)(x)
return x
return f
######################################################
######################################################
######################################################
### KERAS MODEL ZOO
######################################################
######################################################
######################################################
#------------------------------------------------
# NaimishNet Model
# ref: https://arxiv.org/abs/1710.00977
#------------------------------------------------
def get_keras_naimishnet(self, X, Y, batch_size, epoch_count, X_val = None, Y_val = None, val_split = 0.1, shuffle = True,
feature_name = "unknown", recalculate_pickle = True, full = True, verbose = False):
__MODEL_NAME = "Keras - NaimishNet"
__MODEL_FNAME_PREFIX = "KERAS_NAIMISHNET/"
if full:
__MODEL_SUFFIX = "_30"
else:
__MODEL_SUFFIX = "_8"
nested_dir = "".join([self.__models_path,__MODEL_FNAME_PREFIX])
if not os.path.exists(nested_dir):
os.makedirs(nested_dir)
__model_file_name = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, ".h5"])
__model_json_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, ".json"])
__history_params_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, "_params.csv"])
__history_performance_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, "_history.csv"])
__history_plot_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, "_plot.png"])
__model_architecture_plot_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, "_model_plot.png"])
if verbose: print("Retrieving model: %s..." % "".join([__MODEL_NAME, "_", feature_name, __MODEL_SUFFIX]))
# Create or load the model
if (not os.path.isfile(__model_file_name)) or (not os.path.isfile(__model_json_file)) or recalculate_pickle:
if verbose: print("Pickle file for '%s' MODEL not found or skipped by caller." % feature_name)
act = Adam(lr = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-08)
lss = 'mean_squared_error'
mtrc = ['mae','mse']
#ke = initializers.lecun_uniform(seed = 42)
ke = 'glorot_uniform'
stop_at = np.max([int(0.1 * epoch_count), self.__MIN_early_stopping])
es = EarlyStopping(patience = stop_at, verbose = verbose)
cp = ModelCheckpoint(filepath = __model_file_name, verbose = verbose, save_best_only = True,
mode = 'min', monitor = 'val_mae')
if self.__GPU_count > 1: dev = "/cpu:0"
else: dev = "/gpu:0"
with tf.device(dev):
l1 = Input((96, 96, 1))
l2 = Convolution2D(32, (4, 4), kernel_initializer = ke, padding = 'valid', activation = 'elu') (l1)
#l3 = ELU() (l2)
l3 = MaxPooling2D(pool_size=(2,2), strides = (2,2)) (l2)
l4 = Dropout(rate = 0.1) (l3)
l5 = Convolution2D(64, (3, 3), kernel_initializer = ke, padding = 'valid', activation = 'elu') (l4)
#l7 = ELU() (l6)
l6 = MaxPooling2D(pool_size=(2,2), strides = (2,2)) (l5)
l7 = Dropout(rate = 0.2) (l6)
l8 = Convolution2D(128, (2, 2), kernel_initializer = ke, padding = 'valid', activation = 'elu') (l7)
#l11 = ELU() (l10)
l9 = MaxPooling2D(pool_size=(2,2), strides = (2,2)) (l8)
l10 = Dropout(rate = 0.3) (l9)
l11 = Convolution2D(256, (1, 1), kernel_initializer = ke, padding = 'valid', activation = 'elu') (l10)
#l15 = ELU() (l14)
l12 = MaxPooling2D(pool_size=(2,2), strides = (2,2)) (l11)
l13 = Dropout(rate = 0.4) (l12)
l14 = Flatten() (l13)
l15 = Dense(1000, activation = 'elu') (l14)
#l20 = ELU() (l19)
l16 = Dropout(rate = 0.5) (l15)
#l22 = Dense(1000) (l21)
#l23 = linear(l22)
l17 = Dense(1000, activation = 'linear') (l16)
l18 = Dropout(rate = 0.6) (l17)
l19 = Dense(2) (l18)
model = Model(inputs = [l1], outputs = [l19])
model.compile(optimizer = act, loss = lss, metrics = mtrc)
if verbose: print(model.summary())
# Compile the model
if self.__GPU_count > 1:
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
parallel_model = multi_gpu_model(model, gpus = self.__GPU_count)
parallel_model.compile(optimizer = act, loss = lss, metrics = mtrc)
else:
parallel_model = model
parallel_model.compile(optimizer = act, loss = lss, metrics = mtrc)
if (X_val is None) or (Y_val is None):
history = parallel_model.fit(X, Y, validation_split = val_split, batch_size = batch_size * self.__GPU_count,
epochs = epoch_count, shuffle = shuffle, callbacks = [es, cp], verbose = verbose)
else:
history = parallel_model.fit(X, Y, validation_data = (X_val, Y_val), batch_size = batch_size * self.__GPU_count,
epochs = epoch_count, shuffle = shuffle, callbacks = [es, cp], verbose = verbose)
# print and/or save a performance plot
self.__plot_keras_history(history = history, metric = 'mse', model_name = __MODEL_NAME,
feature_name = feature_name, file_name = __history_plot_file, verbose = verbose)
# save the model, parameters, and performance history
model_json = parallel_model.to_json()
with open(__model_json_file, "w") as json_file:
json_file.write(model_json)
hist_params = pd.DataFrame(history.params)
hist_params.to_csv(__history_params_file)
hist = pd.DataFrame(history.history)
hist.to_csv(__history_performance_file)
if verbose: print("Model JSON, history, and parameters file saved.")
# save a plot of the model architecture
plot_model(parallel_model, to_file = __model_architecture_plot_file, rankdir = 'TB',
show_shapes = True, show_layer_names = True, expand_nested = True, dpi=300)
else:
if verbose: print("Loading history and params files for '%s' MODEL..." % feature_name)
hist_params = pd.read_csv(__history_params_file)
hist = pd.read_csv(__history_performance_file)
if verbose: print("Loading pickle file for '%s' MODEL from file '%s'" % (feature_name, __model_file_name))
modparallel_modelel = self.__load_keras_model(__MODEL_NAME, __model_file_name, __model_json_file, verbose = verbose)
return parallel_model, hist_params, hist
# inferencing
def predict_keras_naimishnet(self, X, feature_name = "unknown", full = True, verbose = False):
__MODEL_NAME = "Keras - NaimishNet"
__MODEL_FNAME_PREFIX = "KERAS_NAIMISHNET/"
if full:
__MODEL_SUFFIX = "_30"
else:
__MODEL_SUFFIX = "_8"
nested_dir = "".join([self.__models_path,__MODEL_FNAME_PREFIX])
if not os.path.exists(nested_dir):
raise RuntimeError("Model path '%s' does not exist; exiting inferencing." % nested_dir)
__model_file_name = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, ".h5"])
__model_json_file = "".join([nested_dir, "NaimishNet_", feature_name, __MODEL_SUFFIX, ".json"])
if (not os.path.isfile(__model_file_name)) or (not os.path.isfile(__model_json_file)):
raise RuntimeError("One or some of the following files are missing; prediction cancelled:\n\n'%s'\n'%s'\n" %
(__model_file_name, __model_json_file))
# load the Keras model for the specified feature
model = self.__load_keras_model(__MODEL_NAME, __model_file_name, __model_json_file, verbose = verbose)
# predict
if verbose: print("Predicting %d (x,y) coordinates for '%s'..." % (len(X), feature_name))
Y = model.predict(X, verbose = verbose)
if verbose: print("Predictions completed!")
return Y
#------------------------------------------------
# Kaggle1 Model
# Inspired by: https://www.kaggle.com/balraj98/data-augmentation-for-facial-keypoint-detection
#------------------------------------------------
def get_keras_kaggle1(self, X, Y, batch_size, epoch_count, val_split = 0.05, X_val = None, Y_val = None, shuffle = True,
feature_name = "ALL_FEATURES", recalculate_pickle = True, full = True, verbose = False):
__MODEL_NAME = "Keras - Kaggle1"
__MODEL_FNAME_PREFIX = "KERAS_KAGGLE1/"
if full:
__MODEL_SUFFIX = "_30"
else:
__MODEL_SUFFIX = "_8"
nested_dir = "".join([self.__models_path,__MODEL_FNAME_PREFIX])
if not os.path.exists(nested_dir):
os.makedirs(nested_dir)
__model_file_name = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".h5"])
__model_json_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".json"])
__history_params_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_params.csv"])
__history_performance_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_history.csv"])
__history_plot_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_plot.png"])
__model_architecture_plot_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_model_plot.png"])
##__scaler_file = "".join([nested_dir, feature_name, "_scaler.pkl"])
if verbose: print("Retrieving model: %s..." % "".join([__MODEL_NAME, __MODEL_SUFFIX]))
# Create or load the model
if (not os.path.isfile(__model_file_name)) or (not os.path.isfile(__model_json_file)) or recalculate_pickle:
if verbose: print("Pickle file for '%s' MODEL not found or skipped by caller." % feature_name)
#act = Adam(lr = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-08)
act = 'adam'
#lss = losses.mean_squared_error
lss = 'mean_squared_error'
#mtrc = [metrics.RootMeanSquaredError()]
mtrc = ['mae','mse']
stop_at = np.max([int(0.1 * epoch_count), self.__MIN_early_stopping])
es = EarlyStopping(patience = stop_at, verbose = verbose)
cp = ModelCheckpoint(filepath = __model_file_name, verbose = verbose, save_best_only = True,
mode = 'min', monitor = 'val_mae')
if self.__GPU_count > 1: dev = "/cpu:0"
else: dev = "/gpu:0"
with tf.device(dev):
model = Sequential()
# Input dimensions: (None, 96, 96, 1)
model.add(Convolution2D(32, (3,3), padding='same', use_bias=False, input_shape=(96,96,1)))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 96, 96, 32)
model.add(Convolution2D(32, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
# CDB: 3/5 DROPOUT ADDED
model.add(Dropout(0.2))
# Input dimensions: (None, 48, 48, 32)
model.add(Convolution2D(64, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 48, 48, 64)
model.add(Convolution2D(64, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
# CDB: 3/5 DROPOUT ADDED
model.add(Dropout(0.25))
# Input dimensions: (None, 24, 24, 64)
model.add(Convolution2D(96, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 24, 24, 96)
model.add(Convolution2D(96, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
# CDB: 3/5 DROPOUT ADDED
model.add(Dropout(0.15))
# Input dimensions: (None, 12, 12, 96)
model.add(Convolution2D(128, (3,3),padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 12, 12, 128)
model.add(Convolution2D(128, (3,3),padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
# CDB: 3/5 DROPOUT ADDED
model.add(Dropout(0.3))
# Input dimensions: (None, 6, 6, 128)
model.add(Convolution2D(256, (3,3),padding='same',use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 6, 6, 256)
model.add(Convolution2D(256, (3,3),padding='same',use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
# CDB: 3/5 DROPOUT ADDED
model.add(Dropout(0.2))
# Input dimensions: (None, 3, 3, 256)
model.add(Convolution2D(512, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 3, 3, 512)
model.add(Convolution2D(512, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# TEST added 4/8
model.add(Dropout(0.3))
model.add(Convolution2D(1024, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 3, 3, 512)
model.add(Convolution2D(1024, (3,3), padding='same', use_bias=False))
model.add(LeakyReLU(alpha = 0.1))
model.add(BatchNormalization())
# Input dimensions: (None, 3, 3, 512)
model.add(Flatten())
model.add(Dense(1024,activation='relu'))
# CDB DROPOUT INCREASED FROM 0.1 to 0.2
model.add(Dropout(0.15))
if full:
model.add(Dense(30))
else:
model.add(Dense(8))
if verbose: print(model.summary())
# Compile the model
if self.__GPU_count > 1:
strategy = tf.distribute.MirroredStrategy()
with strategy.scope():
parallel_model = multi_gpu_model(model, gpus = self.__GPU_count)
parallel_model.compile(optimizer = act, loss = lss, metrics = mtrc)
else:
parallel_model = model
parallel_model.compile(optimizer = act, loss = lss, metrics = mtrc)
if (X_val is None) or (Y_val is None):
history = parallel_model.fit(X, Y, validation_split = val_split, batch_size = batch_size * self.__GPU_count,
epochs = epoch_count, shuffle = shuffle, callbacks = [es, cp], verbose = verbose)
else:
history = parallel_model.fit(X, Y, validation_data = (X_val, Y_val), batch_size = batch_size * self.__GPU_count,
epochs = epoch_count, shuffle = shuffle, callbacks = [es, cp], verbose = verbose)
# print and/or save a performance plot
self.__plot_keras_history(history = history, metric = 'mse', #metric = 'root_mean_squared_error',
model_name = __MODEL_NAME, feature_name = feature_name, file_name = __history_plot_file,
verbose = verbose)
# save the model, parameters, and performance history
model_json = parallel_model.to_json()
with open(__model_json_file, "w") as json_file:
json_file.write(model_json)
hist_params = pd.DataFrame(history.params)
hist_params.to_csv(__history_params_file)
hist = pd.DataFrame(history.history)
hist.to_csv(__history_performance_file)
if verbose: print("Model JSON, history, and parameters file saved.")
# save a plot of the model architecture
plot_model(parallel_model, to_file = __model_architecture_plot_file, rankdir = 'TB',
show_shapes = True, show_layer_names = True, expand_nested = True, dpi=300)
else:
if verbose: print("Loading history and params files for '%s' MODEL..." % feature_name)
hist_params = pd.read_csv(__history_params_file)
hist = pd.read_csv(__history_performance_file)
if verbose: print("Loading pickle file for '%s' MODEL from file '%s'" % (feature_name, __model_file_name))
parallel_model = self.__load_keras_model(__MODEL_NAME, __model_file_name, __model_json_file, verbose = verbose)
return parallel_model, hist_params, hist
# inferencing
def predict_keras_kaggle1(self, X, feature_name = "unknown", full = True, verbose = False):
__MODEL_NAME = "Keras - Kaggle1"
__MODEL_FNAME_PREFIX = "KERAS_KAGGLE1/"
if full:
__MODEL_SUFFIX = "_30"
else:
__MODEL_SUFFIX = "_8"
nested_dir = "".join([self.__models_path,__MODEL_FNAME_PREFIX])
if not os.path.exists(nested_dir):
raise RuntimeError("Model path '%s' does not exist; exiting inferencing." % nested_dir)
__model_file_name = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".h5"])
__model_json_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".json"])
##__scaler_file = "".join([nested_dir, feature_name, "_scaler.pkl"])
if (not os.path.isfile(__model_file_name)) or (not os.path.isfile(__model_json_file)):## or (not os.path.isfile(__scaler_file)):
raise RuntimeError("One or some of the following files are missing; prediction cancelled:\n\n'%s'\n'%s'\n" % ##'%s'\n" %
(__model_file_name, __model_json_file))##, __scaler_file))
# Load the training scaler for this model
##if verbose: print("Loading SCALER for '%s' and zero-centering X." % feature_name)
##scaler = pickle.load(open(__scaler_file, "rb"))
##X = self.__4d_Scaler(arr = X, ss = scaler, fit = False, verbose = verbose)
# load the Keras model for the specified feature
model = self.__load_keras_model(__MODEL_NAME, __model_file_name, __model_json_file, verbose = verbose)
# predict
if verbose: print("Predicting %d (x,y) coordinates for '%s'..." % (len(X), feature_name))
Y = model.predict(X, verbose = verbose)
if verbose: print("Predictions completed!")
return Y
#-------------------------------------------------------------
# LeNet5 Model
# Inspired by: Google's LeNet5 for MNSIST - Modified
#-------------------------------------------------------------
def get_keras_lenet5(self, X, Y, batch_size, epoch_count, X_val = None, Y_val = None, val_split = 0.1, shuffle = True,
feature_name = "ALL_FEATURES", recalculate_pickle = True, full = True, verbose = False):
__MODEL_NAME = "Keras - LeNet5"
__MODEL_FNAME_PREFIX = "KERAS_LENET5/"
if full:
__MODEL_SUFFIX = "_30"
else:
__MODEL_SUFFIX = "_8"
nested_dir = "".join([self.__models_path,__MODEL_FNAME_PREFIX])
if not os.path.exists(nested_dir):
os.makedirs(nested_dir)
__model_file_name = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".h5"])
__model_json_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, ".json"])
__model_architecture_plot_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_model_plot.png"])
__history_params_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_params.csv"])
__history_performance_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_history.csv"])
__history_plot_file = "".join([nested_dir, feature_name, __MODEL_SUFFIX, "_plot.png"])
if verbose: print("Retrieving model: %s..." % "".join([__MODEL_NAME, __MODEL_SUFFIX]))
# Create or load the model
if (not os.path.isfile(__model_file_name)) or (not os.path.isfile(__model_json_file)) or recalculate_pickle:
if verbose: print("Pickle file for '%s' MODEL not found or skipped by caller." % feature_name)
#if (X_val is None) or (Y_val is None):
# if verbose: print("No validation set specified; creating a split based on %.2f val_split parameter." % val_split)
# X, Y, X_val, Y_val = train_test_split(X, Y, test_size = val_split, random_state = 42)
act = Adam(lr = 0.001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-8)
lss = 'mean_squared_error'
mtrc = ['mae','mse']
stop_at = np.max([int(0.1 * epoch_count), self.__MIN_early_stopping])
es = EarlyStopping(patience = stop_at, verbose = verbose)
cp = ModelCheckpoint(filepath = __model_file_name, verbose = verbose, save_best_only = True,
mode = 'min', monitor = 'val_mae')
if self.__GPU_count > 1: dev = "/cpu:0"
else: dev = "/gpu:0"
with tf.device(dev):
model = Sequential()
model.add(Convolution2D(filters = 6, kernel_size = (3, 3), input_shape = (96, 96, 1)))
model.add(ReLU())
# CDB: 3/5 added Batch Normalization
#model.add(BatchNormalization())
model.add(AveragePooling2D())
#model.add(Dropout(0.2))
model.add(Convolution2D(filters = 16, kernel_size = (3, 3)))
model.add(ReLU())
# CDB: 3/5 added Batch Normalization
#model.add(BatchNormalization())
model.add(AveragePooling2D())
#model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(512))
model.add(ReLU())