-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.py
1497 lines (1297 loc) · 57.5 KB
/
utils.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
"""
Utils functions for training deep artificial neural networks
"""
import os
import sys
import re
import shutil
import yaml
import csv
import time
import numpy as np
import dask.array as da
import h5py
import pickle
from argparse import Namespace
from functools import partial, update_wrapper
from data_input import validation_image_params, create_control_dataset
from data_input import get_generator, batch_generator
from activations import get_activations
import tensorflow.compat.v1.keras.backend as K
from tensorflow.compat.v1.keras.layers import Layer
from tensorflow.compat.v1.keras.callbacks import Callback
from tensorflow.compat.v1.keras.losses import categorical_crossentropy
import tensorflow.compat.v1 as tf
class TrainingProgressLogger():
def __init__(self, output_file, model, config, images, labels, layers=[],
every_iter=None, every_epoch=None, **kwargs):
self.output_file = open(output_file, 'w')
self.model = model
if layers:
self.layers = layers
else:
self.layers = config.logger.layers
self.layers_dim = []
if every_iter:
self.every_iter = every_iter
else:
self.every_iter = config.logger.every_iter
if every_epoch:
self.every_epoch = every_epoch
else:
self.every_epoch = config.logger.every_epoch
self.images = images
self.labels = labels
self.activation_functions = []
self.activations = []
# Create log dataset
daug_params_file = get_daug_scheme_path(config.logger.daug,
config.data.data_file)
daug_params = yaml.load(open(daug_params_file, 'r'),
Loader=yaml.FullLoader)
nodaug_params_file = get_daug_scheme_path(config.logger.daug,
config.data.data_file)
self.nodaug_params = validation_image_params(config.daug.nodaug,
**daug_params)
self.images, self.labels = create_control_dataset(
images, labels, daug_params, self.nodaug_params,
n_per_image=config.logger.n_per_image,
n_per_class=config.logger.n_per_class,
chunk_size=config.logger.chunk_size,
seed=config.logger.seed)
self.n_images = self.images.shape[0]
# Setup data generator
image_gen = get_generator(images, **self.nodaug_params)
self.batch_gen = batch_generator(image_gen, self.images, self.labels,
config.logger.batch_size,
aug_per_im=1, shuffle=False)
# Determine activation functions
for layer_name in self.layers:
layer = model.get_layer(layer_name)
self.layers_dim.append(np.prod(layer.output_shape[1:]))
self.activation_functions.append(
K.function([model.input, K.learning_phase()],
[layer.output]))
# setup CSV writer
self.writer = csv.writer(self.output_file, delimiter=',',
quotechar='"', quoting=csv.QUOTE_MINIMAL)
# Write headers
headers = model.metrics_names[:]
for layer_name, layer_dim in zip(self.layers, self.layers_dim):
layer_header = ['{}_dim{:05d}_data{:05d}'.format(
layer_name, dim, x) for x in range(self.n_images)
for dim in range(layer_dim)]
headers.extend(layer_header)
self.writer.writerow(headers)
def log(self, metrics):
row = list(list(zip(*metrics))[1])
for activations in self.activations:
row.extend(activations)
self.writer.writerow(row)
self.activations = []
def get_activations(self):
for activation_function in self.activation_functions:
activations = get_activations(activation_function, self.batch_gen)
self.activations.append(
da.ravel(da.squeeze(activations)).compute().tolist())
def close(self):
self.output_file.close()
def pairwise_loss(y_true, y_pred):
"""
Computes the relative loss (MSE) of a set of relevant pairs of samples,
determined by the mask y_true.
Parameters
----------
y_true : ndarray
Boolean mask to determine the relevant pairs of samples. For image
identification, these are the samples that belong to the same source
image.
y_pred : ndarray
Squared matrix of pairwise losses, typically the mean squared error
(MSE) for image identification.
Returns
-------
Relative mean loss of the relevant pairs, that is the mean loss of the
relevant pairs normalized by the mean loss of all pairs.
"""
return K.sum(y_true * y_pred) / K.sum(y_true) / (K.mean(y_pred) + K.epsilon())
def daug_inv_loss(y_true, y_pred):
"""
Computes the relative loss (MSE) of a set of relevant pairs of samples,
determined by the mask y_true.
Parameters
----------
y_true : ndarray
Boolean mask to determine the relevant pairs of samples. For image
identification, these are the samples that belong to the same source
image.
y_pred : ndarray
Squared matrix of pairwise losses, typically the mean squared error
(MSE) for image identification.
Returns
-------
Relative mean loss of the relevant pairs, that is the mean loss of the
relevant pairs normalized by the mean loss of all pairs.
"""
y_pred = y_pred[:, :, 0]
y_daug = y_true[:, :, 0]
y_class = y_true[:, :, 1]
return (K.sum(y_daug * y_pred) / K.sum(y_daug)) / \
(K.sum(y_class * y_pred) / K.sum(y_class))
def invariance_loss(y_true, y_pred):
"""
Computes the relative loss (MSE) of a set of relevant pairs of samples,
determined by the mask y_true.
Parameters
----------
y_true : ndarray
Boolean mask to determine the relevant pairs of samples. For image
identification, these are the samples that belong to the same source
image.
y_pred : ndarray
Squared matrix of pairwise losses, typically the mean squared error
(MSE) for image identification.
Returns
-------
Relative mean loss of the relevant pairs, that is the mean loss of the
relevant pairs normalized by the mean loss of all pairs.
"""
y_pred = y_pred[:, :, 0]
y_rel = y_true[:, :, 0]
y_all = y_true[:, :, 1]
return (K.sum(y_rel * y_pred) / K.sum(y_rel)) / \
(K.sum(y_all * y_pred) / K.sum(y_all))
def weighted_loss(loss_function, weight):
if loss_function == 'categorical_crossentropy':
loss_function = categorical_crossentropy
def loss(y_true, y_pred):
return loss_function(y_true, y_pred) * weight
return loss
def mean_loss_mod(y_true, y_pred):
"""
Simply returns the mean of y_pred across the batch, regardless of y_true.
Parameters
----------
y_true : ndarray
Irrelevant.
y_pred : ndarray
Irrelevant
Returns
-------
The mean of y_pred
"""
y_true_mod = y_true
y_true_mod[:, :5]
return K.mean(y_true_mod)
def mean_loss(y_true, y_pred):
"""
Simply returns the mean of y_pred across the batch, regardless of y_true.
Parameters
----------
y_true : ndarray
Irrelevant.
y_pred : ndarray
Irrelevant
Returns
-------
The mean of y_pred
"""
return K.mean(y_pred)
def sum_inv_losses(losses, loss_weights):
def inv_sum(y_true, y_pred):
mses = []
for loss, weight in zip(losses.items(), loss_weights.items()):
if ('inv' in loss[0]) & (loss[0] == weight[0]):
mses.append(weight[1] * loss[1](y_true, y_pred))
return K.sum(mses)
return inv_sum
def handle_train_dir(train_dir):
"""
Checks if the training directory exists and creates it or overwrites it
according to the user input.
Parameters
----------
train_dir : str
Training directory, where the checkpoint and other files are stored
"""
if os.path.exists(train_dir):
print('Train directory %s already exists!' % train_dir)
if _confirm('Do you want to overwrite its contents? [Y/N]: '):
shutil.rmtree(train_dir)
os.makedirs(train_dir)
else:
if _confirm('Do you want to create the new files for alongside the'
'old ones? [Y/N]: '):
pass
else:
raise ValueError('Cannot establish a train directory')
else:
os.makedirs(train_dir)
def prepare_train_config(train_config, flags):
"""
Modifies the input train configuration file according to the arguments of
the current execution. The specifications passed as arguments prevail over
the settings from the configuration file. Not every single field can be
modified from the flags.
Parameters
----------
train_config: dict
The train configuration dictionary, read from a YAML file
flags : argparse.Namespace
The flag aguments of the execution
Return
------
train_config : dict
The updated configuration
"""
# Get data set
if flags.data_file is None:
flags.data_file = train_config['data']['data_file']
if 'cifar' in flags.data_file:
dataset = 'cifar'
elif 'mnist_rot' in flags.data_file:
dataset = 'mnist_rot'
elif 'mnist' in flags.data_file:
dataset = 'mnist'
elif 'tinyimagenet' in flags.data_file:
dataset = 'tinyimagenet'
elif 'imagenet' in flags.data_file:
dataset = 'imagenet'
elif 'emotion' in flags.data_file:
dataset = 'emotion'
elif 'catsndogs' in flags.data_file:
dataset = 'catsndogs'
elif 'synthetic' in flags.data_file:
dataset = 'synthetic'
elif 'niko92' in flags.data_file:
dataset = 'niko92'
elif 'kamitani1200' in flags.data_file:
dataset = 'kamitani1200'
else:
raise NotImplementedError()
# Set data configuration
if 'data' not in train_config:
train_config.update({'data': {
'data_file': flags.data_file,
'group_tr': flags.group_tr,
'group_val': flags.group_val,
'labels_id': flags.labels_id,
'pct_tr': flags.pct_tr,
'pct_val': flags.pct_val,
'shuffle_train_val': flags.shuffle_train_val,
'chunk_size': flags.chunk_size}})
if flags.data_file:
train_config['data']['data_file'] = flags.data_file
if flags.group_tr:
train_config['data']['group_tr'] = flags.group_tr
if flags.group_val:
train_config['data']['group_val'] = flags.group_val
if flags.labels_id:
train_config['data']['labels_id'] = flags.labels_id
if flags.pct_tr:
train_config['data']['pct_tr'] = flags.pct_tr
if flags.pct_val:
train_config['data']['pct_val'] = flags.pct_val
if flags.shuffle_train_val:
train_config['data']['shuffle_train_val'] = flags.shuffle_train_val
if train_config['data']['group_val']:
train_config['data']['pct_val'] = None
# Set data augmentaiton configuration
if 'daug' not in train_config:
train_config.update({'daug': {
'daug_params_file': os.path.join(
'daug_schemes', dataset, flags.daug_params),
'aug_per_img_tr': flags.aug_per_img_tr,
'aug_per_img_val': flags.aug_per_img_val}})
train_config['daug'].update({'nodaug': os.path.join(
'daug_schemes', dataset, 'nodaug.yml')})
if flags.daug_params:
train_config['daug']['daug_params_file'] = os.path.join(
'daug_schemes', dataset, flags.daug_params)
else:
train_config['daug']['daug_params_file'] = os.path.join(
'daug_schemes', dataset,
train_config['daug']['daug_params_file'])
if flags.aug_per_img_tr:
train_config['daug']['aug_per_img_tr'] = flags.aug_per_img_tr
if flags.aug_per_img_val:
train_config['daug']['aug_per_img_val'] = flags.aug_per_img_val
# Set seed configuration
if 'seeds' not in train_config:
train_config.update({'seeds': {
'tf': flags.seed_tf,
'np': flags.seed_np,
'daug': flags.seed_daug,
'batch_shuffle': flags.seed_batch_shuffle,
'train_val': flags.seed_train_val}})
if flags.seed_tf:
train_config['seeds']['tf'] = flags.seed_tf
if flags.seed_np:
train_config['seeds']['np'] = flags.seed_np
if flags.seed_daug:
train_config['seeds']['daug'] = flags.seed_daug
if flags.seed_batch_shuffle:
train_config['seeds']['batch_shuffle'] = flags.seed_batch_shuffle
if flags.seed_train_val:
train_config['seeds']['train_val'] = flags.seed_train_val
# Set metrics
if flags.metrics:
train_config['metrics'] = flags.metrics
# Set train hyperparameters
if flags.epochs is not None:
train_config['train']['epochs'] = flags.epochs
if flags.batch_size:
train_config['train']['batch_size']['tr'] = flags.batch_size
if flags.learning_rate:
train_config['train']['lr']['init_lr'] = flags.learning_rate
# Set invariance parameters files
if flags.force_invariance:
train_config['optimizer']['invariance'] = True
else:
train_config['optimizer']['invariance'] = False
if flags.daug_invariance_params:
train_config['optimizer']['daug_invariance_params_file'] = \
os.path.join('invariance_params', flags.daug_invariance_params)
elif 'daug_invariance_params_file' in train_config['optimizer']:
train_config['optimizer']['daug_invariance_params_file'] = \
os.path.join(
'invariance_params',
train_config['optimizer']['daug_invariance_params_file'])
else:
pass
if flags.class_invariance_params:
train_config['optimizer']['class_invariance_params_file'] = \
os.path.join('invariance_params',
flags.class_invariance_params)
elif 'class_invariance_params_file' in train_config['optimizer']:
train_config['optimizer']['class_invariance_params_file'] = \
os.path.join(
'invariance_params',
train_config['optimizer']['class_invariance_params_file'])
else:
pass
# Set network parameters
if flags.network_name:
train_config['network']['name'] = flags.network_name
if flags.weight_decay:
train_config['network']['reg']['weight_decay'] = flags.weight_decay
if flags.dropout:
if isinstance(flags.dropout, bool):
train_config['network']['reg']['dropout'] = True
elif isinstance(flags.dropout, float):
train_config['network']['reg']['dropout'] = flags.dropout
else:
pass
if flags.no_dropout:
train_config['network']['reg']['dropout'] = False
if flags.batch_norm:
train_config['network']['batch_norm'] = True
if flags.no_batch_norm:
train_config['network']['batch_norm'] = False
# Set simulation parameters
if flags.simulate_norep_samples:
train_config['train']['simulate']['norep_samples'] = True
if flags.simulate_rep_samples:
train_config['train']['simulate']['rep_samples'] = \
flags.simulate_rep_samples
if flags.simulate_bs_lr:
train_config['train']['simulate']['bs_lr'] = flags.simulate_bs_lr
return train_config
def prepare_test_config(test_config, flags):
"""
Prepares a generic test configuration dictionary for use and modifies the
configuration according to the arguments passed as flags.
Parameters
----------
test_config: dict
The test configuration dictionary, read from a YAML file
flags : argparse.Namespace
The flag aguments of the execution
Return
------
test_config : dict
The updated configuration
"""
def _add_recursively(config_dict, metrics, dataset, root='daug_schemes'):
"""
Recursively adds or updates value of the configuration dictionary:
- metrics
- Read the data augmentation configuration dictionaries
Parameters
----------
config_dict : dict
metrics : list str
The list of metrics to compute
dataset : str
The name of the data set, which must be the name of a folder within
root.
root : str
The root directory where the data augmentation configuration files
are stored. It must contain a folder named dataset.
Return
------
config_dict : dict
The modified dictionary
"""
for k, v in config_dict.items():
if 'daug_params' in k:
filename = os.path.join(root, dataset, v)
with open(filename, 'r') as yml_file:
config_dict[k]= yaml.load(yml_file, Loader=yaml.FullLoader)
elif metrics is not None and k == 'metrics':
config_dict[k] = metrics
elif isinstance(v, dict):
_add_recursively(v, metrics, dataset, root)
else:
pass
return config_dict
# Get data set
if 'cifar' in flags.data_file:
dataset = 'cifar'
elif 'mnist_rot' in flags.data_file:
dataset = 'mnist_rot'
elif 'mnist' in flags.data_file:
dataset = 'mnist'
elif 'tinyimagenet' in flags.data_file:
dataset = 'tinyimagenet'
elif 'imagenet' in flags.data_file:
dataset = 'imagenet'
elif 'emotion' in flags.data_file:
dataset = 'emotion'
elif 'catsndogs' in flags.data_file:
dataset = 'catsndogs'
elif 'synthetic' in flags.data_file:
dataset = 'synthetic'
else:
raise NotImplementedError()
# Add performance on original images
if 'test' in test_config and \
'orig' not in test_config['test'] and \
hasattr(flags, 'orig') and \
flags.orig == True:
test_config['test'].update({'orig': {'daug_params': 'nodaug.yml',
'metrics': flags.metrics}})
# Add test data augmentation performance
if hasattr(flags, 'daug_schemes') and flags.daug_schemes:
if 'test' in test_config and \
'daug' not in test_config['test']:
test_config['test'].update({'daug': {}})
for scheme in flags.daug_schemes:
if scheme not in test_config['test']['daug']:
test_config['test']['daug'].update(
{scheme: {'daug_params': '{}.yml'.format(scheme),
'repetitions': flags.daug_rep,
'metrics': flags.metrics}})
# Edit adversarial robustness configuration
if hasattr(flags, 'adv_pct_data') and flags.adv_pct_data and \
flags.adv_pct_data < 1.:
adv_shuffle = True
adv_shuffle_seed = flags.adv_shuffle_seed
else:
adv_shuffle = False
adv_shuffle_seed = 0
if hasattr(flags, 'adv_model') and flags.adv_model:
if 'adv' not in test_config:
test_config.update({'adv':
{'attacks': flags.adv_attacks,
'daug_params': 'nodaug.yml',
'black_box_model': flags.adv_model,
'pct_data': flags.adv_pct_data,
'shuffle_data': adv_shuffle,
'shuffle_seed': adv_shuffle_seed}})
else:
test_config['adv'].update(
{'black_box_model': flags.adv_model})
if hasattr(flags, 'adv_attacks') and flags.adv_attacks:
if 'adv' not in test_config:
test_config.update({'adv':
{'attacks': flags.adv_attacks,
'daug_params': 'nodaug.yml',
'black_box_model': flags.adv_model,
'pct_data': flags.adv_pct_data,
'shuffle_data': adv_shuffle,
'shuffle_seed': adv_shuffle_seed}})
else:
test_config['adv'].update({'attacks': flags.adv_attacks})
# Read attack configuration files
if 'adv' in test_config:
flags.adv_attacks = test_config['adv']['attacks']
del test_config['adv']['attacks']
test_config['adv'].update({'attacks': {}})
for attack_file in flags.adv_attacks:
with open(attack_file, 'r') as yml_file:
attack = yaml.load(yml_file, Loader=yaml.FullLoader)
test_config['adv']['attacks'].update({attack_file: attack})
# Set percentage of data to compute adversarial robustness
if hasattr(flags, 'adv_pct_data') and flags.adv_pct_data:
test_config['adv'].update({'pct_data': flags.adv_pct_data})
# Edit ablation configuration
if hasattr(flags, 'ablation_pct') and flags.ablation_pct:
if 'ablation' not in test_config:
test_config.update({'ablation': {'pct': flags.ablation_pct,
'daug_params': 'nodaug.yml',
'metrics': flags.metrics,
'repetitions': 1,
'seed': 19}})
else:
test_config['ablation'].update({'pct': flags.ablation_pct})
if hasattr(flags, 'ablation_rep') and flags.ablation_rep:
if flags.ablation_rep > 1:
flags.ablation_seed = None
if 'ablation' not in test_config:
test_config.update({'ablation': {'pct': [0.5],
'layer_regexflags.':
layer_regex_ablation,
'daug_params': 'nodaug.yml',
'metrics': flags.metrics,
'repetitions': flags.ablation_rep,
'seed': flags.ablation_seed}})
else:
test_config['ablation'].update({'repetitions': flags.ablation_rep,
'seed': flags.ablation_seed})
if hasattr(flags, 'metrics') and len(flags.metrics) > 0:
metrics = flags.metrics
else:
metrics = None
# Edit daug_params values
test_config = _add_recursively(test_config, metrics, dataset)
return test_config
def get_daug_scheme_path(daug_scheme, data_file, root='./'):
# Get data set
if 'cifar' in data_file:
dataset = 'cifar'
elif 'mnist_rot' in data_file:
dataset = 'mnist_rot'
elif 'mnist' in data_file:
dataset = 'mnist'
elif 'tinyimagenet' in data_file:
dataset = 'tinyimagenet'
elif 'imagenet' in data_file:
dataset = 'imagenet'
elif 'synthetic' in data_file:
dataset = 'synthetic'
elif 'niko92' in data_file:
dataset = 'niko92'
elif 'kamitani1200' in data_file:
dataset = 'kamitani1200'
else:
raise NotImplementedError()
daug_scheme_path = os.path.join(root, 'daug_schemes', dataset,
daug_scheme)
return daug_scheme_path
def handle_metrics(metrics):
metric_funcs = []
metric_names = []
for metric in metrics:
if metric.lower() in ('accuracy', 'acc', 'categorical_accuracy'):
from tensorflow.compat.v1.keras.metrics import categorical_accuracy
metric_funcs.append(categorical_accuracy)
metric_names.append('acc')
elif metric.lower() in ('mae', 'mean_absolute_error'):
from tensorflow.compat.v1.keras.losses import mean_absolute_error
metric_funcs.append(mean_absolute_error)
metric_names.append('mae')
elif metric.lower().startswith('top'):
k = int(metric[-1])
from tensorflow.compat.v1.keras.metrics import top_k_categorical_accuracy
metric_funcs.append(update_wrapper(
partial(top_k_categorical_accuracy, k=k),
top_k_categorical_accuracy))
metric_names.append('top{:d}'.format(k))
else:
raise NotImplementedError()
return metric_funcs, metric_names
def change_metrics_names(model, invariance):
model.metrics_names = [s.replace('softmax', 'cat') for s
in model.metrics_names]
model.metrics_names = [s.replace('categorical_accuracy', 'acc') for s
in model.metrics_names]
# model.metrics_names = [s.replace('top_k', 'top{}'.format(m.keywords['k'])) if hasattr(m, 'keywords') else s for s, m in zip(model.metrics_names, model.metrics)]
if not invariance:
model.metrics_names = ['cat_{}'.format(s) for s in model.metrics_names]
return model
def sel_metrics(metrics_names, metrics, no_mean, no_val_daug=False,
metrics_cat=[]):
metrics_progbar = list(zip(metrics_names, metrics))
for metric_name, metric in zip(metrics_names, metrics):
if no_mean and 'mean_' in metric_name:
metrics_progbar.remove((metric_name, metric))
elif no_val_daug and 'val_daug_' in metric_name:
metrics_progbar.remove((metric_name, metric))
elif metric_name in metrics_cat:
metrics_progbar.remove((metric_name, metric))
else:
pass
return metrics_progbar
def dict2namespace(data_dict):
"""
Recursively converts a dictionary and its internal dictionaries into an
argparse.Namespace
Parameters
----------
data_dict : dict
The input dictionary
Return
------
data_namespace : argparse.Namespace
The output namespace
"""
for k, v in data_dict.items():
if isinstance(v, dict):
data_dict[k] = dict2namespace(v)
else:
pass
data_namespace = Namespace(**data_dict)
return data_namespace
def namespace2dict(data_namespace):
"""
Recursively converts a dictionary and its internal dictionaries into an
argparse.Namespace
Parameters
----------
data_dict : dict
The input dictionary
Return
------
data_namespace : argparse.Namespace
The output namespace
"""
data_dict = {}
for k in vars(data_namespace):
if isinstance(getattr(data_namespace, k), Namespace):
data_dict.update({k: namespace2dict(getattr(data_namespace, k))})
else:
data_dict.update({k: getattr(data_namespace, k)})
return data_dict
def numpy_to_python(results_dict):
"""
Recursively converts the numpy types into native Python types in order to
enable proper dumping into YAML files:
Parameters
----------
results_dict : dict
The input dictionary
Return
------
results_dict : dict
The modified dictionary
"""
def convert(v):
if isinstance(v, np.ndarray):
if np.ndim(v) == 1:
return v.tolist()
elif isinstance(v, (int, np.integer)):
return int(v)
elif isinstance(v, (float, np.float, np.float32)):
return float(v)
elif isinstance(v, list):
for idx, el in enumerate(v):
v[idx] = convert(el)
return v
elif isinstance(v, dict):
return numpy_to_python(v)
elif isinstance(v, Namespace):
return numpy_to_python(vars(v))
else:
return v
for k, v in results_dict.items():
if isinstance(v, dict):
numpy_to_python(v)
elif isinstance(v, Namespace):
numpy_to_python(vars(v))
else:
results_dict[k] = convert(v)
return results_dict
def _confirm(message):
"""
Ask user to enter Y or N (case-insensitive)
Parameters
----------
message : str
Message to ask for confirmation
Returns
-------
answer : bool
True if the answer is Y.
"""
answer = ""
while answer not in ["y", "n"]:
try: # Python 2.x
answer = raw_input(message).lower()
except NameError: # Python 3.x
answer = input(message).lower()
return answer == "y"
def print_flags(flags, write_file=True):
"""
Prints the flag arguments of the current execution
Parameters
----------
flags : argparse.Namespace
Collection of flags (arguments)
"""
print('')
print('--------------------------------------------------')
print('Running %s' % sys.argv[0])
print('')
print('FLAGS:')
for f in vars(flags):
print('{}: {}'.format(f, getattr(flags, f)))
print('')
def write_flags(flags, write_file=True):
"""
Writes the flag arguments of the current execution into a txt file.
Parameters
----------
flags : argparse.Namespace
Collection of flags (arguments)
"""
output_file = os.path.join(flags.train_dir, 'flags_' +
time.strftime('%a_%d_%b_%Y_%H%M%S'))
with open(output_file, 'w') as file:
file.write('FLAGS:\n')
for f in vars(flags):
file.write('{}: {}\n'.format(f, getattr(flags, f)))
def print_test_results(d):
if 'test' in d:
sys.stdout.write('\nTest performance:\n')
test_dict = d['test']
if 'orig' in test_dict:
sys.stdout.write('\n\tOriginal images:\n')
for metric, metric_dict in test_dict['orig']['metrics'].items():
sys.stdout.write('\t\t{}: {:.4f}\n'.format(
metric, metric_dict['mean']))
if 'daug' in test_dict:
sys.stdout.write('\n\tData augmentation:\n')
for scheme, scheme_dict in test_dict['daug'].items():
sys.stdout.write('\t\t{}:\n'.format(scheme))
for metric, metric_dict in scheme_dict['metrics'].items():
sys.stdout.write('\t\t\t{} - mean: {:.4f}\n'.format(
metric, metric_dict['mean']))
sys.stdout.write('\t\t\t{} - median: {:.4f}\n'.format(
metric, metric_dict['median']))
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t\t{} per rep: '.format(metric))
for acc in metric_dict['per_rep']:
sys.stdout.write('{:.4f} '.format(acc))
sys.stdout.write('\n')
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t\tmean std predictions: '
'{:.4f}\n'.format(
scheme_dict['mean_std_predictions']))
if 'train' in d:
sys.stdout.write('\nTrain performance:\n')
train_dict = d['train']
if 'orig' in train_dict:
sys.stdout.write('\n\tOriginal images:\n')
for metric, metric_dict in train_dict['orig']['metrics'].items():
sys.stdout.write('\t\t{}: {:.4f}\n'.format(
metric, metric_dict['mean']))
if 'daug' in train_dict:
sys.stdout.write('\n\tData augmentation:\n')
for scheme, scheme_dict in train_dict['daug'].items():
sys.stdout.write('\t\t{}:\n'.format(scheme))
for metric, metric_dict in scheme_dict['metrics'].items():
sys.stdout.write('\t\t\t{} - mean: {:.4f}\n'.format(
metric, metric_dict['mean']))
sys.stdout.write('\t\t\t{} - median: {:.4f}\n'.format(
metric, metric_dict['median']))
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t\t{} per rep: '.format(metric))
for acc in metric_dict['per_rep']:
sys.stdout.write('{:.4f} '.format(acc))
sys.stdout.write('\n')
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t\tmean std predictions: '
'{:.4f}\n'.format(
scheme_dict['mean_std_predictions']))
if 'ablation' in d:
if 'test' in d['ablation']:
sys.stdout.write('\nRobustness to ablation of units '
'(test data):\n')
for pct in sorted(d['ablation']['test'].keys()):
pct_dict = d['ablation']['test'][pct]
sys.stdout.write('\t{} % of the units:\n'.format(100 * pct))
for metric, metric_dict in pct_dict['metrics'].items():
sys.stdout.write('\t\t{} - mean: {:.4f}\n'.format(
metric, metric_dict['mean']))
sys.stdout.write('\t\t{} - std: {:.4f}\n'.format(
metric, metric_dict['std']))
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t{} per rep: '.format(metric))
for acc in metric_dict['per_rep']:
sys.stdout.write('{:.4f} '.format(acc))
sys.stdout.write('\n')
if 'train' in d['ablation']:
sys.stdout.write('\nRobustness to ablation of units '
'(train data):\n')
for pct in sorted(d['ablation']['train'].keys()):
pct_dict = d['ablation']['train'][pct]
sys.stdout.write('\t{} % of the units:\n'.format(100 * pct))
for metric, metric_dict in pct_dict['metrics'].items():
sys.stdout.write('\t\t{} - mean: {:.4f}\n'.format(
metric, metric_dict['mean']))
sys.stdout.write('\t\t{} - std: {:.4f}\n'.format(
metric, metric_dict['std']))
if len(metric_dict['per_rep']) > 1:
sys.stdout.write('\t\t{} per rep: '.format(metric))
for acc in metric_dict['per_rep']:
sys.stdout.write('{:.4f} '.format(acc))
sys.stdout.write('\n')
if 'adv' in d:
sys.stdout.write('\nRobustness to adversarial examples '
'- white box attacks:\n')
for attack, attack_dict in d['adv']['white_box'].items():
sys.stdout.write('\tAttack: {}:\n'.format(attack))
if 'mean_acc' in attack_dict:
sys.stdout.write('\t\tmean acc: {:.4f}\n'.format(
attack_dict['mean_acc']))
sys.stdout.write('\t\tmean mse: {:.4f}\n'.format(
attack_dict['mean_mse']))
else:
for eps, eps_dict in sorted(
d['adv']['white_box'][attack].items()):
sys.stdout.write('\t\tepsilon = {}:\n'.format(eps))
sys.stdout.write('\t\t\tmean acc: {:.4f}\n'.format(
eps_dict['mean_acc']))
sys.stdout.write('\t\t\tmean mse: {:.4f}\n'.format(
eps_dict['mean_mse']))
if 'black_box' in d['adv']: