-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathNN.py
1557 lines (1279 loc) · 50.8 KB
/
NN.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
import linecache
import copy
import h5py
import pdb
import sys
#import cv2
import os
import NNAL_tools
import PW_NN
import AL
read_file_path = "/home/ch194765/repos/atlas-active-learning/"
sys.path.insert(0, read_file_path)
#import prep_dat
read_file_path = "/home/ch194765/repos/atlas-active-learning/AlexNet"
sys.path.insert(0, read_file_path)
import alexnet
from alexnet import AlexNet
def AlexNet_features(img_arr):
"""Extracting features from the pretrained alexnet
"""
tf.reset_default_graph()
# creating the network
# placeholder for input and dropout rate
x = tf.placeholder(tf.float32, shape=[None, 227, 227, 3])
keep_prob = tf.placeholder(tf.float32)
# create model with default config
# ( == no skip_layer and 1000 units in the last layer)
model = alexnet.AlexNet(
x, keep_prob, 1000, [],
weights_path='/home/ch194765/repos/atlas-active-learning/AlexNet/bvlc_alexnet.npy')
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# Load the pretrained weights into the model
model.load_initial_weights(sess)
# extract the features
features = sess.run(model.feature_layer,
feed_dict={x: img_arr, keep_prob: 1})
return features
class CNN(object):
"""Class of CNN models
"""
def __init__(self,
x,
layer_dict,
name,
feature_layer=None,
dropout=None,
probes=[]):
"""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_characteristic}
Layer's characteristic, in turn, contains two or three
items dependending on the type of the layer. At this time
this class supports only three types of layers:
- Convolutional: [# output channel, 'conv', kernel size]
- Fully-connected: [# output channel, 'fc']
- max-pooling: [pool size, 'pool']
Note that "kernel size" and "pool size" are a list with
two elements.
**name**: string
Name of Tensorflow scope of all the variables defined in
this class.
**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.layer_type = []
self.name = name
self.keep_prob = tf.placeholder(
tf.float32, name='keep_prob')
if dropout:
self.dropout_layers = dropout[0]
self.dropout_rate = dropout[1]
else:
self.dropout_layers = []
self.dropout_rate = 1.
# creating the network's variables
self.var_dict = {}
layer_names = list(layer_dict.keys())
self.probes = []
with tf.name_scope(name):
for i in range(len(layer_dict)):
# extract previous depth
if i==0:
#prev_depth = x.shape[-1].value
self.output = x
if i==len(layer_dict)-1:
last_layer_flag=True
next_layer_type = None
else:
last_layer_flag=False
next_layer_type = layer_dict[
layer_names[i+1]][1]
self.add_layer(
layer_dict[layer_names[i]],
layer_names[i],
next_layer_type,
last_layer_flag)
# dropping out the output layers 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)
# 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
if i in probes:
self.probes += [self.output]
self.layer_type += [
layer_dict[layer_names[i]][1]]
# posterior
posteriors = tf.nn.softmax(
tf.transpose(self.output))
self.posteriors = tf.transpose(
posteriors, name='posteriors')
def add_layer(self,
layer_specs,
name,
next_layer_type=None,
last_layer=True):
"""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
"""
if layer_specs[1]=='conv':
# if the next layer is fully-connected,
# output a flattened tensor
if next_layer_type=='fc':
self.add_conv(layer_specs,
name,
flatten=True)
else:
self.add_conv(layer_specs,
name,
flatten=False)
elif layer_specs[1]=='fc':
# apply relu activation only if we are NOT
# at the last layer
if last_layer:
self.add_fc(layer_specs,
name,
activation=False)
else:
self.add_fc(layer_specs,
name,
activation=True)
elif layer_specs[1] == 'pool':
# if the next layer is fully-connected we need
# to output a flatten tensor
if next_layer_type=='fc':
self.add_pool(layer_specs,
flatten=True)
else:
self.add_pool(layer_specs,
flatten=False)
else:
raise ValueError(
"Layer's type should be either 'fc'" +
", 'conv' or 'pool'.")
def add_conv(self,
layer_specs,
name,
flatten=True,
strides = [1,1],
padding='SAME',):
"""Adding a convolutional layer to the graph given
the specifications
"""
kernel_dim = layer_specs[2]
prev_depth = self.output.get_shape()[-1].value
self.var_dict.update(
{name: [
weight_variable(
[kernel_dim[0],
kernel_dim[1],
prev_depth,
layer_specs[0]],
name=name+'_weight'),
bias_variable(
[layer_specs[0]],
name=name+'_bias')
]
}
)
# output of the layer
output = tf.nn.conv2d(
self.output,
self.var_dict[name][0],
strides= [1,] + strides + [1,],
padding=padding) + self.var_dict[name][1]
self.output = tf.nn.relu(output)
# if the flatten flag is True,
# flatten the output tensor
# into a 2D array, where each column
# has a vectorized tensor in it
if flatten:
out_size = np.prod(
self.output.get_shape()[1:]).value
self.output = tf.reshape(
tf.transpose(self.output),
[out_size, -1])
def add_fc(self,
layer_specs,
name,
activation=True):
"""Adding a fully-connected layer with a given
specification to the graph
"""
prev_depth = self.output.get_shape()[0].value
self.var_dict.update(
{name:[
weight_variable(
[layer_specs[0], prev_depth],
name=name+'_weight'),
bias_variable(
[layer_specs[0], 1],
name=name+'_bias')]
}
)
# output of the layer
self.output = tf.matmul(
self.var_dict[name][0],
self.output) + self.var_dict[name][1]
# apply activation function if necessary
if activation:
self.output = tf.nn.relu(self.output)
def add_pool(self, layer_specs, flatten=False):
"""Adding a (max-)pooling layer with given specifications
"""
pool_size = layer_specs[0]
self.output = max_pool(self.output,
pool_size[0],
pool_size[1])
# flatten the output if necessary
if flatten:
out_size = np.prod(self.output.get_shape()[1:]).value
self.output = tf.reshape(
tf.transpose(self.output), [out_size, -1])
def add_unpool(self, layer_specs, flatten=False):
"""Adding an unpooling layer as the opposite layer of a
pooling one, to increase size of the output
For now, we are using NN interpolation.
"""
pool_size = layer_specs[0]
def initialize_graph(self,
session,
path=None):
"""Initializing the graph, and if given loading
a set of pre-trained weights into the model
:Parameters:
**session** : Tensorflow session
The active session in which the model is
running
**pretr_name** : string (default: None)
Name of the model that has pre-trained
weights. It will be `None` if no pre-
trained weights are given
**path** : string (default: None)
Path to the pre-trained weights, if the
the given model has one
"""
model_vars = list(np.concatenate(
[self.var_dict[layer_name] for layer_name
in self.var_dict]))
session.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, pars in self.var_dict.items():
L = f.create_group(layer_name)
L.create_dataset('Weight', data=pars[0].eval())
L.create_dataset('Bias', data=pars[1].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)
for layer_name, pars in self.var_dict.items():
# weight
value_to_load = np.array(
f[layer_name]['Weight'])
session.run(pars[0].assign(value_to_load))
# bias
value_to_load = np.array(
f[layer_name]['Bias'])
session.run(pars[1].assign(value_to_load))
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.
"""
self.assign_placeholders={}
self.assign_ops=[]
for layer_name, pars in self.var_dict.items():
# assigning value placeholders
self.assign_placeholders.update(
{layer_name: [tf.placeholder(pars[0].dtype,
pars[0].get_shape()),
tf.placeholder(pars[1].dtype,
pars[1].get_shape())]})
# assigning ops
self.assign_ops += [pars[0].assign(
self.assign_placeholders[layer_name][0])]
self.assign_ops += [pars[1].assign(
self.assign_placeholders[layer_name][1])]
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.
"""
feed_dict={}
if file_path=='init':
# preparing feed_dict
for layer_name, pars in self.var_dict.items():
# initial values for weights
W_shape = pars[0].shape
if len(W_shape)>2:
# conv. layer
# (kernel w x kernel h x in_channels
n = np.prod([W_shape[i].value for i
in range(3)])
std = np.sqrt(2/n)
W_init = std*np.random.randn(W_shape[0].value,
W_shape[1].value,
W_shape[2].value,
W_shape[3].value)
else:
# fc layer
n = W_shape[1].value
std = np.sqrt(2/n)
W_init = std*np.random.randn(W_shape[0].value,
W_shape[1].value)
b_shape = pars[1].shape
b_init = np.zeros([b_shape[i].value for i
in range(len(b_shape))])
feed_dict.update({
self.assign_placeholders[layer_name][0]:W_init,
self.assign_placeholders[layer_name][1]:b_init})
else:
f = h5py.File(file_path)
# preparing feed_dict
for layer_name, pars in self.var_dict.items():
# weight
W = np.array(f[layer_name]['Weight'])
b = np.array(f[layer_name]['Bias'])
feed_dict.update({
self.assign_placeholders[layer_name][0]:W,
self.assign_placeholders[layer_name][1]:b})
sess.run(self.assign_ops, feed_dict=feed_dict)
def extract_features(self, inds,
expr,
session):
"""Extracting features
"""
n = len(inds)
d = self.feature_layer.get_shape()[0].value
features = np.zeros((d, n))
batch_size = expr.pars['batch_size']
# preparing batch_of_inds, whose
# indices are in terms of "inds"
if batch_size > n:
batch_of_inds = [np.arange(
n).tolist()]
else:
batch_of_inds = gen_batch_inds(
n, batch_size)
# extracting the features
for inner_inds in batch_of_inds:
# loading the data for this patch
X,_ = load_winds(inds[inner_inds],
expr.imgs_path_file,
expr.pars['target_shape'],
expr.pars['mean'])
features[:,inner_inds] = session.run(
self.feature_layer,
feed_dict={self.x: X,
self.keep_prob:1.})
return features
def get_optimizer(self, learning_rate,
train_layers=[],
optimizer_name='SGD'):
"""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()`.
"""
# number of classes
c = self.output.get_shape()[0].value
self.y_ = tf.placeholder(tf.float32,
[c, None],
name='labels')
# loss function
self.loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(
labels=tf.transpose(self.y_),
logits=tf.transpose(self.output)),
name='loss')
tf.summary.scalar('Loss', self.loss)
# optimizer
if len(train_layers)==0:
if optimizer_name=='SGD':
self.train_step = tf.train.GradientDescentOptimizer(
learning_rate).minimize(
self.loss)
elif optimizer_name=='Adam':
self.train_step = tf.train.AdamOptimizer(
learning_rate).minimize(
self.loss)
else:
self.train_layers = train_layers
# if some layers are specified, only
# modify these layers in the training
var_list = []
for layer in train_layers:
var_list += self.var_dict[layer]
if optimizer_name=='SGD':
self.train_step = tf.train.GradientDescentOptimizer(
learning_rate).minimize(
self.loss, var_list=var_list)
elif optimizer_name=='Adam':
self.train_step = tf.train.AdamOptimizer(
learning_rate).minimize(
self.loss, var_list=var_list)
# define the accuracy
self.prediction = tf.argmax(
self.posteriors, 0, name='prediction')
def get_gradients(self, grad_layers=[]):
"""Forming gradients of the log-posteriors
"""
# collect all the trainable variabels
self.grad_layers = grad_layers
if len(grad_layers)==0:
gpars = tf.trainable_variables()
else:
gpars = []
for layer in grad_layers:
gpars += self.var_dict[layer]
self.grad_posts = {}
c = self.output.get_shape()[0].value
# in binary classification, get only
# gradient of the first class
for j in range(c):
self.grad_posts.update(
{str(j): tf.gradients(
tf.log(self.posteriors[j, 0]),
gpars, name='score_class_%d'% j)
}
)
def train_graph_one_epoch(self, expr,
train_inds,
session,
TB_opt={}):
"""Randomly partition the data into
batches and complete one epoch of training
:Parameters:
**expr** : AL.Experiment object
**train_inds** : list or array of integers
indices of the samples in terms of the
`img_path_list` of the give experiment
based on which the model is to be modified
**batch_size** : integer
size of the batch for training or
evaluating the accuracy
**session** : Tensorflow Session
**TB_opt** : dictionary (default={})
If the results are to be saved for
Tensorboard's use, this dictionary
includes all the necessary information
for saving the TB files:
* `summs`: the merged summaries that are
are created outisde the function
* `writer`: file writer f the TB for these
this epoch (it contains the path
in which the TB files will be saved)
* `epoch_id`: index of the current epoch
* `tag`: a tag for the current training epoch
"""
# random partitioning into batches
batch_size = expr.pars['batch_size']
train_size = len(train_inds)
if train_size > batch_size:
batch_of_inds = gen_batch_inds(
train_size, batch_size)
else:
batch_of_inds = [np.arange(
train_size).tolist()]
# completing an epoch
for j in range(len(batch_of_inds)):
# create the 4D array of batch images
iter_inds = train_inds[batch_of_inds[j]]
batch_of_imgs, batch_of_labels = load_winds(
iter_inds,
expr.imgs_path_file,
expr.pars['target_shape'],
expr.pars['mean'],
expr.labels_file)
batch_of_labels = AL.make_onehot(
batch_of_labels, expr.nclass)
if TB_opt:
summary, _ = session.run(
[TB_opt['summs'], self.train_step],
feed_dict={self.x: batch_of_imgs,
self.y_: batch_of_labels,
self.keep_prob: self.dropout_rate})
else:
session.run(
self.train_step,
feed_dict={self.x: batch_of_imgs,
self.y_: batch_of_labels,
self.keep_prob: self.dropout_rate})
# writing tensorboard files if necessary
# (every 50 iterations)
if TB_opt:
if j%50 == 0:
# compute the accuracy
train_preds = self.predict(
expr, train_inds, session)
iter_acc = AL.get_accuracy(
train_preds, expr.labels[:,train_inds])
# adding accuracy to a summary
acc_summary = tf.Summary()
acc_summary.value.add(
tag='Accuracy',
simple_value=iter_acc)
TB_opt['writer'].add_summary(
summary,
TB_opt['epoch_id']*len(batch_of_inds)+j)
TB_opt['writer'].add_summary(
acc_summary,
TB_opt['epoch_id']*len(batch_of_inds)+j)
def validated_train(self,
expr,
sess,
train_inds,
valid_ratio,
const_inds=None,
print_flag=False):
"""Validated training of a CNN model
:Parameters:
**model** : CNN object
the CNN model which has the method
`train_graph_one_epoch()`
**expr** : active learning experiment
the experiment's object which contains
the path to data directories
**sess** : Tensorflow session
**train_inds** : array of positive integers
indices of samples inside the training
data set
**valid_ratio** : positive float (<1)
ratio of the validatio data set and the
one that is used for training
**cosnt_inds** : array of positive integerses
If given, it represents a set of samples
that are constrained to be inside the
partition that is used for fine-tuning
(and not the validation data set)
"""
# separate the training indices to validation
# and the ones to be used for fine-tuning
labels = np.loadtxt(expr.labels_file)
tuning_inds, valid_inds = NNAL_tools.test_training_part(
labels[train_inds], valid_ratio)
if const_inds:
tuning_inds = np.append(tuning_inds, const_inds)
# best accuracy is the initial accuracy
# in the beginning (like sorting)
predicts = self.predict(expr,valid_inds,sess)
best_acc = AL.get_accuracy(predicts,
expr.labels_file,
valid_inds)
# save the initial weights in the current directory
# as the temporary "best" weights so far
self.save_weights('tmp_weights.h5')
print('init. acc.: %f'% best_acc)
for i in range(expr.pars['epochs']):
self.train_graph_one_epoch(expr,tuning_inds,sess)
# validating the model after each epoch
predicts = self.predict(expr,valid_inds,sess)
acc = AL.get_accuracy(predicts,
expr.labels_file,
valid_inds)
if acc > best_acc + 1e-6:
best_acc = acc
self.save_weights("tmp_weights.h5")
if print_flag:
print('%d- (%f,%f)'% (i,acc,best_acc))
# after fix number of iterations load the best
# weights that is stored
self.load_weights("tmp_weights.h5", sess)
# delete the temporary file
os.remove("tmp_weights.h5")
def predict(self, expr,
inds,
session):
"""Generate a set of predictions for a set of
data points
The predictions will be in form of class labels
for test samples whose indices are saved in
text.txt of the given experiment.
"""
n = len(inds)
batch_size = expr.pars['batch_size']
if n > batch_size:
batch_inds = gen_batch_inds(
n, batch_size)
else:
batch_inds = [np.arange(len(n)).tolist()]
predicts = np.zeros(n)
for j in range(len(batch_inds)):
# create the 4D array of the current batch
iter_inds = inds[batch_inds[j]]
batch_of_imgs, _ = load_winds(
iter_inds,
expr.imgs_path_file,
expr.pars['target_shape'],
expr.pars['mean'])
predicts[batch_inds[j]] = session.run(
self.prediction,
feed_dict={self.x: batch_of_imgs,
self.keep_prob: 1.})
return predicts
def add_loss_grad(model, pars=[]):
"""Adding the gradient of the loss
with respect to parameters if necessary
"""
if pars==[]:
pars = tf.trainable_variables()
model.loss_grad = tf.gradients(
model.loss, pars)
def LLFC_hess(model,sess,feed_dict):
"""Explicit Hessian matrix of the loss with
respect to the last (FC) layer when the loss
is the soft-max and the last layer does not
have any additional activation except this
soft-max
"""
# input to the last layer (u)
u = sess.run(model.feature_layer,
feed_dict=feed_dict)
d = u.shape[0]
# the class probabilities
pi = sess.run(model.posteriors,
feed_dict=feed_dict)
# A(pi)
c = pi.shape[0]
repM = np.repeat(pi,c,axis=1) - np.eye(c)
A = np.diag(pi[:,0]) @ repM.T
# Hessian
H = np.zeros(((d+1)*c, (d+1)*c))
H[:c*d,:c*d] = np.kron(A, np.outer(u,u))
H[:c*d,c*d:] = np.kron(A,u)
H[c*d:,:c*d] = np.kron(A,u.T)
H[c*d:,c*d:] = A
return H
def LLFC_grads(model, sess, feed_dict, labels=None):
"""General module for computing gradients
of the log-loss with respect to parameters
of the (FC) last layer of the network
"""
# posteriors (pi)
pies = sess.run(model.posteriors,
feed_dict=feed_dict)
c,n = pies.shape
# input to the last layer (u)
U = sess.run(model.feature_layer,
feed_dict=feed_dict)
d = U.shape[0]
# term containing [pi_1.u_1 ,..., pi_1.u_d,
# pi_2.u_1 ,..., pi_2.u_d,...]
rep_pies = np.repeat(pies, d, axis=0)
rep_U = np.tile(U, (c,1))
pies_dot_U = rep_pies * rep_U
flag=0
if labels is None:
labels = sess.run(model.prediction,
feed_dict=feed_dict)
flag = 1
hot_labels = np.zeros((c,n))
for j in range(c):
hot_labels[j,labels==j]=1
# sparse term containing columns
# [0,...,0, u_1,...,u_d, 0,...,0].T
# |____ ____|
# v
# y*-th block
sparse_term = np.repeat(
hot_labels, d, axis=0) * rep_U
# dJ/dW
dJ_dW = sparse_term - pies_dot_U
# dJ/db
dJ_db = hot_labels - pies
if flag==1:
return np.concatenate(
(dJ_dW,dJ_db),axis=0), labels
else:
return np.concatenate(
(dJ_dW,dJ_db),axis=0)
def PW_LLFC_grads(model, sess,
expr,
all_padded_imgs,
img_inds,
labels):
"""Computing gradients of the log-likelihoods
with respect to the parameters of the last
layer of a given model
Given labels are not necessarily the true
labels of the indexed sampels (i.e. not
necessarily those based on the mask image
present in `all_padded_imgs`)
"""
s = len(img_inds)
n = np.sum([len(img_inds[i]) for i in range(s)])
d = model.feature_layer.shape[0].value
c = expr.nclass
all_pies = np.zeros((c,n))
all_a = np.zeros((d,n))
# loading patches
patches,_ = patch_utils.get_patches_multimg(
all_padded_imgs, img_inds,
expr.pars['patch_shape'],
expr.train_stats)
cnt=0
for i in range(s):
# posteriors pie's
pies = sess.run(model.posteriors,
feed_dict={model.x:patches[i],
model.keep_prob:1.})
all_pies[:,cnt:cnt+len(img_inds[i])] = pies
# last layer's inputs a^{n1-1}
a_s = sess.run(model.feature_layer,
feed_dict={model.x:patches[i],
model.keep_prob:1.})
all_a[:,cnt:cnt+len(img_inds[i])] = a_s
cnt += len(img_inds[i])