-
Notifications
You must be signed in to change notification settings - Fork 28
/
candidate_1.0.3.02.py
1336 lines (1142 loc) · 48.6 KB
/
candidate_1.0.3.02.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 numpy as np
import os
import wget
from sklearn.model_selection import train_test_split
import tensorflow as tf
from training_utils import download_file, get_batches, read_and_decode_single_example, load_validation_data, \
download_data, evaluate_model, get_training_data, load_weights, flatten, _scale_input_data
import argparse
from tensorboard import summary as summary_lib
# If number of epochs has been passed in use that, otherwise default to 50
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--epochs", help="number of epochs to train", default=30, type=int)
parser.add_argument("-d", "--data", help="which dataset to use", default=9, type=int)
parser.add_argument("-m", "--model", help="model to initialize with", default=None)
parser.add_argument("-l", "--label", help="how to classify data", default="normal")
parser.add_argument("-a", "--action", help="action to perform", default="train")
parser.add_argument("-f", "--freeze", help="whether to freeze convolutional layers", nargs='?', const=True, default=False)
parser.add_argument("-t", "--threshold", help="decision threshold", default=0.4, type=float)
parser.add_argument("-c", "--contrast", help="contrast adjustment, if any", default=0.0, type=float)
parser.add_argument("-w", "--weight", help="weight to give to positive examples in cross-entropy", default=2, type=int)
parser.add_argument("-v", "--version", help="version or run number to assign to model name", default="")
parser.add_argument("--distort", help="use online data augmentation", default=False, const=True, nargs="?")
args = parser.parse_args()
epochs = args.epochs
dataset = args.data
init_model = args.model
how = args.label
action = args.action
threshold = args.threshold
freeze = args.freeze
contrast = args.contrast
weight = args.weight - 1
distort = args.distort
version = args.version
# figure out how to label the model name
if how == "label":
model_label = "l"
elif how == "normal":
model_label = "b"
else:
model_label = "x"
# precalculated pixel mean of images
mu = 104.1353
# download the data
download_data(what=dataset)
## config
batch_size = 32
train_files, total_records = get_training_data(what=dataset)
## Hyperparameters
# Small epsilon value for the BN transform
epsilon = 1e-8
# learning rate
epochs_per_decay = 5
starting_rate = 0.001
decay_factor = 0.85
staircase = True
# learning rate decay variables
steps_per_epoch = int(total_records / batch_size)
print("Steps per epoch:", steps_per_epoch)
# lambdas
lamC = 0.00010
lamF = 0.00200
# use dropout
dropout = True
fcdropout_rate = 0.5
convdropout_rate = 0.01
pooldropout_rate = 0.2
if how == "label":
num_classes = 5
elif how == "normal":
num_classes = 2
elif how == "mass":
num_classes = 3
elif how == "benign":
num_classes = 3
print("Number of classes:", num_classes)
## Build the graph
graph = tf.Graph()
# whether to retrain model from scratch or use saved model
init = True
model_name = "model_s1.0.3.06" + model_label + "." + str(dataset) + str(version)
# 0.0.0.4 - increase pool3 to 3x3 with stride 3
# 0.0.0.6 - reduce pool 3 stride back to 2
# 0.0.0.7 - reduce lambda for l2 reg
# 0.0.0.8 - increase conv1 to 7x7 stride 2
# 0.0.0.9 - disable per image normalization
# 0.0.0.10 - commented out batch norm in conv layers, added conv4 and changed stride of convs to 1, increased FC lambda
# 0.0.0.11 - turn dropout for conv layers on
# 0.0.0.12 - added batch norm after pooling layers, increase pool dropout, decrease conv dropout, added extra conv layer to reduce data dimensionality
# 0.0.0.13 - added precision and f1 summaries
# 0.0.0.14 - fixing batch normalization, I don't think it's going to work after each pool
# 0.0.0.15 - reduced xentropy weighting term
# 0.0.0.17 - replaced initial 5x5 conv layers with 3 3x3 layers
# 0.0.0.18 - changed stride of first conv to 2 from 1
# 0.0.0.19 - doubled units in two fc layers
# 0.0.0.20 - lowered learning rate, put a batch norm back in
# 0.0.0.21 - put all batch norms back in
# 0.0.0.22 - increased lambdaC, removed dropout from conv layers
# 1.0.0.23 - added extra conv layers
# 1.0.0.27 - slowed down learning rate decay
# 1.0.0.28 - increased dropout and regularization to prevent overfitting
# 1.0.0.29 - put learning rate back
# 1.0.0.30 - added a branch to conv1 section
# 1.0.2.01 - added another branch, a concat and a 1x1 conv to downsize layers before conv3
# 1.0.2.02 - removed useless 1x1 conv layer and increased size of subsequent conv layers
# 1.0.3.01 - rerouting branch
# 1.0.3.02 - split extra branch so it also goes back into main branch
# 1.0.3.03 - updated training code to reevaluate the model, fixed other issues with model, added 1x1 convs, increased number of filters
# 1.0.3.05 - added extra conv layer to reduce dimensions of data before fc layers
# 1.0.3.06 - not centering input, just scaling it
with graph.as_default():
training = tf.placeholder(dtype=tf.bool, name="is_training")
is_testing = tf.placeholder(dtype=bool, shape=(), name="is_testing")
# create global step for decaying learning rate
global_step = tf.Variable(0, trainable=False)
learning_rate = tf.train.exponential_decay(starting_rate,
global_step,
steps_per_epoch * epochs_per_decay,
decay_factor,
staircase=staircase)
with tf.name_scope('inputs') as scope:
image, label = read_and_decode_single_example(train_files, label_type=how, normalize=False, distort=distort)
X_def, y_def = tf.train.shuffle_batch([image, label], batch_size=batch_size, capacity=2000,
min_after_dequeue=1000)
# Placeholders
X = tf.placeholder_with_default(X_def, shape=[None, 299, 299, 1])
y = tf.placeholder_with_default(y_def, shape=[None])
# increase the contrast and cast to float
X_adj = _scale_input_data(X, contrast=contrast, mu=0, scale=255.0)
# Convolutional layer 1
with tf.name_scope('conv1') as scope:
conv1 = tf.layers.conv2d(
X_adj, # Input data
filters=64, # 32 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(2, 2), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=100),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1'
)
conv1 = tf.layers.batch_normalization(
conv1,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1'
)
# apply relu
conv1 = tf.nn.relu(conv1, name='relu1')
############################################################
## Branch 1
with tf.name_scope('conv1.0') as scope:
conv11 = tf.layers.conv2d(
conv1, # Input data
filters=32, # 32 filters
kernel_size=(1, 1), # Kernel size: 5x5
strides=(1, 1), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=101),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1.0'
)
conv11 = tf.layers.batch_normalization(
conv11,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1.0'
)
# apply relu
conv11 = tf.nn.relu(conv11, name='relu1.0')
with tf.name_scope('conv1.1') as scope:
conv11 = tf.layers.conv2d(
conv11, # Input data
filters=64, # 32 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=101),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1.1'
)
conv11 = tf.layers.batch_normalization(
conv11,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1.1'
)
# apply relu
conv11 = tf.nn.relu(conv11, name='relu1.1')
with tf.name_scope('conv1.2') as scope:
conv12 = tf.layers.conv2d(
conv11, # Input data
filters=64, # 32 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=1101),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1.2'
)
conv12 = tf.layers.batch_normalization(
conv12,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1.2'
)
# apply relu
conv12 = tf.nn.relu(conv12, name='relu1.1')
##########################################################
## Branch 2
with tf.name_scope('conv1.3') as scope:
conv113 = tf.layers.conv2d(
conv1, # Input data
filters=32, # 32 filters
kernel_size=(1, 1), # Kernel size: 5x5
strides=(1, 1), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=11019),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1.3'
)
conv113 = tf.layers.batch_normalization(
conv113,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1.3'
)
# apply relu
conv113 = tf.nn.relu(conv113, name='relu1.3')
with tf.name_scope('conv1.4') as scope:
conv113 = tf.layers.conv2d(
conv113, # Input data
filters=64, # 32 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 2
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=11019),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv1.4'
)
conv113 = tf.layers.batch_normalization(
conv113,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn1.4'
)
# apply relu
conv113 = tf.nn.relu(conv113, name='relu1.4')
with tf.name_scope("concat1") as scope:
concat1 = tf.concat(
[conv12, conv113],
axis=3,
name='concat1'
)
# Max pooling layer 1
with tf.name_scope('pool1.1') as scope:
pool1 = tf.layers.max_pooling2d(
concat1, # Input
pool_size=(3, 3), # Pool size: 3x3
strides=(2, 2), # Stride: 2
padding='SAME', # "same" padding
name='pool1.1'
)
# optional dropout
if dropout:
pool1 = tf.layers.dropout(pool1, rate=pooldropout_rate, seed=103, training=training)
############################################################
## Convolutional layer 2 Branch 1
with tf.name_scope('conv2.0') as scope:
conv2 = tf.layers.conv2d(
pool1, # Input data
filters=64, # 32 filters
kernel_size=(1, 1), # Kernel size: 9x9
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=104),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv2.0'
)
conv2 = tf.layers.batch_normalization(
conv2,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn2.0'
)
# apply relu
conv2 = tf.nn.relu(conv2, name='relu2.0')
with tf.name_scope('conv2.1') as scope:
conv2 = tf.layers.conv2d(
conv2, # Input data
filters=96, # 32 filters
kernel_size=(3, 3), # Kernel size: 9x9
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=104),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv2.1'
)
conv2 = tf.layers.batch_normalization(
conv2,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn2.1'
)
# apply relu
conv2 = tf.nn.relu(conv2, name='relu2.1')
# Convolutional layer 2
with tf.name_scope('conv2.2') as scope:
conv22 = tf.layers.conv2d(
conv2, # Input data
filters=96, # 32 filters
kernel_size=(3, 3), # Kernel size: 9x9
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=1104),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv2.2'
)
conv22 = tf.layers.batch_normalization(
conv22,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn2.2'
)
# apply relu
conv22 = tf.nn.relu(conv22, name='relu2.2')
###########################################################
## Branch 2
with tf.name_scope('conv2.3') as scope:
conv23 = tf.layers.conv2d(
pool1, # Input data
filters=64, # 32 filters
kernel_size=(1, 1), # Kernel size: 9x9
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=104),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv2.3'
)
conv23 = tf.layers.batch_normalization(
conv23,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn2.3'
)
# apply relu
conv23 = tf.nn.relu(conv23, name='relu2.3')
with tf.name_scope('conv2.4') as scope:
conv23 = tf.layers.conv2d(
conv23, # Input data
filters=96, # 32 filters
kernel_size=(3, 3), # Kernel size: 9x9
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=104),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv2.4'
)
conv23 = tf.layers.batch_normalization(
conv23,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn2.4'
)
# apply relu
conv23 = tf.nn.relu(conv23, name='relu2.4')
with tf.name_scope("concat2") as scope:
concat2 = tf.concat(
[conv22, conv23],
axis=3,
name='concat2'
)
# Max pooling layer 2
with tf.name_scope('pool2.1') as scope:
pool2 = tf.layers.max_pooling2d(
concat2, # Input
pool_size=(2, 2), # Pool size: 3x3
strides=(2, 2), # Stride: 2
padding='SAME', # "same" padding
name='pool2.1'
)
# optional dropout
if dropout:
pool2 = tf.layers.dropout(pool2, rate=pooldropout_rate, seed=106, training=training)
# Convolutional layer 3
with tf.name_scope('conv3.1') as scope:
conv3 = tf.layers.conv2d(
pool2, # Input data
filters=256, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=107),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv3.1'
)
conv3 = tf.layers.batch_normalization(
conv3,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn3.1'
)
# apply relu
conv3 = tf.nn.relu(conv3, name='relu3.1')
# Convolutional layer 3
with tf.name_scope('conv3.2') as scope:
conv32 = tf.layers.conv2d(
conv3, # Input data
filters=256, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=1107),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv3.2'
)
conv32 = tf.layers.batch_normalization(
conv32,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn3.2'
)
# apply relu
conv32 = tf.nn.relu(conv32, name='relu3.2')
# Max pooling layer 3
with tf.name_scope('pool3') as scope:
pool3 = tf.layers.max_pooling2d(
conv32, # Input
pool_size=(2, 2), # Pool size: 2x2
strides=(2, 2), # Stride: 2
padding='SAME', # "same" padding
name='pool3'
)
if dropout:
pool3 = tf.layers.dropout(pool3, rate=pooldropout_rate, seed=109, training=training)
# Convolutional layer 4
with tf.name_scope('conv4') as scope:
conv4 = tf.layers.conv2d(
pool3, # Input data
filters=384, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=110),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv4'
)
conv4 = tf.layers.batch_normalization(
conv4,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn4'
)
# apply relu
conv4 = tf.nn.relu(conv4, name='relu4')
# Convolutional layer 4
with tf.name_scope('conv4.1') as scope:
conv4 = tf.layers.conv2d(
conv4, # Input data
filters=384, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=110),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv4.1'
)
conv4 = tf.layers.batch_normalization(
conv4,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn4.1'
)
# apply relu
conv4 = tf.nn.relu(conv4, name='relu4.1')
# Max pooling layer 4
with tf.name_scope('pool4') as scope:
pool4 = tf.layers.max_pooling2d(
conv4, # Input
pool_size=(2, 2), # Pool size: 2x2
strides=(2, 2), # Stride: 2
padding='SAME', # "same" padding
name='pool4'
)
if dropout:
pool4 = tf.layers.dropout(pool4, rate=pooldropout_rate, seed=112, training=training)
# Convolutional layer 5
with tf.name_scope('conv5') as scope:
conv5 = tf.layers.conv2d(
pool4, # Input data
filters=512, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=113),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv5'
)
conv5 = tf.layers.batch_normalization(
conv5,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn5'
)
# apply relu
conv5 = tf.nn.relu(conv5, name='relu5')
with tf.name_scope('conv5.1') as scope:
conv5 = tf.layers.conv2d(
conv5, # Input data
filters=512, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=113),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv5.1'
)
conv5 = tf.layers.batch_normalization(
conv5,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn5.1'
)
# apply relu
conv5 = tf.nn.relu(conv5, name='relu5.1')
# Max pooling layer 4
with tf.name_scope('pool5') as scope:
pool5 = tf.layers.max_pooling2d(
conv5,
pool_size=(2, 2), # Pool size: 2x2
strides=(2, 2), # Stride: 2
padding='SAME',
name='pool5'
)
if dropout:
pool5 = tf.layers.dropout(pool5, rate=pooldropout_rate, seed=115, training=training)
with tf.name_scope('conv6.1') as scope:
conv6 = tf.layers.conv2d(
pool5, # Input data
filters=512, # 48 filters
kernel_size=(3, 3), # Kernel size: 5x5
strides=(1, 1), # Stride: 1
padding='SAME', # "same" padding
activation=None, # None
kernel_initializer=tf.truncated_normal_initializer(stddev=5e-2, seed=117),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamC),
name='conv6.1'
)
conv6 = tf.layers.batch_normalization(
conv6,
axis=-1,
momentum=0.99,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn6.1'
)
# apply relu
conv6 = tf.nn.relu(conv6, name='relu6.1')
# Max pooling layer 6
with tf.name_scope('pool6') as scope:
pool6 = tf.layers.max_pooling2d(
conv6,
pool_size=(2, 2), # Pool size: 2x2
strides=(2, 2), # Stride: 2
padding='SAME',
name='pool6'
)
if dropout:
pool6 = tf.layers.dropout(pool6, rate=pooldropout_rate, seed=116, training=training)
# Flatten output
with tf.name_scope('flatten') as scope:
flat_output = tf.contrib.layers.flatten(pool6)
# dropout at fc rate
flat_output = tf.layers.dropout(flat_output, rate=fcdropout_rate, seed=116, training=training)
# Fully connected layer 1
with tf.name_scope('fc1') as scope:
fc1 = tf.layers.dense(
flat_output,
2048,
activation=None,
kernel_initializer=tf.variance_scaling_initializer(scale=2, seed=117),
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamF),
name="fc1"
)
bn_fc1 = tf.layers.batch_normalization(
fc1,
axis=-1,
momentum=0.9,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn_fc1'
)
fc1_relu = tf.nn.relu(bn_fc1, name='fc1_relu')
# dropout
fc1_relu = tf.layers.dropout(fc1_relu, rate=fcdropout_rate, seed=118, training=training)
# Fully connected layer 2
with tf.name_scope('fc2') as scope:
fc2 = tf.layers.dense(
fc1_relu, # input
1024, # 1024 hidden units
activation=None, # None
kernel_initializer=tf.variance_scaling_initializer(scale=2, seed=119),
bias_initializer=tf.zeros_initializer(),
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale=lamF),
name="fc2"
)
bn_fc2 = tf.layers.batch_normalization(
fc2,
axis=-1,
momentum=0.9,
epsilon=epsilon,
center=True,
scale=True,
beta_initializer=tf.zeros_initializer(),
gamma_initializer=tf.ones_initializer(),
moving_mean_initializer=tf.zeros_initializer(),
moving_variance_initializer=tf.ones_initializer(),
training=training,
name='bn_fc2'
)
fc2_relu = tf.nn.relu(bn_fc2, name='fc2_relu')
# dropout
fc2_relu = tf.layers.dropout(fc2_relu, rate=fcdropout_rate, seed=120, training=training)
# Output layer
logits = tf.layers.dense(
fc2_relu,
num_classes, # One output unit per category
activation=None, # No activation function
kernel_initializer=tf.variance_scaling_initializer(scale=1, seed=121),
bias_initializer=tf.zeros_initializer(),
name="logits"
)
# get the fully connected variables so we can only train them when retraining the network
fc_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "fc")
with tf.variable_scope('conv1', reuse=True):
conv_kernels1 = tf.get_variable('kernel')
kernel_transposed = tf.transpose(conv_kernels1, [3, 0, 1, 2])
with tf.variable_scope('visualization'):
tf.summary.image('conv1/filters', kernel_transposed, max_outputs=32, collections=["kernels"])
#########################################################
## Loss function options
# Regular mean cross entropy
# mean_ce = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=logits))
# This will weight the positive examples higher so as to improve recall and account for the unbalanced training data
weights = tf.multiply(weight, tf.cast(tf.greater(y, 0), tf.int32)) + 1
mean_ce = tf.reduce_mean(tf.losses.sparse_softmax_cross_entropy(labels=y, logits=logits, weights=weights))
# Add in l2 loss
loss = mean_ce + tf.losses.get_regularization_loss()
# Adam optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
# Minimize cross-entropy - freeze certain layers depending on input
if freeze:
train_op = optimizer.minimize(loss, global_step=global_step, var_list=fc_vars)
else:
train_op = optimizer.minimize(loss, global_step=global_step)
# get the probabilites for the classes
probabilities = tf.nn.softmax(logits, name="probabilities")
abnormal_probability = 1 - probabilities[:,0]
#################################################
## Compute predictions from the probabilities
# if we have multi-class do an argmax on the probabilities
if num_classes != 2:
predictions = tf.argmax(probabilities, axis=1, output_type=tf.int64)
# else if we have binary, use the threshold
else:
#predictions = tf.cast(tf.greater(abnormal_probability, threshold), tf.int32)
predictions = tf.argmax(probabilities, axis=1, output_type=tf.int64)
# get the accuracy
accuracy, acc_op = tf.metrics.accuracy(
labels=y,
predictions=predictions,
updates_collections=tf.GraphKeys.UPDATE_OPS,
name="accuracy",
)
# calculate recall
if num_classes > 2:
# collapse the predictions down to normal or not for our pr metrics
zero = tf.constant(0, dtype=tf.int64)
collapsed_predictions = tf.cast(tf.greater(abnormal_probability, threshold), tf.int32)
collapsed_labels = tf.greater(y, 0)
recall, rec_op = tf.metrics.recall(labels=collapsed_labels, predictions=collapsed_predictions, updates_collections=tf.GraphKeys.UPDATE_OPS, name="recall")
precision, prec_op = tf.metrics.precision(labels=collapsed_labels, predictions=collapsed_predictions, updates_collections=tf.GraphKeys.UPDATE_OPS, name="precision")
else:
recall, rec_op = tf.metrics.recall(labels=y, predictions=predictions, updates_collections=tf.GraphKeys.UPDATE_OPS, name="recall")
precision, prec_op = tf.metrics.precision(labels=y, predictions=predictions, updates_collections=tf.GraphKeys.UPDATE_OPS, name="precision")
f1_score = 2 * ((precision * recall) / (precision + recall))
_, update_op = summary_lib.pr_curve_streaming_op(name='pr_curve',
predictions=abnormal_probability,
labels=y,
updates_collections=tf.GraphKeys.UPDATE_OPS,
num_thresholds=20)
tf.summary.scalar('recall_1', recall, collections=["summaries"])
tf.summary.scalar('precision_1', precision, collections=["summaries"])
tf.summary.scalar('f1_score', f1_score, collections=["summaries"])
# Create summary hooks
tf.summary.scalar('accuracy', accuracy, collections=["summaries"])
tf.summary.scalar('cross_entropy', mean_ce, collections=["summaries"])
tf.summary.scalar('learning_rate', learning_rate, collections=["summaries"])
# add this so that the batch norm gets run
extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
# Merge all the summaries
merged = tf.summary.merge_all("summaries")
kernel_summaries = tf.summary.merge_all("kernels")
per_epoch_summaries = [[]]
print("Graph created...")
# ## Train
## CONFIGURE OPTIONS
if init_model is not None:
if os.path.exists(os.path.join("model", init_model + '.ckpt.index')):
init = False