-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFYP.py
1037 lines (865 loc) · 48 KB
/
FYP.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
# -*- coding: utf-8 -*-
"""Copy of FinalYearProject.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1LOTca0RgNNupwjtwYEqR9EREPs20d2ZZ
"""
!env
!sudo apt-get purge cuda
!sudo apt-get purge libcudnn6
!sudo apt-get purge libcudnn6-dev
!pip uninstall tf-nightly-1.12 --yes
!sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.6 1
!sudo update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.7 2
!update-alternatives --list python3
!sudo update-alternatives --config python3
!ls -l /usr/local/bin/python3 /etc/alternatives/python3
!sudo apt-get install python3-pip
!python3 -m pip install tensorflow==1.12
!python3 -m pip install tensorflow-gpu==1.12
!python3 -m pip uninstall tensorboard-plugin-wit --yes
!python3 -m pip install keras==2.2.4
!sudo apt-get purge cuda
!sudo apt-get purge libcudnn6
!sudo apt-get purge libcudnn6-dev
!wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7-dev_7.0.5.15-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl2_2.1.4-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl-dev_2.1.4-1+cuda9.0_amd64.deb
!sudo dpkg -i cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
!sudo apt-get update
!sudo apt-get install cuda=9.0.176-1
!sudo apt-get install libcudnn7-dev
!sudo apt-get install libnccl-dev
!export PATH=/usr/local/bin:$PATH
!echo $PATH
import sys
sys.path = ['',
'/content',
'/usr/bin/python3.6',
'/usr/bin/python3.7',
'/usr/lib/python36.zip',
'/usr/lib/python37.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/usr/local/lib/python3.7/dist-packages',
'/usr/lib/python3/dist-packages',
'/usr/local/lib/python3.6/dist-packages/IPython/extensions',
'/usr/local/lib/python3.7/dist-packages/IPython/extensions',
'/root/.ipython']
!sudo rm -r /usr/lib/python3.7
!sudo rm -r /usr/local/lib/python3.7
!sudo rm -r /usr/bin/python3.7
!sudo rm -r /usr/bin/python3.7m
!sudo rm -r /usr/bin/python3.7-config
!sudo rm -r /usr/bin/python3.7m-config
!which python # should return /usr/local/bin/python
!python --version
!echo $PYTHONPATH
# Commented out IPython magic to ensure Python compatibility.
# %%bash
# MINICONDA_INSTALLER_SCRIPT=Miniconda3-4.5.4-Linux-x86_64.sh
# MINICONDA_PREFIX=/usr/local
# wget https://repo.continuum.io/miniconda/$MINICONDA_INSTALLER_SCRIPT
# chmod +x $MINICONDA_INSTALLER_SCRIPT
# ./$MINICONDA_INSTALLER_SCRIPT -b -f -p $MINICONDA_PREFIX
!which conda # should return /usr/local/bin/conda
!which python # still returns /usr/local/bin/python
!python --version # now returns Python 3.6.5 :: Anaconda, Inc.
# Commented out IPython magic to ensure Python compatibility.
# %%bash
# conda install --channel defaults conda python=3.6 --yes
# conda update --channel defaults --all --yes
#
!conda --version # now returns 4.8.3
!python --version # now returns Python 3.6.10 :: Anaconda, Inc.
!source ~/.bashrc
!conda init bash
!add-apt-repository ppa:deadsnakes/ppa
!apt-get update
!apt-get install python3.6
!apt-get install python3.6-dev
!wget https://bootstrap.pypa.io/get-pip.py && python3.6 get-pip.py
import sys
sys.path[3]='/usr/local/lib/python36.zip'
sys.path[4]='/usr/local/lib/python3.6'
sys.path[5]='/usr/local/lib/python3.6/lib-dynload'
sys.path[6]='/usr/local/lib/python3.6/dist-packages'
sys.path[8]='/usr/local/lib/python3.6/dist-packages/IPython/extensions'
import tensorflow as tf
print(tf.__version__)
!python --version
!pip install tensorflow==1.13.1
!pip install keras==2.2.4
!sudo apt-get purge cuda
!sudo apt-get purge libcudnn6
!sudo apt-get purge libcudnn6-dev
!wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7-dev_7.0.5.15-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl2_2.1.4-1+cuda9.0_amd64.deb
!wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libnccl-dev_2.1.4-1+cuda9.0_amd64.deb
!sudo dpkg -i cuda-repo-ubuntu1604_9.0.176-1_amd64.deb
!sudo apt-get update
!sudo apt-get install cuda=9.0.176-1
!sudo apt-get install libcudnn7-dev
!sudo apt-get install libnccl-dev
!export PATH=/usr/local/cuda-9.0/bin${PATH:+:${PATH}}
!export LD_LIBRARY_PATH=/usr/local/cuda-9.0/lib64${LD_LIBRARY_PATH:+:${LD_LIBRARY_PATH}}
!sudo cp /usr/include/cudnn.h /usr/local/cuda/include
!conda install h5py
!pip show keras
vi ~/.bash_profile
alias python='/usr/local/bin/python3'
import sys
sys.path = ['',
'/env/python',
'/usr/lib/python36.zip',
'/usr/lib/python3.6',
'/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', # pre-installed packages
'/usr/lib/python3/dist-packages',
'/usr/local/lib/python3.6/dist-packages/IPython/extensions',
'/root/.ipython']
_ = (sys.path.append("/usr/local/lib/python3.6/site-packages"))
!conda install --channel conda-forge featuretools --yes
!pip uninstall scipy --yes
!conda update numpy scipy matplotlib ipython jupyter pandas sympy nose
!python -m pip install numpy scipy matplotlib ipython jupyter pandas sympy nose
import tensorflow as tf
!python3 -c 'import keras; print(keras.__version__)'
print(tf.__version__)
tf.enable_eager_execution()
tf.executing_eagerly()
!sudo apt-get install python-pip
from google.colab import drive
drive.mount('/content/drive')
!python3 -m pip install sklearn
!apt install python3-setuptools
!sudo apt-get install –f
import matplotlib.pyplot as plt
import os
import cv2
from google.colab import files
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.utils import class_weight
from sklearn.utils.class_weight import compute_class_weight
from sklearn.metrics import roc_auc_score
from sklearn.metrics import roc_curve, auc
from itertools import cycle
from scipy import interp
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from time import time
files.upload()
!mkdir -p ~/.kaggle
!cp kaggle.json ~/.kaggle/
#change the permission
!chmod 600 ~/.kaggle/kaggle.json
!kaggle competitions download -c aptos2019-blindness-detection
# Only run it when the dataset in not preprocessed
# This function subtracts from each color, the local average color. (Color Normalization)
def load_ben_color(image):
sigmaX=10
image=cv2.addWeighted (image,4, cv2.GaussianBlur( image , (0, 0) , sigmaX) ,-4 ,128)
return image
!unzip "/content/drive/My Drive/mixed" -d "/tmp/"
train_dir = '/tmp/train'
val_test_dir = '/tmp/test'
train_datagen = ImageDataGenerator(
rescale = 1.0/255.,
horizontal_flip = True,
vertical_flip = True,
rotation_range = 40,
fill_mode = 'constant',
zoom_range = 0.15,
cval = 0.,
width_shift_range = 0.1,
height_shift_range = 0.1,
preprocessing_function = load_ben_color
)
val_test_datagen = ImageDataGenerator(
rescale = 1.0/255.)
bs = 64
training_generator = train_datagen.flow_from_directory(
train_dir,
batch_size = bs,
target_size = (256, 256),
shuffle = True,
seed = 40,
classes = ['0', '1', '2', '3', '4'],
class_mode = 'categorical'
)
validation_generator = val_test_datagen.flow_from_directory(
val_test_dir,
batch_size = bs,
target_size = (256, 256),
shuffle = True,
seed = 40,
classes = ['0', '1', '2', '3', '4'],
class_mode = 'categorical'
)
testing_generator = val_test_datagen.flow_from_directory(
val_test_dir,
batch_size = 1060,
target_size = (256, 256),
shuffle = True,
seed = 40,
classes = ['0', '1', '2', '3', '4'],
class_mode = 'categorical'
)
train = pd.read_csv("/tmp/train_Labels.csv", dtype=str)
print("<------------------Training Data----------------------->")
train['image_name'] = [i+".png" for i in train['image'].values]
print(str(train['level'].hist())) # display histogram
print(str(train['level'].value_counts())) # display counts
test = pd.read_csv("/tmp/test_Labels.csv", dtype=str)
print("<------------------validation/Test Data---------------->")
test['image_name'] = [i+".png" for i in test['image'].values]
print(str(test['level'].hist())) # display histogram
print(str(test['level'].value_counts())) # display counts
def load_ben_color(image):
IMG_SIZE = 256
sigmaX=4
image=cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0, 0) , sigmaX) ,-4 ,128)
return image
train_dir = '/tmp/train'
test_dir = '/tmp/test'
train_data_gen = ImageDataGenerator(
rescale=1/255.,
rotation_range = 110,
zoom_range=0.1,
fill_mode='nearest',
horizontal_flip=True,
vertical_flip=True,
preprocessing_function = load_ben_color
)
validation_data_gen = ImageDataGenerator(
rescale = 1.0/255.
)
bs = 32
training_generator = train_data_gen.flow_from_dataframe(
train, # labels
train_dir, # directory of the images
x_col="image_name", # name of the images with extension
y_col="level", # labels
class_mode="categorical", # inferred from the labels
batch_size = bs,
shuffle = True,
seed = 42,
target_size=(256, 256)
)
validation_generator = validation_data_gen.flow_from_dataframe(
test, # labels
test_dir, # directory of the images
x_col="image_name", # name of the images with extension
y_col="level", # inferred from the labels
class_mode="categorical",
batch_size=bs,
shuffle = True,
seed = 42,
target_size=(256, 256)
)
testing_generator = validation_data_gen.flow_from_dataframe(
test, # labels
test_dir, # directory of the images
x_col="image_name", # name of the images with extension
y_col="level", # inferred from the labels
class_mode="categorical",
batch_size=1000,
shuffle = True,
seed = 42,
target_size=(256, 256)
)
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced',
np.unique(training_generator.classes),
training_generator.classes)
class_weights = dict(enumerate(class_weights))
print(str(class_weights))
def IResNet_module(input, layercount):
n = layercount
############################################################################
# Parallel Block 1
x1_1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu', padding = 'same')(input)
x1_1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu', padding = 'same')(x1_1)
x1_1 = tf.keras.layers.BatchNormalization()(x1_1)
############################################################################
# Parallel Block 2
x2_1 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu', padding = 'same')(input)
x2_1 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu', padding = 'same')(x2_1)
x2_1 = tf.keras.layers.BatchNormalization()(x2_1)
############################################################################
# Parallel Block 1
x1_2 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu', padding = 'same')(x1_1)
x1_2 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu', padding = 'same')(x1_1)
x1_2 = tf.keras.layers.BatchNormalization()(x1_2)
x1 = tf.keras.layers.add([x1_1, x1_2, x2_1])
############################################################################
# Parallel Block 2
x2_2 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu', padding = 'same')(x2_1)
x2_2 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu', padding = 'same')(x2_1)
x2_2 = tf.keras.layers.BatchNormalization()(x2_2)
x2 = tf.keras.layers.add([x2_1, x2_2, x1_1])
mod = tf.keras.layers.concatenate([x1, x2], axis = -1)
return mod
def IResNet_reduction_module(input, layercount):
n = layercount
############################################################################
# Reduction module
R1 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu')(input)
R1 = tf.keras.layers.Conv2D(n, (1, 1), activation = 'relu')(R1)
R1 = tf.keras.layers.BatchNormalization()(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
R1 = tf.keras.layers.BatchNormalization()(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
R1 = tf.keras.layers.Conv2D(n, (3, 3), activation = 'relu')(R1)
mod = tf.keras.layers.MaxPooling2D(2, 2)(R1)
mod = tf.keras.layers.BatchNormalization()(mod)
return mod
def IResNet_dense(input):
############################################################################
y = tf.keras.layers.GlobalAveragePooling2D()(input)
y = tf.keras.layers.Flatten()(y)
y = tf.keras.layers.Dense(1024, activation = 'relu', kernel_regularizer='l2')(y)
y = tf.keras.layers.Dropout(0.5)(y)
y = tf.keras.layers.Dense(512, activation = 'relu', kernel_regularizer='l2')(y)
y = tf.keras.layers.Dropout(0.5)(y)
y = tf.keras.layers.Dense(5, activation = 'softmax')(y)
return y
# Defining Model Architecture
strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0")
with strategy.scope():
img_inputs = tf.keras.layers.Input(shape=(256, 256, 3))
module_1 = IResNet_module(img_inputs, 32)
module_2 = IResNet_module(module_1, 32)
red_1 = IResNet_reduction_module(module_2, 32)
module_3 = IResNet_module(red_1, 64)
module_4 = IResNet_module(module_3, 64)
red_3 = IResNet_reduction_module(module_4, 64)
module_5 = IResNet_module(red_3, 128)
module_6 = IResNet_module(module_5, 128)
red_4 = IResNet_reduction_module(module_6, 128)
module_7 = IResNet_module(red_4, 128)
red_5 = IResNet_reduction_module(module_7, 512)
y = IResNet_dense(red_5)
model = tf.keras.models.Model(inputs=img_inputs, outputs=y, name = "IResNetv3")
model.compile(
optimizer=tf.keras.optimizers.Adam(),
loss=tf.keras.losses.CategoricalCrossentropy(),
metrics=[tf.keras.metrics.CategoricalAccuracy(),
tf.keras.metrics.AUC(num_thresholds = 50, curve = 'ROC', name = 'auc', summation_method = 'interpolation')],
)
!pip install keras==2.2.0
model.summary()
tf.keras.utils.plot_model(model)
!python3 -c 'from tensorflow.keras.applications import ResNet50'
!python3 -c 'from tensorflow.keras.models import Sequential'
def get_compiled_model():
base_model = ResNet50(weights = "imagenet", include_top=False, input_shape=(256,256,3))
base_model.trainable = True
for layer in base_model.layers[:35]:
layer.trainable = False
model = Sequential([
base_model,
tf.keras.layers.MaxPool2D(),
tf.keras.layers.MaxPool2D(),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(5, activation='softmax')
])
return model
model = get_compiled_model()
model.summary()
model.save('/tmp/resnet50reshape.h5')
model = tf.keras.models.load_model('best_model_resnet50_tf_1.12.hdf5')
print(model.input)
print(model.output)
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
import os.path as osp
#model = load_model('/content/drive/My Drive/Colab Notebooks/Transfer Learning experiments/best model/resnet50 tf 1.12.hdf5')
#nb_classes = 5 # The number of output nodes in the model
#prefix_output_node_names_of_final_network = 'output_node'
K.set_learning_phase(0)
sess = K.get_session()
output_fld = '/tmp/frozen_graph'
if not os.path.isdir(output_fld):
os.mkdir(output_fld)
output_graph_name = '/tmp/frozen_graph/Frozen_ResNetAVG' + '.pb'
output_graph_suffix = '_inference'
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(),['Softmax_1'] )
graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
import os.path as osp
#model = load_model('/content/drive/My Drive/Colab Notebooks/Transfer Learning experiments/best model/resnet50 tf 1.12.hdf5')
#nb_classes = 5 # The number of output nodes in the model
#prefix_output_node_names_of_final_network = 'output_node'
K.set_learning_phase(0)
sess = K.get_session()
output_fld = '/tmp/frozen_graph'
if not os.path.isdir(output_fld):
os.mkdir(output_fld)
output_graph_name = '/tmp/frozen_graph/Frozen_ResNetAVG' + '.pb'
output_graph_suffix = '_inference'
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(),['dense/Identity'] )
graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))
# Commented out IPython magic to ensure Python compatibility.
# %reload_ext tensorboard
# define a callback class for early stopping
class myCallback_EarlyStopping(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs = {}):
X, y = testing_generator.next()
y_pred = model.predict(X)
print("Displaying Normalized Confusion Matrix...")
confusion_matrix(y, y_pred, 'normalize')
print("Displaying Simple Confusion Matrix...")
confusion_matrix(y, y_pred, 'none')
print("Plotting ROC curve...")
roc = roc_auc(y,y_pred)
model.save('/content/drive/My Drive/MobileNetv2_7.h5', overwrite = True)
if (roc['macro']>0.90):
print("\n Validation Macro AUC of 90% has reached!")
model.save('/content/drive/My Drive/Best_Macro_MobileNetv2.h5', overwrite = True)
self.model.stop_training = True
elif (roc['micro']>0.92):
print("\n Validation Micro AUC of 92% has reached!")
model.save('/content/drive/My Drive/Best_Micro_MobileNetv2.h5', overwrite = True)
self.model.stop_training = True
callback_EarlyStopping = myCallback_EarlyStopping()
# Callback for tensorboard to update data after every epoch
tensorboard = tf.keras.callbacks.TensorBoard(log_dir='/content/drive/My Drive/TensorBoardLogs/MobileNetv2_7_logs/{}'.format(time()))
# Callback to reduce learning rate when the validation loss is experiencing no furter reduction
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.89,
patience=5, min_lr=0.00001, verbose = 1)
# Callback for saving model at each checkpoint during training
model_checkpoint = tf.keras.callbacks.ModelCheckpoint(
filepath="/content/drive/My Drive/ModelCheckPoints/checkpoint/MobileNetv2_7.hdf5",
monitor='val_acc',
mode='max',
save_best_only=True)
# Save the data per epoch into a CSV file
csv_logger = tf.keras.callbacks.CSVLogger('/content/drive/My Drive/MobileNetv2_7_TrainingData.csv', separator=",", append=True)
def confusion_matrix(y_test, y_pred, *args):
y_pred_L = np.argmax(y_pred, axis=1)
y_test_L = np.argmax(y_test, axis=1)
for arg in args:
if arg == 'normalize':
cn = sklearn.metrics.confusion_matrix(y_test_L, y_pred_L, normalize = 'all')
df_cm = pd.DataFrame(cn, range(5), range(5))
plt.figure(figsize=(14, 7))
sn.set(font_scale=1) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 12}) # font size
plt.show()
elif arg == 'none':
cn = sklearn.metrics.confusion_matrix(y_test_L, y_pred_L)
df_cm = pd.DataFrame(cn, range(5), range(5))
plt.figure(figsize=(14, 7))
sn.set(font_scale=1) # for label size
sn.heatmap(df_cm, annot=True, annot_kws={"size": 12}, fmt = 'd') # font size
plt.show()
def roc_auc(y_test, y_pred):
# Compute ROC curve and ROC area for each class
lw = 2
fpr = dict()
tpr = dict()
roc_auc = dict()
n_classes = 5
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_pred[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_pred.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
mean_tpr += interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
# Plot all ROC curves
plt.figure()
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
colors = cycle(['aqua', 'darkorange', 'cornflowerblue', 'purple', 'red'])
for i, color in zip(range(n_classes), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()
return roc_auc
X, y = testing_generator.next()
y_pred = model.predict(X)
confusion_matrix(y,y_pred)
roc_auc(y,y_pred)
confusion_matrix(y,y_pred, 'none')
print("Displaying Normalized Confusion Matrix...")
confusion_matrix(y, y_pred, 'normalize')
print("Displaying Simple Confusion Matrix...")
confusion_matrix(y, y_pred, 'none')
print("Plotting ROC curve...")
roc = roc_auc(y,y_pred)
model.load_weights('/content/drive/My Drive/MobileNetv2_4.h5')
for layer in model.layers[0].layers[10:70]:
layer.trainable = True
model.compile(
optimizer=tf.train.AdamOptimizer(learning_rate = 0.0001),
loss=['categorical_crossentropy'],
metrics=['accuracy']
)
# Commented out IPython magic to ensure Python compatibility.
# %tensorboard --logdir '/content/drive/My Drive/TensorBoardLogs/MobileNetv2_logs'
model.fit_generator(training_generator, epochs=250, validation_data=validation_generator, verbose = 1,
callbacks = [callback_EarlyStopping, tensorboard, model_checkpoint, csv_logger], class_weight = class_weights)
from tensorflow.python.framework import graph_util
from tensorflow.python.framework import graph_io
from tensorflow.keras.models import load_model
from tensorflow.keras import backend as K
import os.path as osp
#model = load_model('/content/drive/My Drive/Colab Notebooks/Transfer Learning experiments/best model/resnet50 tf 1.12.hdf5')
#nb_classes = 5 # The number of output nodes in the model
#prefix_output_node_names_of_final_network = 'output_node'
K.set_learning_phase(0)
sess = K.get_session()
output_fld = '/content/drive/My Drive/frozen_graph_mobilenetv2'
if not os.path.isdir(output_fld):
os.mkdir(output_fld)
output_graph_name = '/content/drive/My Drive/frozen_graph/Frozen_InceptionV3' + '.pb'
output_graph_suffix = '_inference'
constant_graph = graph_util.convert_variables_to_constants(sess, sess.graph.as_graph_def(),['dense_3/Softmax'] )
graph_io.write_graph(constant_graph, output_fld, output_graph_name, as_text=False)
print('saved the constant graph (ready for inference) at: ', osp.join(output_fld, output_graph_name))
!pip show tensorflow
from matplotlib import pyplot as plt
import math
from tensorflow.keras.callbacks import LambdaCallback
import tensorflow.keras.backend as K
import numpy as np
class LRFinder:
"""
Plots the change of the loss function of a Keras model when the learning rate is exponentially increasing.
See for details:
https://towardsdatascience.com/estimating-optimal-learning-rate-for-a-deep-neural-network-ce32f2556ce0
"""
def __init__(self, model):
self.model = model
self.losses = []
self.lrs = []
self.best_loss = 1e9
def on_batch_end(self, batch, logs):
# Log the learning rate
lr = K.get_value(self.model.optimizer.learning_rate)
self.lrs.append(lr)
# Log the loss
loss = logs['loss']
self.losses.append(loss)
# Check whether the loss got too large or NaN
if batch > 5 and (math.isnan(loss) or loss > self.best_loss * 4):
self.model.stop_training = True
return
if loss < self.best_loss:
self.best_loss = loss
# Increase the learning rate for the next batch
lr *= self.lr_mult
K.set_value(self.model.optimizer.learning_rate, lr)
def find(self, x_train, y_train, start_lr, end_lr, batch_size=64, epochs=1):
# If x_train contains data for multiple inputs, use length of the first input.
# Assumption: the first element in the list is single input; NOT a list of inputs.
N = x_train[0].shape[0] if isinstance(x_train, list) else x_train.shape[0]
# Compute number of batches and LR multiplier
num_batches = epochs * N / batch_size
self.lr_mult = (float(end_lr) / float(start_lr)) ** (float(1) / float(num_batches))
# Save weights into a file
self.model.save_weights('tmp.h5')
# Remember the original learning rate
original_lr = K.get_value(self.model.optimizer.learning_rate)
# Set the initial learning rate
K.set_value(self.model.optimizer.learning_rate, start_lr)
callback = LambdaCallback(on_batch_end=lambda batch, logs: self.on_batch_end(batch, logs))
self.model.fit(x_train, y_train,
batch_size=batch_size, epochs=epochs,
callbacks=[callback])
# Restore the weights to the state before model fitting
self.model.load_weights('tmp.h5')
# Restore the original learning rate
K.set_value(self.model.optimizer.learning_rate, original_lr)
def find_generator(self, generator, start_lr, end_lr, epochs=1, steps_per_epoch=None, **kw_fit):
if steps_per_epoch is None:
try:
steps_per_epoch = len(generator)
except (ValueError, NotImplementedError) as e:
raise e('`steps_per_epoch=None` is only valid for a'
' generator based on the '
'`keras.utils.Sequence`'
' class. Please specify `steps_per_epoch` '
'or use the `keras.utils.Sequence` class.')
self.lr_mult = (float(end_lr) / float(start_lr)) ** (float(1) / float(epochs * steps_per_epoch))
# Save weights into a file
self.model.save_weights('tmp.h5')
# Remember the original learning rate
original_lr = K.get_value(self.model.optimizer.learning_rate)
# Set the initial learning rate
K.set_value(self.model.optimizer.learning_rate, start_lr)
callback = LambdaCallback(on_batch_end=lambda batch,
logs: self.on_batch_end(batch, logs))
self.model.fit_generator(generator=generator,
epochs=epochs,
steps_per_epoch=steps_per_epoch,
callbacks=[callback],
**kw_fit)
# Restore the weights to the state before model fitting
self.model.load_weights('tmp.h5')
# Restore the original learning rate
K.set_value(self.model.optimizer.learning_rate, original_lr)
def plot_loss(self, n_skip_beginning=10, n_skip_end=5, x_scale='log'):
"""
Plots the loss.
Parameters:
n_skip_beginning - number of batches to skip on the left.
n_skip_end - number of batches to skip on the right.
"""
plt.ylabel("loss")
plt.xlabel("learning rate (log scale)")
plt.plot(self.lrs[n_skip_beginning:-n_skip_end], self.losses[n_skip_beginning:-n_skip_end])
plt.xscale(x_scale)
plt.show()
def plot_loss_change(self, sma=1, n_skip_beginning=10, n_skip_end=5, y_lim=(-0.01, 0.01)):
"""
Plots rate of change of the loss function.
Parameters:
sma - number of batches for simple moving average to smooth out the curve.
n_skip_beginning - number of batches to skip on the left.
n_skip_end - number of batches to skip on the right.
y_lim - limits for the y axis.
"""
derivatives = self.get_derivatives(sma)[n_skip_beginning:-n_skip_end]
lrs = self.lrs[n_skip_beginning:-n_skip_end]
plt.ylabel("rate of loss change")
plt.xlabel("learning rate (log scale)")
plt.plot(lrs, derivatives)
plt.xscale('log')
plt.ylim(y_lim)
plt.show()
def get_derivatives(self, sma):
assert sma >= 1
derivatives = [0] * sma
for i in range(sma, len(self.lrs)):
derivatives.append((self.losses[i] - self.losses[i - sma]) / sma)
return derivatives
def get_best_lr(self, sma, n_skip_beginning=10, n_skip_end=5):
derivatives = self.get_derivatives(sma)
best_der_idx = np.argmax(derivatives[n_skip_beginning:-n_skip_end])[0]
return self.lrs[n_skip_beginning:-n_skip_end][best_der_idx]
lr_finder = LRFinder(model)
lr_finder.find_generator(training_generator, 0.00001, 0.01, 3, 55)
lr_finder.plot_loss()
lr_finder.plot_loss_change(sma=20, n_skip_beginning=20, n_skip_end=5, y_lim=(-0.02, 0.1))
from __future__ import print_function
import imageio
from PIL import Image
import numpy as np
import keras
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, AveragePooling2D, ZeroPadding2D, Dropout, Flatten, Concatenate, Reshape, Activation
from keras.models import Model
from keras.regularizers import l2
from keras.optimizers import SGD
from pool_helper import PoolHelper
from lrn import LRN
if keras.backend.backend() == 'tensorflow':
from keras import backend as K
import tensorflow as tf
from keras.utils.conv_utils import convert_kernel
def create_googlenet(weights_path=None):
# creates GoogLeNet a.k.a. Inception v1 (Szegedy, 2015)
input = Input(shape=(3, 224, 224))
input_pad = ZeroPadding2D(padding=(3, 3))(input)
conv1_7x7_s2 = Conv2D(64, (7,7), strides=(2,2), padding='valid', activation='relu', name='conv1/7x7_s2', kernel_regularizer=l2(0.0002))(input_pad)
conv1_zero_pad = ZeroPadding2D(padding=(1, 1))(conv1_7x7_s2)
pool1_helper = PoolHelper()(conv1_zero_pad)
pool1_3x3_s2 = MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid', name='pool1/3x3_s2')(pool1_helper)
pool1_norm1 = LRN(name='pool1/norm1')(pool1_3x3_s2)
conv2_3x3_reduce = Conv2D(64, (1,1), padding='same', activation='relu', name='conv2/3x3_reduce', kernel_regularizer=l2(0.0002))(pool1_norm1)
conv2_3x3 = Conv2D(192, (3,3), padding='same', activation='relu', name='conv2/3x3', kernel_regularizer=l2(0.0002))(conv2_3x3_reduce)
conv2_norm2 = LRN(name='conv2/norm2')(conv2_3x3)
conv2_zero_pad = ZeroPadding2D(padding=(1, 1))(conv2_norm2)
pool2_helper = PoolHelper()(conv2_zero_pad)
pool2_3x3_s2 = MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid', name='pool2/3x3_s2')(pool2_helper)
inception_3a_1x1 = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_3a/1x1', kernel_regularizer=l2(0.0002))(pool2_3x3_s2)
inception_3a_3x3_reduce = Conv2D(96, (1,1), padding='same', activation='relu', name='inception_3a/3x3_reduce', kernel_regularizer=l2(0.0002))(pool2_3x3_s2)
inception_3a_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_3a_3x3_reduce)
inception_3a_3x3 = Conv2D(128, (3,3), padding='valid', activation='relu', name='inception_3a/3x3', kernel_regularizer=l2(0.0002))(inception_3a_3x3_pad)
inception_3a_5x5_reduce = Conv2D(16, (1,1), padding='same', activation='relu', name='inception_3a/5x5_reduce', kernel_regularizer=l2(0.0002))(pool2_3x3_s2)
inception_3a_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_3a_5x5_reduce)
inception_3a_5x5 = Conv2D(32, (5,5), padding='valid', activation='relu', name='inception_3a/5x5', kernel_regularizer=l2(0.0002))(inception_3a_5x5_pad)
inception_3a_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_3a/pool')(pool2_3x3_s2)
inception_3a_pool_proj = Conv2D(32, (1,1), padding='same', activation='relu', name='inception_3a/pool_proj', kernel_regularizer=l2(0.0002))(inception_3a_pool)
inception_3a_output = Concatenate(axis=1, name='inception_3a/output')([inception_3a_1x1,inception_3a_3x3,inception_3a_5x5,inception_3a_pool_proj])
inception_3b_1x1 = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_3b/1x1', kernel_regularizer=l2(0.0002))(inception_3a_output)
inception_3b_3x3_reduce = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_3b/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_3a_output)
inception_3b_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_3b_3x3_reduce)
inception_3b_3x3 = Conv2D(192, (3,3), padding='valid', activation='relu', name='inception_3b/3x3', kernel_regularizer=l2(0.0002))(inception_3b_3x3_pad)
inception_3b_5x5_reduce = Conv2D(32, (1,1), padding='same', activation='relu', name='inception_3b/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_3a_output)
inception_3b_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_3b_5x5_reduce)
inception_3b_5x5 = Conv2D(96, (5,5), padding='valid', activation='relu', name='inception_3b/5x5', kernel_regularizer=l2(0.0002))(inception_3b_5x5_pad)
inception_3b_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_3b/pool')(inception_3a_output)
inception_3b_pool_proj = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_3b/pool_proj', kernel_regularizer=l2(0.0002))(inception_3b_pool)
inception_3b_output = Concatenate(axis=1, name='inception_3b/output')([inception_3b_1x1,inception_3b_3x3,inception_3b_5x5,inception_3b_pool_proj])
inception_3b_output_zero_pad = ZeroPadding2D(padding=(1, 1))(inception_3b_output)
pool3_helper = PoolHelper()(inception_3b_output_zero_pad)
pool3_3x3_s2 = MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid', name='pool3/3x3_s2')(pool3_helper)
inception_4a_1x1 = Conv2D(192, (1,1), padding='same', activation='relu', name='inception_4a/1x1', kernel_regularizer=l2(0.0002))(pool3_3x3_s2)
inception_4a_3x3_reduce = Conv2D(96, (1,1), padding='same', activation='relu', name='inception_4a/3x3_reduce', kernel_regularizer=l2(0.0002))(pool3_3x3_s2)
inception_4a_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_4a_3x3_reduce)
inception_4a_3x3 = Conv2D(208, (3,3), padding='valid', activation='relu', name='inception_4a/3x3' ,kernel_regularizer=l2(0.0002))(inception_4a_3x3_pad)
inception_4a_5x5_reduce = Conv2D(16, (1,1), padding='same', activation='relu', name='inception_4a/5x5_reduce', kernel_regularizer=l2(0.0002))(pool3_3x3_s2)
inception_4a_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_4a_5x5_reduce)
inception_4a_5x5 = Conv2D(48, (5,5), padding='valid', activation='relu', name='inception_4a/5x5', kernel_regularizer=l2(0.0002))(inception_4a_5x5_pad)
inception_4a_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_4a/pool')(pool3_3x3_s2)
inception_4a_pool_proj = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_4a/pool_proj', kernel_regularizer=l2(0.0002))(inception_4a_pool)
inception_4a_output = Concatenate(axis=1, name='inception_4a/output')([inception_4a_1x1,inception_4a_3x3,inception_4a_5x5,inception_4a_pool_proj])
loss1_ave_pool = AveragePooling2D(pool_size=(5,5), strides=(3,3), name='loss1/ave_pool')(inception_4a_output)
loss1_conv = Conv2D(128, (1,1), padding='same', activation='relu', name='loss1/conv', kernel_regularizer=l2(0.0002))(loss1_ave_pool)
loss1_flat = Flatten()(loss1_conv)
loss1_fc = Dense(1024, activation='relu', name='loss1/fc', kernel_regularizer=l2(0.0002))(loss1_flat)
loss1_drop_fc = Dropout(rate=0.7)(loss1_fc)
loss1_classifier = Dense(1000, name='loss1/classifier', kernel_regularizer=l2(0.0002))(loss1_drop_fc)
loss1_classifier_act = Activation('softmax')(loss1_classifier)
inception_4b_1x1 = Conv2D(160, (1,1), padding='same', activation='relu', name='inception_4b/1x1', kernel_regularizer=l2(0.0002))(inception_4a_output)
inception_4b_3x3_reduce = Conv2D(112, (1,1), padding='same', activation='relu', name='inception_4b/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_4a_output)
inception_4b_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_4b_3x3_reduce)
inception_4b_3x3 = Conv2D(224, (3,3), padding='valid', activation='relu', name='inception_4b/3x3', kernel_regularizer=l2(0.0002))(inception_4b_3x3_pad)
inception_4b_5x5_reduce = Conv2D(24, (1,1), padding='same', activation='relu', name='inception_4b/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_4a_output)
inception_4b_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_4b_5x5_reduce)
inception_4b_5x5 = Conv2D(64, (5,5), padding='valid', activation='relu', name='inception_4b/5x5', kernel_regularizer=l2(0.0002))(inception_4b_5x5_pad)
inception_4b_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_4b/pool')(inception_4a_output)
inception_4b_pool_proj = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_4b/pool_proj', kernel_regularizer=l2(0.0002))(inception_4b_pool)
inception_4b_output = Concatenate(axis=1, name='inception_4b/output')([inception_4b_1x1,inception_4b_3x3,inception_4b_5x5,inception_4b_pool_proj])
inception_4c_1x1 = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_4c/1x1', kernel_regularizer=l2(0.0002))(inception_4b_output)
inception_4c_3x3_reduce = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_4c/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_4b_output)
inception_4c_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_4c_3x3_reduce)
inception_4c_3x3 = Conv2D(256, (3,3), padding='valid', activation='relu', name='inception_4c/3x3', kernel_regularizer=l2(0.0002))(inception_4c_3x3_pad)
inception_4c_5x5_reduce = Conv2D(24, (1,1), padding='same', activation='relu', name='inception_4c/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_4b_output)
inception_4c_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_4c_5x5_reduce)
inception_4c_5x5 = Conv2D(64, (5,5), padding='valid', activation='relu', name='inception_4c/5x5', kernel_regularizer=l2(0.0002))(inception_4c_5x5_pad)
inception_4c_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_4c/pool')(inception_4b_output)
inception_4c_pool_proj = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_4c/pool_proj', kernel_regularizer=l2(0.0002))(inception_4c_pool)
inception_4c_output = Concatenate(axis=1, name='inception_4c/output')([inception_4c_1x1,inception_4c_3x3,inception_4c_5x5,inception_4c_pool_proj])
inception_4d_1x1 = Conv2D(112, (1,1), padding='same', activation='relu', name='inception_4d/1x1', kernel_regularizer=l2(0.0002))(inception_4c_output)
inception_4d_3x3_reduce = Conv2D(144, (1,1), padding='same', activation='relu', name='inception_4d/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_4c_output)
inception_4d_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_4d_3x3_reduce)
inception_4d_3x3 = Conv2D(288, (3,3), padding='valid', activation='relu', name='inception_4d/3x3', kernel_regularizer=l2(0.0002))(inception_4d_3x3_pad)
inception_4d_5x5_reduce = Conv2D(32, (1,1), padding='same', activation='relu', name='inception_4d/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_4c_output)
inception_4d_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_4d_5x5_reduce)
inception_4d_5x5 = Conv2D(64, (5,5), padding='valid', activation='relu', name='inception_4d/5x5', kernel_regularizer=l2(0.0002))(inception_4d_5x5_pad)
inception_4d_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_4d/pool')(inception_4c_output)
inception_4d_pool_proj = Conv2D(64, (1,1), padding='same', activation='relu', name='inception_4d/pool_proj', kernel_regularizer=l2(0.0002))(inception_4d_pool)
inception_4d_output = Concatenate(axis=1, name='inception_4d/output')([inception_4d_1x1,inception_4d_3x3,inception_4d_5x5,inception_4d_pool_proj])
loss2_ave_pool = AveragePooling2D(pool_size=(5,5), strides=(3,3), name='loss2/ave_pool')(inception_4d_output)
loss2_conv = Conv2D(128, (1,1), padding='same', activation='relu', name='loss2/conv', kernel_regularizer=l2(0.0002))(loss2_ave_pool)
loss2_flat = Flatten()(loss2_conv)
loss2_fc = Dense(1024, activation='relu', name='loss2/fc', kernel_regularizer=l2(0.0002))(loss2_flat)
loss2_drop_fc = Dropout(rate=0.7)(loss2_fc)
loss2_classifier = Dense(1000, name='loss2/classifier', kernel_regularizer=l2(0.0002))(loss2_drop_fc)
loss2_classifier_act = Activation('softmax')(loss2_classifier)
inception_4e_1x1 = Conv2D(256, (1,1), padding='same', activation='relu', name='inception_4e/1x1', kernel_regularizer=l2(0.0002))(inception_4d_output)
inception_4e_3x3_reduce = Conv2D(160, (1,1), padding='same', activation='relu', name='inception_4e/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_4d_output)
inception_4e_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_4e_3x3_reduce)
inception_4e_3x3 = Conv2D(320, (3,3), padding='valid', activation='relu', name='inception_4e/3x3', kernel_regularizer=l2(0.0002))(inception_4e_3x3_pad)
inception_4e_5x5_reduce = Conv2D(32, (1,1), padding='same', activation='relu', name='inception_4e/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_4d_output)
inception_4e_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_4e_5x5_reduce)
inception_4e_5x5 = Conv2D(128, (5,5), padding='valid', activation='relu', name='inception_4e/5x5', kernel_regularizer=l2(0.0002))(inception_4e_5x5_pad)
inception_4e_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_4e/pool')(inception_4d_output)
inception_4e_pool_proj = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_4e/pool_proj', kernel_regularizer=l2(0.0002))(inception_4e_pool)
inception_4e_output = Concatenate(axis=1, name='inception_4e/output')([inception_4e_1x1,inception_4e_3x3,inception_4e_5x5,inception_4e_pool_proj])
inception_4e_output_zero_pad = ZeroPadding2D(padding=(1, 1))(inception_4e_output)
pool4_helper = PoolHelper()(inception_4e_output_zero_pad)
pool4_3x3_s2 = MaxPooling2D(pool_size=(3,3), strides=(2,2), padding='valid', name='pool4/3x3_s2')(pool4_helper)
inception_5a_1x1 = Conv2D(256, (1,1), padding='same', activation='relu', name='inception_5a/1x1', kernel_regularizer=l2(0.0002))(pool4_3x3_s2)
inception_5a_3x3_reduce = Conv2D(160, (1,1), padding='same', activation='relu', name='inception_5a/3x3_reduce', kernel_regularizer=l2(0.0002))(pool4_3x3_s2)
inception_5a_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_5a_3x3_reduce)
inception_5a_3x3 = Conv2D(320, (3,3), padding='valid', activation='relu', name='inception_5a/3x3', kernel_regularizer=l2(0.0002))(inception_5a_3x3_pad)
inception_5a_5x5_reduce = Conv2D(32, (1,1), padding='same', activation='relu', name='inception_5a/5x5_reduce', kernel_regularizer=l2(0.0002))(pool4_3x3_s2)
inception_5a_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_5a_5x5_reduce)
inception_5a_5x5 = Conv2D(128, (5,5), padding='valid', activation='relu', name='inception_5a/5x5', kernel_regularizer=l2(0.0002))(inception_5a_5x5_pad)
inception_5a_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_5a/pool')(pool4_3x3_s2)
inception_5a_pool_proj = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_5a/pool_proj', kernel_regularizer=l2(0.0002))(inception_5a_pool)
inception_5a_output = Concatenate(axis=1, name='inception_5a/output')([inception_5a_1x1,inception_5a_3x3,inception_5a_5x5,inception_5a_pool_proj])
inception_5b_1x1 = Conv2D(384, (1,1), padding='same', activation='relu', name='inception_5b/1x1', kernel_regularizer=l2(0.0002))(inception_5a_output)
inception_5b_3x3_reduce = Conv2D(192, (1,1), padding='same', activation='relu', name='inception_5b/3x3_reduce', kernel_regularizer=l2(0.0002))(inception_5a_output)
inception_5b_3x3_pad = ZeroPadding2D(padding=(1, 1))(inception_5b_3x3_reduce)
inception_5b_3x3 = Conv2D(384, (3,3), padding='valid', activation='relu', name='inception_5b/3x3', kernel_regularizer=l2(0.0002))(inception_5b_3x3_pad)
inception_5b_5x5_reduce = Conv2D(48, (1,1), padding='same', activation='relu', name='inception_5b/5x5_reduce', kernel_regularizer=l2(0.0002))(inception_5a_output)
inception_5b_5x5_pad = ZeroPadding2D(padding=(2, 2))(inception_5b_5x5_reduce)
inception_5b_5x5 = Conv2D(128, (5,5), padding='valid', activation='relu', name='inception_5b/5x5', kernel_regularizer=l2(0.0002))(inception_5b_5x5_pad)
inception_5b_pool = MaxPooling2D(pool_size=(3,3), strides=(1,1), padding='same', name='inception_5b/pool')(inception_5a_output)
inception_5b_pool_proj = Conv2D(128, (1,1), padding='same', activation='relu', name='inception_5b/pool_proj', kernel_regularizer=l2(0.0002))(inception_5b_pool)
inception_5b_output = Concatenate(axis=1, name='inception_5b/output')([inception_5b_1x1,inception_5b_3x3,inception_5b_5x5,inception_5b_pool_proj])
pool5_7x7_s1 = AveragePooling2D(pool_size=(7,7), strides=(1,1), name='pool5/7x7_s2')(inception_5b_output)
loss3_flat = Flatten()(pool5_7x7_s1)
pool5_drop_7x7_s1 = Dropout(rate=0.4)(loss3_flat)
loss3_classifier = Dense(1000, name='loss3/classifier', kernel_regularizer=l2(0.0002))(pool5_drop_7x7_s1)
loss3_classifier_act = Activation('softmax', name='prob')(loss3_classifier)
googlenet = Model(inputs=input, outputs=[loss1_classifier_act,loss2_classifier_act,loss3_classifier_act])