-
Notifications
You must be signed in to change notification settings - Fork 2
/
surgery.py
1245 lines (1044 loc) · 40.7 KB
/
surgery.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
"""
Routine for performing "DreamLearning": post-training a pre-trained neural
network with in a layer-wise fashion by inserting noise layer.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow.compat.v1.keras.backend as K
from tensorflow.compat.v1.keras.callbacks import LearningRateScheduler, TensorBoard, ModelCheckpoint
from tensorflow.compat.v1.keras.models import load_model
from tensorflow.compat.v1.keras.optimizers import SGD
from tensorflow.compat.v1.keras.metrics import top_k_categorical_accuracy
from tensorflow.compat.v1.keras.layers import Input
from tensorflow.compat.v1.keras.layers import Flatten, BatchNormalization
from tensorflow.compat.v1.keras.layers import add, subtract, multiply, dot
from tensorflow.compat.v1.keras.layers import Lambda
from tensorflow.compat.v1.keras.layers import Activation, Dropout
from tensorflow.compat.v1.keras.models import Model
from tensorflow.compat.v1.keras.losses import mean_squared_error
import tensorflow.compat.v1.keras.losses
from functools import partial, update_wrapper
import tensorflow as tf
import h5py
import yaml
import sys
import os
import re
import argparse
import time
import shutil
from tqdm import tqdm
# Initialize the Flags container
FLAGS = None
def main(argv=None):
# Set test phase
K.set_learning_phase(0)
# Set float default
K.set_floatx('float32')
handle_train_dir(FLAGS.train_dir)
_print_header()
surgery()
def surgery():
# Output file
log_file = open(os.path.join(FLAGS.train_dir, 'log'), 'w')
# Open training configuration file
with open(FLAGS.train_config_file, 'r') as yml_file:
train_config = yaml.load(yml_file, Loader=yaml.FullLoader)
batch_size = train_config['batch_size']
# Open HDF5 file containing the data set and get images and labels
hdf5_file = h5py.File(FLAGS.data_file, 'r')
if (FLAGS.seed is not None) & (FLAGS.pct_test != 1.0):
shuffle = True
else:
shuffle = False
images, labels, hdf5_aux = data_input.hdf52dask(hdf5_file, FLAGS.group,
FLAGS.chunk_size, shuffle,
FLAGS.seed, FLAGS.pct_test)
# Image parameters
with open(FLAGS.image_params_file, 'r') as yml_file:
train_image_params = yaml.load(yml_file, Loader=yaml.FullLoader)
if train_image_params['do_random_crop'] & \
(train_image_params['crop_size'] is not None):
image_shape = train_image_params['crop_size']
val_image_params = data_input.validation_image_params(**train_image_params)
# Attack parameters
with open(FLAGS.attack_params_file, 'r') as yml_file:
attack_params = yaml.load(yml_file, Loader=yaml.FullLoader)
# Load original model
model = load_model(os.path.join(FLAGS.model))
model = ensure_softmax_output(model)
model.summary()
model.summary(print_fn=lambda x: log_file.write(x + '\n'))
# Load adversarial model
if FLAGS.model_adv:
model_adv = load_model(os.path.join(FLAGS.model_adv))
else:
model_adv = model
# Compute original clean accuracy
if FLAGS.test_orig:
compute_accuracy(model, images, labels, batch_size,
val_image_params, None, log_file, orig_new='orig')
# Compute original adversarial accuracy
if FLAGS.test_adv_orig:
# White-box
compute_adv_accuracy(model, model, images, labels, batch_size,
val_image_params, attack_params, log_file,
orig_new='orig')
model = del_extra_nodes(model, verbose=0)
# Black-box
if FLAGS.model_adv:
compute_adv_accuracy(model, model_adv, images, labels, batch_size,
val_image_params, attack_params, log_file,
orig_new='orig')
# Create new model by modifying the logits
model = del_extra_nodes(model, verbose=0)
print('\nCreating new model...')
if 'bn' in train_config['key_layer']:
new_model = insert_bn(model, train_config['key_layer'],
n_bn=train_config['n_layers'])
else:
new_model = insert_layer_old(model, train_config['key_layer'])
# new_model.compile(loss='mean_squared_error', optimizer='sgd')
# Print summary architecture
if FLAGS.print_summary:
new_model.summary()
new_model.summary(print_fn=lambda x: log_file.write(x + '\n'))
# Save new model
if FLAGS.save_new:
model_filename = os.path.join(FLAGS.train_dir,
'model_new_' +
time.strftime('%a_%d_%b_%Y_%H%M%S'))
new_model.save(model_filename)
# Compute new clean accuracy
if FLAGS.test_new:
compute_accuracy(new_model, images, labels, batch_size,
val_image_params, None, log_file, orig_new='new')
# Compute new adversarial accuracy
if FLAGS.test_adv_new:
# White-box
compute_adv_accuracy(new_model, new_model, images, labels, batch_size,
val_image_params, attack_params, log_file,
orig_new='new')
new_model = del_extra_nodes(new_model, verbose=0)
# Black-box
if FLAGS.model_adv:
compute_adv_accuracy(new_model, model_adv, images, labels,
batch_size, val_image_params, attack_params,
log_file, orig_new='new')
# Close HDF5 File and log file
hdf5_file.close()
log_file.close()
# Close and remove aux HDF5 files
for f in hdf5_aux:
filename = f.filename
f.close()
os.remove(filename)
def categorical_crossentropy_from_logits(y_true, logits):
return K.categorical_crossentropy(y_true, logits, from_logits=True)
def del_extra_nodes(model, log_file=None, verbose=0):
"""
Remove all extra nodes (i.e. all but the first nodes) from all layers of
the network to avoid undesirable behaviour.
Parameters
----------
model : Keras Model
The original model
verbose : int
Verbosity. It prints and writes log messages if larger than 0.
Returns
-------
model : Keras Model
The modified model
"""
if model._inbound_nodes:
if len(model._inbound_nodes) > 1:
model._inbound_nodes = [model._inbound_nodes[0]]
if verbose > 0:
print('\nRemoved inbound nodes at model input')
if log_file:
log_file.write('\nRemoved inbound nodes at model input')
if model._outbound_nodes:
if len(model._outbound_nodes) > 1:
model._outbound_nodes = [model._outbound_nodes[0]]
if verbose > 0:
print('\nRemoved outbound nodes at model output')
if log_file:
log_file.write('\nRemoved outbound nodes at model output')
for layer in model.layers:
if layer._inbound_nodes:
if len(layer._inbound_nodes) > 1:
layer._inbound_nodes = [layer._inbound_nodes[0]]
if verbose > 0:
print('\nRemoved inbound nodes at layer %s' % layer.name)
if log_file:
log_file.write('\nRemoved inbound nodes at layer '
'%s' % layer.name)
if layer._outbound_nodes:
if len(layer._outbound_nodes) > 1:
layer._outbound_nodes = [layer._outbound_nodes[0]]
if verbose > 0:
print('\nRemoved outbound nodes at layer %s' % layer.name)
if log_file:
log_file.write('\nRemoved outbound nodes at layer '
'%s' % layer.name)
return model
def network2dict(model):
"""
Stores the inbound and outbound nodes of each layer into a dictionary.
Parameters
----------
model : Keras Model
The original model
Returns
-------
network_dict : dict
A dictionary specifying the input layers of each tensor and the output
tensors of each layer
"""
network_dict = {'model':
{'inbound_nodes': [id(node) for node in model._inbound_nodes],
'outbound_nodes': [id(node) for node in model._outbound_nodes]}}
for layer in model.layers:
network_dict.update({layer.name:
{'inbound_nodes': [id(node) for node in layer._inbound_nodes],
'outbound_nodes': [id(node) for node in layer._outbound_nodes]}})
return network_dict
def restore_nodes(model, network_dict):
"""
Restores the inbound and outbound nodes of each layer according to a
reference dictionary
Parameters
----------
model : Keras Model
The original model
network_dict : dict
A dictionary containing the nodes to be restored
Return
------
model : Keras Model
The model with restored nodes
"""
# Model inbound nodes
nodes = [id(node) for node in model._inbound_nodes]
common_nodes = set(nodes).intersection(
set(network_dict['model']['inbound_nodes']))
old_nodes = set(nodes).difference(
set(network_dict['model']['inbound_nodes']))
if len(old_nodes) > 0:
for node in model._inbound_nodes:
if id(node) in old_nodes:
model._inbound_nodes.remove(node)
if len(common_nodes) > 0:
model._inbound_nodes = [node for node in model._inbound_nodes
if id(node) in common_nodes]
# Model outbound nodes
nodes = [id(node) for node in model._outbound_nodes]
common_nodes = set(nodes).intersection(
set(network_dict['model']['outbound_nodes']))
old_nodes = set(nodes).difference(
set(network_dict['model']['outbound_nodes']))
if len(old_nodes) > 0:
for node in model._outbound_nodes:
if id(node) in old_nodes:
model._outbound_nodes.remove(node)
if len(common_nodes) > 0:
model._outbound_nodes = [node for node in model._outbound_nodes
if id(node) in common_nodes]
# Iterate over the layers
for layer in model.layers:
# Inbound nodes
nodes = [id(node) for node in layer._inbound_nodes]
common_nodes = set(nodes).intersection(
set(network_dict[layer.name]['inbound_nodes']))
old_nodes = set(nodes).difference(
set(network_dict[layer.name]['inbound_nodes']))
if len(old_nodes) > 0:
for node in layer._inbound_nodes:
if id(node) in old_nodes:
layer._inbound_nodes.remove(node)
if len(nodes) == 0:
pass
elif len(common_nodes) > 0:
layer._inbound_nodes = [node for node in layer._inbound_nodes
if id(node) in common_nodes]
else:
raise ValueError('No common inbound nodes between the dictionary '
'and the current graph at layer {}'.format(
layer.name))
# Outbound nodes
nodes = [id(node) for node in layer._outbound_nodes]
common_nodes = set(nodes).intersection(
set(network_dict[layer.name]['outbound_nodes']))
old_nodes = set(nodes).difference(
set(network_dict[layer.name]['outbound_nodes']))
if len(old_nodes) > 0:
for node in layer._outbound_nodes:
if id(node) in old_nodes:
layer._outbound_nodes.remove(node)
if len(nodes) == 0:
pass
elif len(common_nodes) > 0:
layer._outbound_nodes = [node for node in layer._outbound_nodes
if id(node) in common_nodes]
else:
raise ValueError('No common outbound nodes between the dictionary '
'and the current graph at layer {}'.format(
layer.name))
return model
def del_old_nodes(model, network_dict):
"""
Updates the inbound and outbound nodes of each layer by keeping only the
nodes that are not present in the older reference dictionary
Parameters
----------
model : Keras Model
The original model
network_dict : dict
An older reference network dictionary
Return
------
model : Keras Model
The model with updated nodes
"""
# Model inbound nodes
nodes = [id(node) for node in model._inbound_nodes]
diff_nodes = set(nodes).difference(
set(network_dict['model']['inbound_nodes']))
if len(diff_nodes) > 0:
model._inbound_nodes = [node for node in model._inbound_nodes
if id(node) in diff_nodes]
# Model outbound nodes
nodes = [id(node) for node in model._outbound_nodes]
diff_nodes = set(nodes).difference(
set(network_dict['model']['outbound_nodes']))
if len(diff_nodes) > 0:
model._outbound_nodes = [node for node in model._outbound_nodes
if id(node) in diff_nodes]
# Iterate over the layers
for layer in model.layers:
if layer.name in network_dict:
# Inbound nodes
nodes = [id(node) for node in layer._inbound_nodes]
diff_nodes = set(nodes).difference(
set(network_dict[layer.name]['inbound_nodes']))
if len(diff_nodes) > 0:
layer._inbound_nodes = [node for node in layer._inbound_nodes
if id(node) in diff_nodes]
# Outbound nodes
nodes = [id(node) for node in layer._outbound_nodes]
diff_nodes = set(nodes).difference(
set(network_dict[layer.name]['outbound_nodes']))
if len(diff_nodes) > 0:
layer._outbound_nodes = [node for node in layer._outbound_nodes
if id(node) in diff_nodes]
_update_keras_history(model)
return model
def _update_keras_history(model):
def _update_node_history(nodes):
for idx_node, node in enumerate(nodes):
if len(node.node_indices) > 0:
node.node_indices[idx_node] = idx_node
for idx_tensor, tensor in enumerate(node.input_tensors):
tensor._keras_history = (tensor._keras_history[0], idx_node,
idx_tensor)
for idx_tensor, tensor in enumerate(node.output_tensors):
tensor._keras_history = (tensor._keras_history[0], idx_node,
idx_tensor)
_update_node_history(model._inbound_nodes)
_update_node_history(model._outbound_nodes)
for layer in model.layers:
_update_node_history(layer._inbound_nodes)
_update_node_history(layer._outbound_nodes)
def del_mse_nodes(model, log_file=None, verbose=1):
"""
Remove all the node branches corresponding to the pairwise MSE layers so as
to keep the object recognition graph only.
Parameters
----------
model : Keras Model
The original model
verbose : int
Verbosity. It prints and writes log messages if larger than 0.
Returns
-------
model : Keras Model
The modified model
"""
def del_nonrelevant_nodes(model):
relevant_nodes = []
for node in model._nodes_by_depth.values():
relevant_nodes.extend(node)
for layer in model.layers:
if layer._inbound_nodes:
inbound_nodes = layer._inbound_nodes
for node in inbound_nodes:
if node not in relevant_nodes:
inbound_nodes.remove(node)
if verbose > 0:
print('Removed (mse) node {} from layer {}'.format(
node, layer.name))
if layer._outbound_nodes:
outbound_nodes = layer._outbound_nodes
for node in outbound_nodes:
if node not in relevant_nodes:
outbound_nodes.remove(node)
if verbose > 0:
print('Removed (mse) node {} from layer {}'.format(
node, layer.name))
def del_extra_nodes(layer, softmax):
if layer._outbound_nodes:
outbound_nodes = layer._outbound_nodes
for outnode in outbound_nodes:
if outnode.outbound_layer:
if not connected_to_softmax(
outnode.outbound_layer, softmax):
outbound_nodes.remove(outnode)
if verbose > 0:
print('Removed (mse) node {} from layer {}'.format(
outnode, layer.name))
elif outnode.outbound_layers:
for out_layer in outnode.outbound_layers:
if not connected_to_softmax(out_layer, softmax):
outbound_nodes.remove(outnode)
if verbose > 0:
print('Removed (mse) node {} from layer {}'.format(
innode, layer.name))
else:
pass
if layer._inbound_nodes:
inbound_nodes = layer._inbound_nodes
for innode in inbound_nodes:
if innode.inbound_layers:
for in_layer in innode.inbound_layers:
del_extra_nodes(in_layer, softmax)
else:
pass
return
def connected_to_softmax(layer, softmax):
if layer is softmax:
return True
else:
if layer._outbound_nodes:
outbound_nodes = layer._outbound_nodes
for outnode in outbound_nodes:
if outnode.outbound_layer:
return connected_to_softmax(outnode.outbound_layer,
softmax)
elif outnode.outbound_layers:
for out_layer in outnode.outbound_layers:
return connected_to_softmax(out_layer, softmax)
else:
False
else:
return False
def connected_to_input(layer, input):
if layer is input:
return True
else:
if layer._inbound_nodes:
inbound_nodes = layer._inbound_nodes
for innode in inbound_nodes:
if innode.inbound_layers:
for in_layer in innode.inbound_layers:
return connected_to_input(in_layer, input)
else:
False
else:
return False
# Delete all outputs except Softmax
if len(model.outputs) > 1:
# NOTE: These attributes (model.output_layers, model.output_names etc.)
# do not exist anymore in newer Keras and the for-loop will not work.
# Maybe the following works equivalently?
# for layer in model.outputs:
# if 'softmax' in layer.name:
# model.outputs = [layer]
# break
# else:
# pass
for layer, name, tensor, node_index, tensor_index in zip(
model.output_layers,
model.output_names,
model.outputs,
model.output_layers_node_indices,
model.output_layers_tensor_indices):
if layer.name == 'softmax':
model.output_layers = [layer]
model.output_names = [name]
model.outputs = [tensor]
model.output_layers_node_indices = [node_index]
model.output_layers_tensor_indices = [tensor_index]
break
else:
pass
# Delete node from categorical model
del_nonrelevant_nodes(model)
# NOTE: This will also fail in newer Keras because output_layers does not exist
del_extra_nodes(model.output_layers[0], model.output_layers[0])
new_model = Model(inputs=model.input, outputs=model.outputs[0])
else:
new_model = model
return new_model
def ensure_softmax_output(model):
"""
Adds a softmax layer on top of the logits layer, in case the output layer
is a logits layer.
Parameters
----------
model : Keras Model
The original model
Returns
-------
new_model : Keras Model
The modified model
"""
if 'softmax' not in model.output_names:
if 'logits' in model.output_names:
output = Activation('softmax', name='softmax')(model.output)
new_model = Model(inputs=model.input, outputs=output)
else:
raise ValueError('The output layer is neither softmax nor logits')
else:
new_model = model
return new_model
def insert_layer(model, layer_regex, insert_layer_factory,
insert_layer_name=None, position='after'):
"""
Inserts a layer before, after or replacing the layer(s) specified in the
arguments through a regular expression.
Parameters
----------
model : Keras Model
The original model
layer_regex : str
Name of the key layer, as a regular expression.
insert_layer_factory : func
Factory for the layers to be inserted
insert_layer_name : str
If None, the new layers' names will be the concatenation of the key
layer's name and the original insert_layer name. Otherwise,
insert_layer_name is used as name.
position : str
Specifies whether the new layers are inserted before, after or
replacing the key layers.
Returns
-------
Keras Model
The modified new model
"""
# Auxiliary dictionary to describe the network graph
network_dict = {'input_layers_of': {}, 'new_output_tensor_of': {}}
# Set the input layers of each layer
for layer in model.layers:
for node in layer._outbound_nodes:
layer_name = node.outbound_layer.name
if layer_name not in network_dict['input_layers_of']:
network_dict['input_layers_of'].update(
{layer_name: [layer.name]})
else:
network_dict['input_layers_of'][layer_name].append(layer.name)
# Set the output tensor of the input layer
network_dict['new_output_tensor_of'].update(
{model.layers[0].name: model.input})
# Iterate over all layers after the input
for layer in model.layers[1:]:
# Determine input tensors
layer_input = [network_dict['new_output_tensor_of'][layer_aux]
for layer_aux in network_dict['input_layers_of'][layer.name]]
if len(layer_input) == 1:
layer_input = layer_input[0]
# Insert layer if name matches the regular expression
if re.match(layer_regex, layer.name):
if position == 'replace':
x = layer_input
elif position == 'after':
x = layer(layer_input)
elif position == 'before':
pass
else:
raise ValueError('position must be: before, after or replace')
new_layer = insert_layer_factory()
if insert_layer_name:
new_layer.name = insert_layer_name
else:
new_layer.name = '{}_{}'.format(layer.name,
new_layer.name)
x = new_layer(x)
print('Layer {} inserted after layer {}'.format(new_layer.name,
layer.name))
if position == 'before':
x = layer(x)
else:
x = layer(layer_input)
# Set new output tensor (the original one, or the one of the inserted
# layer)
network_dict['new_output_tensor_of'].update({layer.name: x})
return Model(inputs=model.inputs, outputs=x)
def network2dict_old(model):
"""
Parses the architecture of a network into a dictionary, .
Parameters
----------
model : Keras Model
The original model
Returns
-------
network_dict : dict
A dictionary specifying the input layers of each tensor and the output
tensors of each layer
"""
network_dict = {'input_layers_of': {}, 'output_tensor_of': {}}
for idx, layer in enumerate(model.layers):
for node in layer._outbound_nodes:
layer_name = node.outbound_layer.name
if layer_name not in network_dict['input_layers_of']:
network_dict['input_layers_of'].update(
{layer_name: [layer.name]})
else:
network_dict['input_layers_of'][layer_name].append(layer.name)
if idx == 0:
tensor = model.input
network_dict['output_tensor_of'].update(
{layer.name: tensor})
else:
tensor = layer(tensor)
network_dict['output_tensor_of'].update({layer.name: tensor})
return network_dict
def insert_layer_old(model, key_layer_name):
"""
Insert a new layer right after the layer specified in the argument.
Parameters
----------
model : Keras Model
The original model
key_layer_name : str
Name of the layer after which the new one is inserted.
Returns
-------
new_model : Keras Model
The modified new model
"""
# Determine output layer of the model
output_layer = model.get_layer('softmax')
# Extract information from the key key layer, after which the new layer
# will be inserted
key_layer = model.get_layer(key_layer_name)
x = key_layer.output
# Determine next layer after the key layer
next_layer = key_layer._outbound_nodes[0].outbound_layer
key_layer._outbound_nodes = []
# Attach the new layers
n_bn = 1
for n in range(n_bn):
alpha = 1e9
# beta = 1.
# beta = 1000.
beta = 0.
# x = Lambda(lambda x: alpha * x + beta)(x)
# x = Lambda(lambda x: alpha * (x - K.min(x)) / (K.max(x) - K.min(x)))(x)
# x = Lambda(lambda x: K.max(x))(x)
temp = 0.001
x = Lambda(lambda x: x / temp)(x)
# x = Lambda(lambda x: alpha * K.batch_normalization(x, mean=K.mean(x, axis=0), var=K.var(x, axis=0), beta=0., gamma=1.))(x)
# x = multiply([x, x], name='multiply{}'.format(n+1))
# x = add([x, x], name='add{}'.format(n+1))
# Connect the new layers to the original 'next_layer'
next_layer._inbound_nodes = []
x = next_layer(x)
# Re-connect the rest of the layers
while next_layer is not output_layer:
next_layer = next_layer._outbound_nodes[0].outbound_layer
next_layer._inbound_nodes[0].inbound_layers[0]._outbound_nodes = []
next_layer._inbound_nodes = []
x = next_layer(x)
new_model = Model(inputs=model.input, outputs=x)
return new_model
def insert_bn(model, bn_layer_str, n_bn):
"""
Insert a chain of Batch Normalization layers right after the existing Batch
Normalization layer specified in the argument.
Parameters
----------
model : Keras Model
The original model
bn_layer_str : str
Name of the batch normalization layer after which the new one is
inserted.
n_bn : int
Number of new BatchNorm layers to be inserted
Returns
-------
new_model : Keras Model
The modified new model
"""
# Determine output layer of the model
output_layer = model.get_layer('softmax')
# Extract information from the key BN layer, after which the new BN layers
# will be inserted
bn_layer = model.get_layer(bn_layer_str)
x = bn_layer.output
w_bn = bn_layer.get_weights()
gamma = w_bn[0]
beta = w_bn[1]
# Determine next layer after the key BN layer
next_layer = bn_layer._outbound_nodes[0].outbound_layer
bn_layer._outbound_nodes = []
# Attach the new BatchNorm layers
for n in range(n_bn):
x = BatchNormalization(name= '{}_new{}'.format(bn_layer_str, n+1))(x)
# Connect the new layers to the original 'next_layer'
next_layer._inbound_nodes = []
x = next_layer(x)
# Re-connect the rest of the layers
while next_layer is not output_layer:
next_layer = next_layer._outbound_nodes[0].outbound_layer
next_layer._inbound_nodes[0].inbound_layers[0]._outbound_nodes = []
next_layer._inbound_nodes = []
x = next_layer(x)
new_model = Model(inputs=model.input, outputs=x)
# Set weights of the new batch normalization layers
for n in range(n_bn):
new_bn_layer = new_model.get_layer(bn_layer_str + '_new{}'.format(n+1))
new_bn_layer.set_weights(w_bn)
return new_model
def insert_layer_old(model, new_layer, prev_layer_name):
x = model.input
for layer in model.layers:
x = layer(x)
if layer.name == prev_layer_name:
x = new_layer(x)
new_model = Model(inputs=model.input, outputs=x)
def ablate_activations(model, layer_regex, pct_ablation, seed):
# Auxiliary dictionary to describe the network graph
network_dict = {'input_layers_of': {}, 'new_output_tensor_of': {}}
# Set the input layers of each layer
for layer in model.layers:
for node in layer._outbound_nodes:
layer_name = node.outbound_layer.name
if layer_name not in network_dict['input_layers_of']:
network_dict['input_layers_of'].update(
{layer_name: [layer.name]})
else:
network_dict['input_layers_of'][layer_name].append(layer.name)
# Set the output tensor of the input layer
network_dict['new_output_tensor_of'].update(
{model.layers[0].name: model.input})
# Iterate over all layers after the input
for layer in model.layers[1:]:
# Determine input tensors
layer_input = [network_dict['new_output_tensor_of'][layer_aux]
for layer_aux in network_dict['input_layers_of'][layer.name]]
if len(layer_input) == 1:
layer_input = layer_input[0]
x = layer(layer_input)
# Insert layer if name matches the regular expression
if re.match(layer_regex, layer.name):
ablation_layer = Dropout(
rate=pct_ablation,
noise_shape=(None, ) + tuple(np.repeat(1,
len(layer.output_shape) - 2)) + (layer.output_shape[-1], ),
seed=seed, name='{}_dropout'.format(layer.name))
x = ablation_layer(x, training=True)
if seed:
seed += 1
# Set new output tensor (the original one, or the one of the inserted
# layer)
network_dict['new_output_tensor_of'].update({layer.name: x})
return Model(inputs=model.inputs, outputs=x)
def compute_accuracy(model, images, labels, batch_size, image_params,
attack_params, log_file, orig_new):
"""
Computes the accuracy of a model, either on the clean data set.
Parameters
----------
model : Keras Model
The model on which the accuracy is computed
images : dask array
The set of images
labels : dask array
The ground truth labels
batch_size : int
Batch size
image_params: dict
Dictionary of data augmentation parameters
attack_params: dict
Dictionary of the attack parameters
log_file : File
The log file
orig_new : str
Either 'orig' or 'new'. Only used for print and log output.
"""
if orig_new == 'orig':
orig_new_str = 'original'
elif orig_new == 'new':
orig_new_str = 'new'
else:
raise NotImplementedError
print('\nComputing {} clean accuracy...'.format(orig_new_str))
# Compute accuracy
results_dict = test.test(images, labels, batch_size, model, image_params,
repetitions=1)
acc = results_dict['mean_acc'].compute()
# Print
print('{} clean accuracy: {:.4f}'.format(orig_new_str.title(), acc))
# Write to log file
log_file.write('{} clean accuracy: '
'{:.4f}\n'.format(orig_new_str.title(), acc))
def compute_adv_accuracy(model, model_adv, images, labels, batch_size,
image_params, attack_params, log_file, orig_new):
"""
Computes the accuracy of a model, either on the clean data set (if
adversarial is False), or on adversarial examples (if adversarial is True).
Parameters
----------
model : Keras Model
The model on which the accuracy is computed
model_adv : Keras Model
The model used to generate adversarial examples
images : dask array
The set of images
labels : dask array
The ground truth labels
batch_size : int
Batch size
image_params: dict
Dictionary of data augmentation parameters
attack_params: dict
Dictionary of the attack parameters
log_file : File
The log file
orig_new : str
Either 'orig' or 'new'. Only used for print and log output.