-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNN_extended.py
1734 lines (1446 loc) · 66.7 KB
/
NN_extended.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 tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from sklearn.metrics import f1_score
from skimage.util import random_noise
from scipy.ndimage import rotate
import linecache
import copy
import h5py
import pdb
import sys
#import cv2
import os
#from eval_utils import eval_metrics
import PW_NN
import AL
class CNN(object):
"""Class of CNN models
"""
DEFAULT_HYPERS = {
# general parameters
'activation': 'ReLU',
'custom_getter': None,
'loss_name': 'CE',
'optimizer_name': 'SGD',
'lr_schedule': lambda t: exponential_decay(1e-3,t,0.1),
'regularizer': None,
'weight_decay': 1e-4,
# imbalanced optimization
'bin_class_weights': None,
'focal_gamma': None,
# batch normalization
'BN_decay': 0.999,
'BN_epsilon': 1e-3,
# Adam optimizer
'beta1': 0.9,
'beta2': 0.999,
# RMSProp optimizer
'decay': 0.9,
'momentum': 0.,
'epsilon': 1e-10,
# Aleatoric uncertainty
'AU_4L': False, # for labeled samples
'AU_4U': False, # for unlabeled samples
'AU_log_rel_coeff': 0.1,
'MC_T': 10, # for classification AU
# Mean Teacher semi-supervised
'MT_SSL': False,
'MT_ema_decay_schedule': lambda: tf.constant(0.999),
'rotation_angle': None,
'Gaussian_noise_std': None,
'output_perturbation_measure': 'CE',
'max_cons_coeff': 1e-3,
'rampup_length': 5000
}
def __init__(self,
x,
layer_dict,
name,
skips=[],
feature_layer=None,
dropout=None,
probes=[[],[]],
**kwargs):
"""Constructor takes the input placehoder, a dictionary
whose keys are names of the layers and the items assigned to each
key is a 2-element list inlcuding depth of this layer and its type,
and a name which will be assigned to the scope name of the variabels
The constructor goes through all the layers one-by-one in the same
order as the items of `layer_dict` dictionary, and add each layer
over the previous one. Each time the layers is added the output of
the model (stored in `self.output`) will be updated to be the output
of the last layer. Hence, when we added a layer with an index equal
to the given `feature_layer`, the marker `self.features` will be
make equal to the output of this layer. Moreover, if the dropout
is supposed to be applied on this layer, the output of this layer
will be dropped-out with the given probability, at the time of
training.
The assumption is that at least the first layer is a CNN, hence
depth of the input layer is the number of channels of the input.
It is further assumed that the last layer of the network is
not a CNN.
Also, there is the option of specifying a layer whose output
could be used extracted feature vectors of the input samples.
:Parameters:
**x** : Tensorflow placeholder in format [n_batch, (H, W), n_channel]
Input to the network
**layer_dict** : dictionary
Information about all layers of the network in format
{layer_name: [layer_type, layer_specs, operation_order]}
Layer's specifications, in turn, contains two or more
items dependending on the type of the layer. At this time
this class supports only three types of layers:
- Convolutional: [# output channel, kernel size, strides, padding]
- Transpose Convolutional:
[# output channel, kernel size, strides]
- Fully-connected: [# output channel]
- max-pooling: [pool size]
Note that "kernel size", "strides" and "pool size" are a list with
two elements, and "padding" is a string. For now the class
only supports `SAME` padding for transpose 2D-convolution; also
the second and third elements of `strides` for this layer
specifies height and width of the output tensor as
`width=strides[1]*input.shape[1]`
`height=strides[2]*input.shape[2]`
**name**: string
Name of Tensorflow scope of all the variables defined in
this class.
**skips** : list
List of skip connections; each element is a list of
three elements: [layer_index, list_of_destinations, skip_type]
which indicates that outputs of the layer_index should be
connected to the input of all layers with indices in
list_of_destinations; skip_type specifies the type of
connection: summing up if `skip_type=='sum'` and concatenating
if `skip_type=='con'`
CAUTIOUS: all elements in list_of_destinatins are assumed
to be larger than the (source) layer_index
**feature_layer** : int (default: None)
If given, is the index of the layer whose output will be
marked as the features extracted from the network; this
index should be given in terms of the order of layers in
`layer_dict`
**dropout** : list of two elements (default: None)
If any layer should be dropped out during the training,
this list contains the layers that need to be dropped out
(first item) and the drop-out rate (second item).
"""
self.x = x
self.name = name
self.batch_size = tf.shape(x)[0] # to be used in conv2d_transpose
self.layer_dict = layer_dict
self.skips = skips
self.input_shapes = []
self.output_shapes = []
if dropout:
self.dropout_layers = dropout[0]
self.dropout_rate = dropout[1]
else:
self.dropout_layers = []
self.dropout_rate = 0.
self.var_dict = {}
self.layer_names = list(layer_dict.keys())
self.probes = [{layer:[] for layer in probes[0]},
{layer:[] for layer in probes[1]}]
sources_idx = [skips[i][0] for i in range(len(skips))]
sources_output = []
with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
self.global_step = tf.Variable(0, trainable=False, name='global_step')
# setting the hyper-parameters
self.set_hypers(**kwargs)
self.learning_rate = self.lr_schedule(self.global_step)
self.keep_prob = tf.placeholder(tf.float32, name='keep_prob')
self.is_training = tf.placeholder(tf.bool, name='is_training')
self.output = x
for i, layer_name in enumerate(layer_dict):
# before adding a layer check if this layer
# is a destination layer, i.e. it has to
# consider the output of a previous layer
# in its input
combine_layer_outputs(self,
i,
skips,
sources_output)
if layer_name in probes[0]:
self.probes[0].update({layer_name: self.output})
layer = layer_dict[layer_name]
if len(layer)==2:
layer += ['M']
self.input_shapes += [[self.output.shape[i].value for i
in range(len(self.output.shape))]]
# layer[0]: layer type
# layer[1]: layer specs
# layer[2]: order of operations, default: 'M'
self.add_layer(
layer_name, layer[0], layer[1], layer[2])
self.output_shapes += [[self.output.shape[i].value for i
in range(len(self.output.shape))]]
# dropping out the output if the layer
# is in the list of dropped-out layers
if i in self.dropout_layers:
self.output = tf.nn.dropout(
self.output, self.keep_prob)
if layer_name in probes[1]:
self.probes[1].update({layer_name: self.output})
if i in sources_idx:
sources_output += [self.output]
# set the output of the layer one before last as
# the features that the network will extract
if i==feature_layer:
self.feature_layer = self.output
# flatenning the output of the current layer
# if it is 'conv' or 'pool' and the next
# layer is 'fc' (hence needs flattenned input)
if i<len(layer_dict)-1:
next_layer_type = layer_dict[
self.layer_names[i+1]][0]
if (layer[0]=='conv' or layer[0]=='pool') \
and next_layer_type=='fc':
# flattening the output
out_size = np.prod(
self.output.get_shape()[1:]).value
self.output = tf.reshape(
tf.transpose(self.output),
[out_size, -1])
# creating the label node
if len(self.output.shape)==2:
# posterior
posteriors = tf.nn.softmax(tf.transpose(self.output))
self.posteriors = tf.transpose(posteriors, name='Posteriors')
# prediction node
self.prediction = tf.argmax(self.posteriors, 0, name='Prediction')
c = self.output.get_shape()[0].value
self.class_num = c
self.y_ = tf.placeholder(tf.float32,
[c, None],
name='labels')
self.labels = tf.argmax(self.y_, axis=0)
else:
out_map_dim = [_.value for _ in self.output.shape[1:-1]]
c = self.output.shape[-1].value
if self.AU_4L or self.AU_4U:
if self.AU_4L:
# c is definitely even
c = int(c/2)
elif self.AU_4U:
c -= 1
if len(out_map_dim)==2:
self.clean_output = self.output[:,:,:,:c]
self.AU_vals = tf.nn.relu(self.output[:,:,:,c:])
elif len(out_map_dim)==3:
self.clean_output = self.output[:,:,:,:,:c]
self.AU_vals = tf.nn.relu(self.output[:,:,:,:,c:])
self.posteriors = tf.nn.softmax(self.clean_output)
# if AU values are to be used with labeled samples,
# corrupt the outputs with AU-dependent noise
if self.AU_4L:
corrupt_output_wAU_4L_FCN(self)
elif self.AU_4U:
if len(out_map_dim)==2:
self.AU_vals = self.AU_vals[:,:,:,0]
elif len(out_map_dim)==3:
self.AU_vals = self.AU_vals[:,:,:,:,0]
else:
self.posteriors = tf.nn.softmax(self.output, name='posterior')
self.y_ = tf.placeholder(tf.float32,[None,]+out_map_dim+[c,], name='one_hot_labels')
self.labels = tf.argmax(self.y_, axis=-1, name='labels')
self.prediction = tf.argmax(self.posteriors, axis=-1, name='prediction')
self.class_num = c
def add_layer(self,
layer_name,
layer_type,
layer_specs,
layer_op_order):
"""Adding a layer to the graph
Type of the next layer should also be given so that
the appropriate output can be prepared
:Parameters:
**layer_specs** : list of three elements
specification list of the layer with
a format explaned in `__init__` as the
items of `layer_dict`
**name** : string
**next_layer_type** : string
determining type of the next layer so that
the output will be provided accordingly
**last_layer** : binary flag
determining whether the layer is the
last one; if it is `True` there won't be
any activation at the output
"""
with tf.variable_scope(layer_name, reuse=tf.AUTO_REUSE):
for op in layer_op_order:
if op=='M':
# main operation
if layer_type=='conv':
self.add_conv(layer_name,
layer_specs)
elif layer_type=='conv_transpose':
self.add_conv_transpose(layer_name,
layer_specs)
elif layer_type=='fc':
self.add_fc(layer_name,
layer_specs)
elif layer_type=='pool':
self.add_pool(layer_specs)
else:
raise ValueError(
"Layer's type should be either 'fc'" +
", 'conv', 'conv_transpose' or 'pool'.")
elif op=='B':
# batch normalization
self.add_BN(layer_name, layer_specs)
elif op=='A':
# activation
if self.activation=='ReLU':
self.output = tf.nn.relu(self.output)
elif self.activation=='tanh':
self.output = tf.nn.tanh(self.output)
else:
raise ValueError('The specified activation cannot be found.')
else:
raise ValueError(
"Operations should be either 'M'" +
", 'B' or 'A'.")
def add_conv(self,
layer_name,
layer_specs):
"""Adding a convolutional layer to the graph given
the specifications
The layer specifications should have the following
order:
- [num. of kernel, dim. of kernel, strides, padding]
It should containt at least the first two elements,
the other two have default values.
CAUTIOUS: when giving default values be careful
about the order of the parameters, e.g. you cannot
use default values for strides, when padding is
assigned a value. The 3rd value will ALWAYS be
assigned to strides
"""
# creating necessary TF variables
kernel_num = layer_specs[0]
kernel_dim = layer_specs[1]
if len(layer_specs)==2:
strides = [1]*len(kernel_dim)
padding='SAME'
elif len(layer_specs)==3:
strides = layer_specs[2]
padding='SAME'
prev_depth = self.output.get_shape()[-1].value
W = weight_variable('Weight',
kernel_dim +
[prev_depth,
kernel_num],
self.regularizer,
self.custom_getter)
b = bias_variable('Bias', [kernel_num],
self.custom_getter)
new_vars = [W,b]
# there may have already been some variables
# created for this layer (through BN)
if layer_name in self.var_dict:
self.var_dict[layer_name] += new_vars
else:
self.var_dict.update({layer_name: new_vars})
# output of the layer
if len(kernel_dim)==2:
self.output = tf.nn.conv2d(
self.output, W,
strides= [1,] + strides + [1,],
padding=padding) + b
elif len(kernel_dim)==3:
self.output = tf.nn.conv3d(
self.output, W,
strides= [1,] + strides + [1,],
padding = padding) + b
def add_fc(self,
layer_name,
layer_specs):
"""Adding a fully-connected layer with a given
specification to the graph
"""
prev_depth = self.output.get_shape()[0].value
new_vars = [weight_variable('Weight',
[layer_specs[0], prev_depth],
self.regularizer,
self.custom_getter),
bias_variable('Bias', [layer_specs[0], 1],
self.custom_getter)
]
if layer_name in self.var_dict:
self.var_dict[layer_name] += new_vars
else:
self.var_dict.update({layer_name: new_vars})
# output of the layer
self.output = tf.matmul(
self.var_dict[layer_name][-2],
self.output) + self.var_dict[layer_name][-1]
def add_pool(self, layer_specs):
"""Adding a (max-)pooling layer with given specifications
* `layer_specs` : list
A list of integers representing window size (=strides)
NOTE: for now, the assumption here is that strides and
window sizes are equal in all directions (because almost
always we use max-pooling for reducing dimensioanlities)
"""
w_sizes = layer_specs
strides = layer_specs
self.output = max_pool(self.output,
w_sizes,
strides)
def add_BN(self,
layer_name,
layer_specs):
"""Adding batch normalization layer
Here, we used tf.contrib.layers.batch_norm which takes
care of updating population mean and variance during the
training phase by means of exponential moving averaging.
Hence, we need an extra boolean placeholder for the model
that specifies when we are in the training phase and
when we are in test.
"""
# get the current scope
scope = tf.get_variable_scope()
# NOTE: We need to have a variable scope to create this
# layer because we use the tf.contrib.layers.batch_norm
# with `reuse=True`, which needs to be provided the
# variable scope too
# shape of the variables
output_shape = self.output.shape
if len(output_shape)==2:
ax = [1]
shape = [output_shape[0].value]
else:
ax = [0]
#shape = [output_shape[i].value for i
# in range(1,len(output_shape))]
shape = [output_shape[-1].value]
# creating the variables
new_vars = [
tf.get_variable('gamma', dtype=tf.float32,
initializer=tf.ones(shape),
custom_getter=self.custom_getter),
tf.get_variable('beta', dtype=tf.float32,
initializer=tf.zeros(shape),
custom_getter=self.custom_getter),
tf.get_variable('moving_mean', dtype=tf.float32,
initializer=tf.zeros(shape),
trainable=False),
tf.get_variable('moving_variance', dtype=tf.float32,
initializer=tf.ones(shape),
trainable=False)]
if layer_name in self.var_dict:
self.var_dict[layer_name] += new_vars
else:
self.var_dict.update({layer_name: new_vars})
if not(hasattr(self, 'BN_decay')):
self.BN_decay = 0.999
if not(hasattr(self, 'BN_epsilon')):
self.BN_epsilon = 1e-3
self.output = tf.contrib.layers.batch_norm(
self.output,
decay=self.BN_decay,
center=True,
scale=True,
epsilon=self.BN_epsilon,
is_training=self.is_training,
reuse=True,
scope=scope)
def add_conv_transpose(self,
layer_name,
layer_specs):
"""Adding a transpose convolutional layer
Any transpose convolution is indeed the backward
direction of a convolution layer with some
ambiguity on the output's size (not fully clear)
Number of elements in `layer_specs` of this
layer should be EXACTLY three
"""
kernel_num = layer_specs[0]
kernel_dim = layer_specs[1]
strides = layer_specs[2]
# adding new variables
prev_depth = self.output.get_shape()[-1].value
W = weight_variable('Weight',
kernel_dim +
[kernel_num,
prev_depth],
self.regularizer,
self.custom_getter)
b = bias_variable('Bias', [kernel_num],
self.custom_getter)
new_vars = [W,b]
# there may have already been some variables
# created for this layer (through BN)
if layer_name in self.var_dict:
self.var_dict[layer_name] += new_vars
else:
self.var_dict.update({layer_name: new_vars})
# output of the layer
dim = len(self.x.shape) - 2
input_size = [self.output.shape[i].value for
i in range(1,dim+1)]
output_shape = [self.batch_size,] + \
[strides[i]*input_size[i] for i in range(dim)] +\
[kernel_num,]
strides = [1,] + strides + [1,]
# padding will stay `SAME` for now
if dim==2:
self.output = tf.nn.conv2d_transpose(
self.output, W, output_shape, strides) + b
elif dim==3:
self.output = tf.nn.conv3d_transpose(
self.output, W, output_shape, strides) + b
# last line is adding zeros with the same size of the
# output (except batch size) only in order to
# remove the size ambiguities that is created by
# tf.nn.conv2d_transpsoe
if output_shape[-1]>1:
self.output += tf.constant(0., shape=[1,]+output_shape[1:])
else:
output_shape[-1]=2
self.output += tf.constant(0., shape=[1,]+output_shape[1:])
if dim==2:
self.output = self.output[:,:,:,:1]
elif dim==3:
self.output = self.output[:,:,:,:,:1]
def set_hypers(self, **kwargs):
kwargs.setdefault('activation', self.DEFAULT_HYPERS['activation'])
kwargs.setdefault('custom_getter', self.DEFAULT_HYPERS['custom_getter'])
kwargs.setdefault('BN_decay', self.DEFAULT_HYPERS['BN_decay'])
kwargs.setdefault('BN_epsilon', self.DEFAULT_HYPERS['BN_epsilon'])
# optimizer and loss
kwargs.setdefault('loss_name', self.DEFAULT_HYPERS['loss_name'])
kwargs.setdefault('optimizer_name', self.DEFAULT_HYPERS['optimizer_name'])
kwargs.setdefault('lr_schedule', self.DEFAULT_HYPERS['lr_schedule'])
if kwargs['optimizer_name']=='Adam':
kwargs.setdefault('beta1', self.DEFAULT_HYPERS['beta1'])
kwargs.setdefault('beta2', self.DEFAULT_HYPERS['beta2'])
elif kwargs['optimizer_name']=='RMSProp':
kwargs.setdefault('decay', self.DEFAULT_HYPERS['decay'])
kwargs.setdefault('momentum', self.DEFAULT_HYPERS['momentum'])
kwargs.setdefault('epsilon', self.DEFAULT_HYPERS['epsilon'])
# weight regularization
kwargs.setdefault('regularizer', self.DEFAULT_HYPERS['regularizer'])
# binary class weighting
kwargs.setdefault('bin_class_weights', self.DEFAULT_HYPERS['bin_class_weights'])
kwargs.setdefault('focal_gamma', self.DEFAULT_HYPERS['focal_gamma'])
if kwargs['regularizer'] is not None:
kwargs.setdefault('weight_decay', self.DEFAULT_HYPERS['weight_decay'])
# aleatoric uncertainty
kwargs.setdefault('AU_4L', self.DEFAULT_HYPERS['AU_4L'])
kwargs.setdefault('AU_4U', self.DEFAULT_HYPERS['AU_4U'])
kwargs.setdefault('AU_log_rel_coeff', self.DEFAULT_HYPERS['AU_log_rel_coeff'])
if kwargs['AU_4L']:
kwargs.setdefault('MC_T', self.DEFAULT_HYPERS['MC_T'])
# consistency-based semi-supervised
kwargs.setdefault('MT_SSL', self.DEFAULT_HYPERS['MT_SSL'])
if kwargs['MT_SSL']:
kwargs.setdefault('MT_ema_decay_schedule', self.DEFAULT_HYPERS['MT_ema_decay_schedule'])
kwargs['MT_ema_decay'] = kwargs['MT_ema_decay_schedule'](self.global_step)
kwargs.setdefault('Gaussian_noise_std', self.DEFAULT_HYPERS['Gaussian_noise_std'])
kwargs.setdefault('rotation_angle', self.DEFAULT_HYPERS['rotation_angle'])
kwargs.setdefault('output_perturbation_measure', self.DEFAULT_HYPERS['output_perturbation_measure'])
kwargs.setdefault('max_cons_coeff', self.DEFAULT_HYPERS['max_cons_coeff'])
kwargs.setdefault('rampup_length', self.DEFAULT_HYPERS['rampup_length'])
self.__dict__.update(kwargs)
def get_var_by_layer_and_op_name(self, layer_name, op_name):
var_names = [var.name for var in self.var_dict[layer_name]]
bin_op_indic = [op_name in var_name for var_name in var_names]
op_loc_in_layer = np.where(np.array(bin_op_indic))[0][0]
return self.var_dict[layer_name][op_loc_in_layer]
def initialize(self, sess):
"""Initializing the model
:Parameters:
**sess** : Tensorflow session
The active session in which the model is
running
"""
# initializing variables of this model only
model_vars = [var for var in tf.global_variables()
if self.name in var.name] + [self.global_step]
sess.run(tf.variables_initializer(model_vars))
def save_weights(self, file_path):
"""Saving only the parameter values of the
current model into a .h5 file
The file will have as many groups as the number
of layers in the model (which is equal to the
number of keys in `self.var_dict`. Each group has
two datasets, one for the weight W, and one for
the bias b.
"""
f = h5py.File(file_path, 'w')
for layer_name, layer_vars in self.var_dict.items():
L = f.create_group(layer_name)
for var in layer_vars:
var_name = var.name.split('/')[-1][:-2]
# if self is a MT model, ignore last name, which
# is ExponentialMovingAverage for all variables
if 'Exponential' in var.name:
var_name = var.name.split('/')[-2]
# last line, [:-2] accounts for ':0' in
# TF variables
L.create_dataset(var_name, data=var.eval())
# save the weights in branches too, if any
if hasattr(self, 'branches'):
for bname, branch in self.branches.items():
B = f.create_group(bname)
for layer_name, layer_vars in branch.var_dict.items():
# if the layer is from the main body,
# ignore it
if bname not in layer_vars[0].name:
continue
sub_B = B.create_group(layer_name)
for var in layer_vars:
var_name = var.name.split('/')[-1][:-2]
sub_B.create_dataset(var_name, data=var.eval())
f.close()
def load_weights(self, file_path, session):
"""Loading parameter values saved in a .h5 file
into the tensorflow variables of the class object
The groups in the .h5 file should match the layers
in the model. Specifically, name of each group
needs to be the same as the name of the layers
in `self.var_dict` (this is autmatically satisfied
if the .h5 file is generated using self.save_model().
"""
f = h5py.File(file_path)
model_real_name = self.output.name.split('/')[0]
for layer_name in list(self.var_dict):
var_names = list(f[layer_name].keys())
for var_name in var_names:
var_value = np.array(f[layer_name][var_name])
full_var_name = '/'.join([model_real_name,
layer_name,
var_name])
tf_var = tf.get_collection(
tf.GraphKeys.GLOBAL_VARIABLES,
scope=full_var_name)[0]
session.run(tf_var.assign(var_value))
def add_assign_ops(self):
"""Adding operations for assigning values to
the nodes of the class's graph. This method
is for creating repeatedly assigning values to
the nodes after finalizing the graph. It should
be called before `sess.graph.finalize()` to
create the operation nodes before finalizing.
Then, the created operation nodes can be
performed without any need to create new nodes.
Note that such repeated value assignment to the
nodes are necessary for, say, querying iterations
where after selecting each set of queries the model
should be trained from scratch (or from the point
that we saved the weights beforehand).
This function, together with `self.perform_assign_ops`
will be used instead of `self.load_weights` when
value assignment needs to be done repeatedly after
finalizing the graph.
The function defines a new attribute called `assign_dict`,
a dictionary of layer names as the keys. Each item
of `assign_dict` is itself a dictionary with keys
equal to the variables names of that layer (from
among `Weight`, `Bias`, `Scale` and `Offset`). Each
item of this dictionary then has two elements:
- the assigning operation for the variable
with the given name
- the placeholder that will carry the value
to be assigned to this variable
In summary `assign_dict` has the following structure:
{
'layer_name_1': {'Weight': [<assign_op>,
<placeholder>],
'Bias': [<assign_op>,
<placeholder>]}
:
'branch_name_1': {layer_name_1: {'Weight': [<assign_op>,
<placeholder>],
'Bias': [<assign_op>,
<placeholder>]}
}
}
"""
self.assign_dict = {}
# main body
for layer_name, layer_vars in self.var_dict.items():
layer_dict = {}
for var in layer_vars:
var_name = var.name.split('/')[-1][:-2]
# value placeholder
var_placeholder = tf.placeholder(var.dtype,
var.get_shape())
# assigning ops
assign_op = var.assign(var_placeholder)
layer_dict.update({var_name:[assign_op,
var_placeholder]})
self.assign_dict.update({layer_name: layer_dict})
# network branches, if any
if hasattr(self, 'branches'):
for bname, branch in self.branches.items():
branch_dict = {}
for layer_name, layer_vars in branch.var_dict.items():
# ignore those layers that are the main body too
if bname not in layer_vars[0].name:
continue
layer_dict = {}
for var in layer_vars:
var_name = var.name.split('/')[-1][:-2]
# value placeholder
var_placeholder = tf.placeholder(var.dtype,
var.get_shape())
# assigning ops
assign_op = var.assign(var_placeholder)
layer_dict[var_name] = [assign_op,
var_placeholder]
branch_dict[layer_name] = layer_dict
self.assign_dict[bname] = branch_dict
def perform_assign_ops(self,file_path,sess):
"""Performing assignment operations that have
been created by `self.add_assign_ops`.
This function, together with `self.add_assign_ops`
will be used instead of `self.load_weights` when
value assignment needs to be done repeatedly after
finalizing the graph.
"""
model_real_name = self.output.name.split('/')[0]
f = h5py.File(file_path)
# get a list of branch names, if any
if hasattr(self, 'branches'):
bnames = list(self.branches.keys())
else:
bnames = []
# preparing the operation list to be performed
# and the necessary `feed_dict`
feed_dict={}
ops_list = []
for name in self.assign_dict:
# this `name` could be a layer name, or a branch name
if name in bnames:
branch_name = name
for layer_name in self.assign_dict[branch_name]:
var_names = list(f[branch_name][layer_name].keys())
for var_name in var_names:
var_value = np.array(f[branch_name][layer_name][var_name])
# adding the operation
ops_list += [self.assign_dict[branch_name][layer_name][var_name][0]]
# adding the corresponding value into feed_dict
feed_dict.update({
self.assign_dict[branch_name][layer_name][var_name][1]:
var_value})
else:
layer_name = name
var_names = list(f[layer_name].keys())
for var_name in var_names:
var_value = np.array(f[layer_name][var_name])
# adding the operation
ops_list += [self.assign_dict[layer_name][var_name][0]]
# adding the corresponding value into feed_dict
feed_dict.update({
self.assign_dict[layer_name][var_name][1]: var_value})
sess.run(ops_list, feed_dict=feed_dict)
def get_optimizer(self):
"""Form the loss function and optimizer of the CNN graph
:Parameters;
**learning_rate** : positive float
learning rate of the optimization, which is
proportional to the step length of the descent
**layer_list** : list of strings
list of names of those layers that are to be
modified in the training step; if empty all
the layers will be included. This list should
be a subset of `self.var_dict.keys()`.
"""
with tf.variable_scope(self.name, reuse=tf.AUTO_REUSE):
if len(self.output.shape)==2:
get_loss(self)
else:
get_FCN_loss(self)
# adding regularization, if any
if self.regularizer is not None:
reg_term = tf.reduce_mean(
tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES))
self.loss += self.weight_decay*reg_term
get_optimizer(self)
def perturb_input(self):
self.perturbed_x = self.x
# Gaussian noise
if self.Gaussian_noise_std is not None:
eps = tf.random_normal(tf.shape(self.perturbed_x),
stddev=self.Gaussian_noise_std)
self.perturbed_x = tf.add(model.perturbed_x, eps)
# rotation
if self.rotation_angle is not None:
self.perturbed_x = tf.contrib.image.rotate(
self.perturbed_x, self.rotation_angle)
def train(self,sess,
global_step_limit,
train_gen,
metric_gens=[],
eval_step=100,
save_path=None):
""" The argument `metric_gens` should be a list of
two elements: (1) the set of metrics to be computed
as the evaluation metrics, (2) the data generator to be used
for computing the metrics
"""
if len(metric_gens)>0:
if not(isinstance(metric_gens[0], list)):
metric_gens = [metric_gens]
for i in range(len(metric_gens)):
valid_dict = {}
for metric in metric_gens[i][0]:
metric_path = os.path.join(save_path,'%s_%d.txt'%(metric, i))
if os.path.exists(metric_path):
M = list(np.loadtxt(metric_path))
else:
M = []
valid_dict.update({metric: M})
setattr(self, 'valid_metrics_%d'%i, valid_dict)
# training iterations
while self.global_step.eval() < global_step_limit:
batch_X, batch_Y = train_gen()
# first, have an initial evaluation
# (if a validation generator is given)
if not(self.global_step.eval()%eval_step):
for i in range(len(metric_gens)):
eval_metrics(self, sess,
metric_gens[i][1],
metric_gens[i][2],
True,
'valid_metrics_%d'%i)
if save_path is not None:
for metric in metric_gens[i][0]:
np.savetxt(os.path.join(save_path,'%s_%d.txt'%(metric, i)),
getattr(self, 'valid_metrics_%d'%i)[metric])
if self.global_step.eval()>0:
self.save_weights(os.path.join(save_path, 'model_pars.h5'))
if hasattr(self, 'teacher'):
self.teacher.save_weights(os.path.join(save_path,
'teacher_pars.h5'))
if len(metric_gens[0])==4:
V = self.valid_metrics_0[metric_gens[0][3]]
if np.all(V[-1] > V[:-1]):
np.savetxt(os.path.join(save_path,'max_valid_iter.txt'),
[self.global_step.eval()])
self.save_weights(os.path.join(save_path,
'max_model_pars.h5'))
if hasattr(self, 'teacher'):
self.teacher.save_weights(os.path.join(save_path,
'max_teacher_pars.h5'))
# --------------------------------------------- #
# --------------------------------------------- #
feed_dict = {self.x: batch_X,
self.y_: batch_Y,
self.keep_prob:1-self.dropout_rate,
self.is_training: True}
# setting up extra feed-dict if a teacher exists
if hasattr(self, 'teacher'):
feed_dict.update({