-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvnet.py
2577 lines (2260 loc) · 128 KB
/
convnet.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
"""
Build convolutional neural networks using TensorFlow low-level APIs.
"""
import time
import warnings
from abc import abstractmethod
import tensorflow.compat.v1 as tf
import tensorflow.contrib as tf_contrib
import numpy as np
from contextlib import nullcontext
class ConvNet(object):
def __init__(self, input_shape, num_classes, loss_weights=None, session=None, model_scope=None,
companion_networks=None, next_elements=None, backbone_only=False, auto_build=True, **kwargs):
"""
:param input_shape: list or tuple, network input size.
:param num_classes: int, number of classes.
:param loss_weights: list or tuple, weighting factors for softmax losses.
:param session: tf.Session, TensorFlow session. If None, a new session is created.
:param model_scope: string, variable scope for the model. None for no scope.
:param companion_networks: dict, other ConvNets related to the model.
:param next_elements: dict, iterator.get_next elements for each device. If None, new elements are created.
:param backbone_only: bool, whether to build backbone (feature extractor) only.
:param auto_build: bool, whether to call build() at init.
:param kwargs: dict, (hyper)parameters.
"""
self._block_list = []
self._curr_block = None # Use this instance to group variables into blocks
self._custom_feed_dict = dict() # feed_dict for custom placeholders {placeholder: value}
if session is None:
graph = tf.get_default_graph()
config = tf.ConfigProto()
config.intra_op_parallelism_threads = kwargs.get('num_parallel_calls', 0)
config.inter_op_parallelism_threads = 0
config.gpu_options.force_gpu_compatible = True
config.allow_soft_placement = False
config.gpu_options.allow_growth = True
# config.gpu_options.per_process_gpu_memory_fraction = 0.7 # FIXME
self._session = tf.Session(graph=graph, config=config) # TF main session
else:
self._session = session
self._top_scope = tf.get_variable_scope()
assert len(input_shape) == 3, 'input_size must contain 3D size'
self._input_size = input_shape # Size of the network input (i.e., the first convolution layer).
self._num_classes = num_classes
self._loss_weights = loss_weights # Weight values for the softmax losses of each class
self._model_scope = model_scope
if next_elements is None:
self._next_elements = dict()
else:
self._next_elements = dict(next_elements)
if companion_networks is None:
self._companion_networks = dict()
else:
self._companion_networks = dict(companion_networks)
self._backbone_only = backbone_only
self._parameters = kwargs
self._dtype = tf.float16 if kwargs.get('half_precision', False) else tf.float32
self._channel_first = kwargs.get('channel_first', False)
self._argmax_output = kwargs.get('argmax_output', False)
self._cpu_offset = kwargs.get('cpu_offset', 0)
self._gpu_offset = kwargs.get('gpu_offset', 0)
num_gpus = kwargs.get('num_gpus', None)
if num_gpus is None:
num_gpus = 1 if tf.test.is_gpu_available(cuda_only=True) else 0
if num_gpus == 0: # No GPU available
self._num_devices = 1
self._compute_device = 'cpu'
self._device_offset = self.cpu_offset
else:
self._num_devices = num_gpus
self._compute_device = 'gpu'
self._device_offset = 0
param_device = kwargs.get('param_device', None)
if param_device is None:
dev = '/gpu:' if num_gpus == 1 else '/cpu:'
self._param_device = dev + str(self.device_offset)
else:
if 'gpu' in param_device.lower():
dev = '/gpu:'
dev_offset = 0
else:
dev = '/cpu:'
dev_offset = self.cpu_offset
if param_device[-1] in '0123456789':
self._param_device = dev + param_device[-1]
else:
self._param_device = dev + str(dev_offset)
self._padded_size = np.round(np.array(self.input_size[0:2])*(1.0 + kwargs.get('zero_pad_ratio', 0.0)))
self.pad_value = kwargs.get('pad_value', 0.5)
self._dropout_weights = kwargs.get('dropout_weights', False)
self._dropout_features = kwargs.get('dropout_features', True)
self._blocks_to_train = kwargs.get('blocks_to_train', None)
self._update_batch_norm = kwargs.get('update_batch_norm', None)
self._moving_average_decay = kwargs.get('moving_average_momentum', kwargs.get('moving_average_decay', 0.99))
self._batch_norm_decay = kwargs.get('batch_norm_momentum', kwargs.get('batch_norm_decay', 0.99))
self._feature_reduction = kwargs.get('feature_reduction_factor', 0)
self.handles = []
self.X_in = []
self.Y_in = []
self.Xs = []
self.Ys = []
self.preds = []
self.valid_masks = []
self.losses = []
self.gcams = []
self.bytes_in_use = []
self._flops = 0
self._params = 0
self._nodes = 0
self._layer_info = []
self.dicts = []
self._update_ops = []
self._init_ops = []
if auto_build:
self.build()
def build(self):
kwargs = self._parameters
with tf.variable_scope(self.model_scope) if self.model_scope is not None else nullcontext():
with tf.device(self.param_device):
with tf.variable_scope('conditions'):
if self.companion_networks:
net = list(self.companion_networks.values())[0]
self.is_train = net.is_train
self.monte_carlo = net.monte_carlo
self.augmentation = net.augmentation
self.total_steps = net.total_steps
else:
self.is_train = tf.placeholder(tf.bool, shape=[], name='is_train')
self.monte_carlo = tf.placeholder(tf.bool, shape=[], name='monte_carlo')
self.augmentation = tf.placeholder(tf.bool, shape=[], name='augmentation')
self.total_steps = tf.placeholder(tf.int64, shape=[], name='total_steps')
with tf.variable_scope('calc'):
self.global_step = tf.train.get_or_create_global_step()
global_step = tf.cast(self.global_step, dtype=tf.float32)
self.dropout_rate = tf.cond(tf.math.logical_or(self.is_train, self.monte_carlo),
lambda: tf.constant(kwargs.get('dropout_rate', 0.0), dtype=self.dtype),
lambda: tf.constant(0.0, dtype=self.dtype, name='0'),
name='dropout_rate')
if self.dropout_weights:
self.dropout_rate_weights = self.dropout_rate
else:
self.dropout_rate_weights = tf.constant(0.0, dtype=self.dtype, name='0')
if self.dropout_features:
self.dropout_rate_features = self.dropout_rate
else:
self.dropout_rate_features = tf.constant(0.0, dtype=self.dtype, name='0')
if kwargs.get('zero_center', True):
self.image_mean = tf.constant(kwargs.get('image_mean', 0.5), dtype=tf.float32,
name='image_mean')
else:
self.image_mean = tf.constant(0.0, dtype=tf.float32, name='0')
self.scale_factor = tf.constant(kwargs.get('scale_factor', 2.0), dtype=tf.float32,
name='scale_factor')
self.linear_schedule_multiplier = tf.math.divide(global_step,
tf.cast(self.total_steps, dtype=tf.float32),
name='linear_schedule_multiplier')
self._dummy_image = tf.zeros([4, 8, 8, 3], dtype=tf.float32, name='dummy_image')
self.ema = tf.train.ExponentialMovingAverage(decay=self.moving_average_decay,
num_updates=self.global_step)
self.debug_values = [self.linear_schedule_multiplier]
self.debug_images = []
self._init_params(**kwargs)
self._init_model(**kwargs)
self._flops = int(self._flops)
self._params = int(self._params)
self._nodes = int(self._nodes)
if self.argmax_output and not self.backbone_only:
with tf.device(self.param_device):
with tf.variable_scope('calc/'):
valid_mask = tf.cast(self.valid_mask, dtype=tf.int32)
invalid_mask = tf.cast(tf.logical_not(self.valid_mask), dtype=tf.int32)
self.Y_all = tf.math.argmax(self.Y_all, axis=-1, output_type=tf.int32)*valid_mask - invalid_mask
self.Y_all = self.Y_all[..., tf.newaxis]
self.pred = tf.math.argmax(self.pred, axis=-1, output_type=tf.int32)
self.pred = self.pred[..., tf.newaxis]
for blk in self.block_list:
if not self.get_collection('block_{}/variables'.format(blk)):
self._block_list.remove(blk)
self._set_num_blocks(len(self.block_list))
print('\n# computing devices : {} {}(s)'.format(self.num_devices, self.compute_device))
print('# variable blocks : {} {}'.format(self.num_blocks, self.block_list))
print('\n# FLOPs : {:-15,}\n# Params: {:-15,}\n# Nodes : {:-15,}\n'.format(self.flops, self.params, self.nodes))
info = sorted(self.layer_info, key=lambda layer: layer['flops'], reverse=True)
print('Most FLOPs : {:-13,} ('.format(info[0]['flops']), end='')
for i in info:
if i['flops'] == info[0]['flops']:
print(i['name'] + ', ', end='')
else:
print(')')
break
info.sort(key=lambda layer: layer['params'], reverse=True)
print('Most Params: {:-13,} ('.format(info[0]['params']), end='')
for i in info:
if i['params'] == info[0]['params']:
print(i['name'] + ', ', end='')
else:
print(')')
break
info.sort(key=lambda layer: layer['nodes'], reverse=True)
print('Most Nodes : {:-13,} ('.format(info[0]['nodes']), end='')
for i in info:
if i['nodes'] == info[0]['nodes']:
print(i['name'] + ', ', end='')
else:
print(')\n')
break
def __setattr__(self, key, value):
if key == '_curr_block':
self.__dict__[key] = value
if value not in self.block_list:
self._block_list.append(value)
self._set_num_blocks(len(self.block_list))
elif key == '_num_blocks':
raise KeyError('Cannot set _num_blocks manually.')
else:
super(ConvNet, self).__setattr__(key, value)
def _init_params(self, **kwargs):
"""
Parameter initialization.
Initialize model parameters.
"""
pass
@abstractmethod
def _build_model(self):
"""
Build model.
This should be implemented.
:return dict containing tensors. Must include 'logits' and 'pred' tensors.
"""
pass
@property
def name(self):
return 'ConvNet'
@property
def session(self):
return self._session
@property
def top_scope(self):
return self._top_scope
@property
def input_size(self):
return self._input_size
@property
def num_classes(self):
return self._num_classes
@property
def loss_weights(self):
return self._loss_weights
@property
def model_scope(self):
return self._model_scope
@property
def companion_networks(self):
return self._companion_networks
@property
def next_elements(self):
return self._next_elements
@property
def backbone_only(self):
return self._backbone_only
@property
def dtype(self):
return self._dtype
@property
def channel_first(self):
return self._channel_first
@property
def argmax_output(self):
return self._argmax_output
@property
def num_devices(self):
return self._num_devices
@property
def cpu_offset(self):
return self._cpu_offset
@property
def gpu_offset(self):
return self._gpu_offset
@property
def param_device(self):
return self._param_device
@property
def compute_device(self):
return self._compute_device
@property
def device_offset(self):
return self._device_offset
@property
def block_list(self):
return tuple(self._block_list)
@property
def num_blocks(self):
return self._num_blocks
def _set_num_blocks(self, num_blocks):
self.__dict__['_num_blocks'] = num_blocks
@property
def custom_feed_dict(self):
return self._custom_feed_dict
@property
def flops(self):
return self._flops
@property
def params(self):
return self._params
@property
def nodes(self):
return self._nodes
@property
def layer_info(self):
return self._layer_info
@property
def dropout_weights(self):
return self._dropout_weights
@property
def dropout_features(self):
return self._dropout_features
@property
def blocks_to_train(self):
return self._blocks_to_train
@property
def update_batch_norm(self):
return self._update_batch_norm
@property
def moving_average_decay(self):
return self._moving_average_decay
@property
def batch_norm_decay(self):
return self._batch_norm_decay
@property
def feature_reduction(self):
return self._feature_reduction
@property
def update_ops(self):
return self._update_ops
@property
def init_ops(self):
return self._init_ops
def close(self):
self.session.close()
def add_to_collection(self, name, tensor):
if self.model_scope is None:
tf.add_to_collection(name, tensor)
else:
tf.add_to_collection(str(self.model_scope) + '/' + name, tensor)
def get_collection(self, key):
if self.model_scope is None:
tensors = tf.get_collection(key)
else:
tensors = tf.get_collection(str(self.model_scope) + '/' + key)
return tensors
def _init_model(self, **kwargs):
dtypes = (tf.float32, tf.float32)
output_shapes = ([None, None, None, self.input_size[-1]],
[None])
self._set_next_elements(dtypes, output_shapes)
with tf.variable_scope(tf.get_variable_scope()):
for i in range(self.device_offset, self.num_devices + self.device_offset):
self._curr_device = i
self._curr_block = None
self._curr_dependent_op = 0 # For ops with dependencies between GPUs such as BN
device = '/{}:'.format(self.compute_device) + str(i)
with tf.device(device):
with tf.name_scope(self.compute_device + '_' + str(i) + '/'):
self.X, self.Y = self.next_elements[device]
# FIXME: Fake label generation from NaNs
self.Y = tf.where(tf.is_nan(self.Y), # Fake label is created when the label is NaN
0.0 - tf.ones_like(self.Y, dtype=tf.float32),
self.Y)
self.X_in.append(self.X)
self.Y_in.append(self.Y)
self.Y = tf.cast(self.Y, dtype=tf.int32)
self.Y = tf.one_hot(self.Y, depth=self.num_classes, dtype=tf.float32) # one-hot encoding
self.X = self.zero_pad(self.X, pad_value=self.pad_value)
self.X = tf.math.subtract(self.X, self.image_mean, name='zero_center')
self.X = self.cond(self.augmentation,
lambda: self.augment_images(self.X, **kwargs),
lambda: self.center_crop(self.X),
name='augmentation')
if kwargs.get('cutmix', False):
self._cutmix_scheduling = kwargs.get('cutmix_scheduling', False)
self.X, self.Y = self.cond(self.is_train,
lambda: self.cutmix(self.X, self.Y),
lambda: (self.X, self.Y),
name='cutmix')
self.Xs.append(self.X)
self.Ys.append(self.Y)
self.X *= self.scale_factor # Scale images
if self.channel_first:
self.X = tf.transpose(self.X, perm=[0, 3, 1, 2])
if self.dtype is not tf.float32:
with tf.name_scope('{}/cast/'.format(self.compute_device + '_' + str(i))):
self.X = tf.cast(self.X, dtype=self.dtype)
with tf.name_scope('nn') if self.model_scope is None else tf.name_scope(self.model_scope):
self.d = self._build_model()
tf.get_variable_scope().reuse_variables()
if not self.backbone_only:
if self.dtype is not tf.float32:
with tf.name_scope('{}/cast/'.format(self.compute_device + '_' + str(i))):
self.d['logits'] = tf.cast(self.d['logits'], dtype=tf.float32)
self.d['pred'] = tf.cast(self.d['pred'], dtype=tf.float32)
for blk in self.block_list[::-1]:
if f'block_{blk}' in self.d:
self.gcams.append(self.grad_cam(self.d['logits'],
self.d[f'block_{blk}'],
y=None))
break
else:
self.gcams.append(self.X)
self.logits = self.d['logits']
self.pred = self.d['pred']
self.preds.append(self.pred)
self.losses.append(self._build_loss(**kwargs))
else:
self.losses.append(0.0)
self.dicts.append(self.d)
# self.bytes_in_use.append(tf_contrib.memory_stats.BytesInUse())
with tf.device(self.param_device):
with tf.variable_scope('calc/'):
self.X_all = tf.concat(self.Xs, axis=0, name='x') + self.image_mean
self.Y_all = tf.concat(self.Ys, axis=0, name='y_true')
self.input_images = tf.concat(self.X_in, axis=0, name='x_in')
self.input_labels = tf.concat(self.Y_in, axis=0, name='y_in')
if not self.backbone_only:
self.pred = tf.concat(self.preds, axis=0, name='y_pred')
self.valid_mask = tf.concat(self.valid_masks, axis=0, name='valid_mask')
self.loss = tf.reduce_mean(self.losses, name='mean_loss')
self.gcam = tf.concat(self.gcams, axis=0, name='grad_cam')
self.debug_images.append(tf.clip_by_value(self.gcam/2 + self.X_all, 0, 1))
self.debug_images.append(tf.clip_by_value(self.gcam*self.X_all, 0, 1))
def _set_next_elements(self, dtypes, output_shapes=None):
for i in range(self.device_offset, self.num_devices + self.device_offset):
device = '/{}:'.format(self.compute_device) + str(i)
if device in self.next_elements:
self.handles.append(None) # Handles already exist in other ConvNet
else:
with tf.device(device):
with tf.name_scope(self.compute_device + '_' + str(i)):
handle = tf.placeholder(tf.string, shape=[], name='handle')
self.handles.append(handle) # Handles for feedable iterators of datasets
iterator = tf.data.Iterator.from_string_handle(handle, dtypes, output_shapes=output_shapes)
self.next_elements[device] = list(iterator.get_next())
def _build_loss(self, **kwargs):
l1_factor = kwargs.get('l1_reg', 0e-8)
l2_factor = kwargs.get('l2_reg', 1e-4)
ls_factor = kwargs.get('label_smoothing', 0.0)
focal_loss_factor = kwargs.get('focal_loss_factor', 0.0)
sigmoid_focal_loss_factor = kwargs.get('sigmoid_focal_loss_factor', 0.0)
variables = self.get_collection('weight_variables')
if kwargs.get('bias_norm_decay', False):
variables += self.get_collection('bias_variables') + self.get_collection('norm_variables')
valid_eps = 1e-5
w = self.loss_weights
if w is None:
w = np.ones(self.num_classes, dtype=np.float32)
else:
w = np.array(w, dtype=np.float32)
print('\nLoss weights: ', w)
with tf.variable_scope('loss'):
w = tf.constant(w, dtype=tf.float32, name='class_weights')
w = tf.expand_dims(w, axis=0)
while len(w.get_shape()) < len(self.Y.get_shape()):
w = tf.expand_dims(w, axis=1)
batch_weights = tf.reduce_sum(self.Y*w, axis=-1)
with tf.variable_scope('l1_loss'):
if l1_factor > 0.0:
l1_factor = tf.constant(l1_factor, dtype=tf.float32, name='L1_factor')
l1_reg_loss = l1_factor*tf.accumulate_n([tf.reduce_sum(tf.math.abs(var)) for var in variables])
else:
l1_reg_loss = tf.constant(0.0, dtype=tf.float32, name='0')
with tf.variable_scope('l2_loss'):
if l2_factor > 0.0:
l2_factor = tf.constant(l2_factor, dtype=tf.float32, name='L2_factor')
l2_reg_loss = l2_factor*tf.math.accumulate_n([tf.nn.l2_loss(var) for var in variables])
else:
l2_reg_loss = tf.constant(0.0, dtype=tf.float32, name='0')
with tf.variable_scope('valid_mask'):
sumval = tf.reduce_sum(self.Y, axis=-1)
valid_g = tf.greater(sumval, 1.0 - valid_eps)
valid_l = tf.less(sumval, 1.0 + valid_eps)
valid_mask = tf.logical_and(valid_g, valid_l)
self.valid_masks.append(valid_mask)
valid_mask = tf.cast(valid_mask, dtype=tf.float32)
if ls_factor > 0.0:
labels = self._label_smoothing(self.Y, ls_factor)
else:
labels = self.Y
softmax_losses = self._loss_fn(labels, self.logits, **kwargs)
if focal_loss_factor > 0.0:
gamma = focal_loss_factor
with tf.variable_scope('focal_loss'):
pred = tf.reduce_sum(self.Y*self.pred, axis=-1)
focal_loss = tf.pow(1.0 - pred, gamma)
softmax_losses *= focal_loss
if sigmoid_focal_loss_factor > 0.0:
alpha = sigmoid_focal_loss_factor
with tf.variable_scope('sigmoid_focal_loss'):
pred = tf.reduce_sum(self.Y*self.pred, axis=-1)
sigmoid_focal_loss = tf.stop_gradient(1.0 - tf.math.sigmoid(alpha*(pred - 0.5)))
sigmoid_focal_loss /= 1.0 - tf.math.sigmoid(-0.5*alpha)
softmax_losses *= sigmoid_focal_loss
softmax_loss = tf.reduce_mean(batch_weights*valid_mask*softmax_losses)
loss = softmax_loss + l1_reg_loss + l2_reg_loss
return loss
def _loss_fn(self, labels, logits, **kwargs):
softmax_losses = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=logits, axis=-1)
return softmax_losses
def _label_smoothing(self, labels, ls_factor, name='label_smoothing'):
with tf.variable_scope(name):
ls_factor = tf.constant(ls_factor, dtype=tf.float32, name='label_smoothing_factor')
labels = labels*(1.0 - ls_factor) + ls_factor/self.num_classes
return labels
def predict(self, dataset, verbose=False, return_images=True, max_examples=None, run_init_ops=True, **kwargs):
batch_size = dataset.batch_size
augment_test = kwargs.get('augment_test', False)
if max_examples is None:
pred_size = dataset.num_examples
else:
pred_size = min(max_examples, dataset.num_examples)
num_steps = np.ceil(pred_size/batch_size).astype(int)
monte_carlo = kwargs.get('monte_carlo', False)
dataset.initialize(self.session)
handles = dataset.get_string_handles(self.session)
if run_init_ops:
self.session.run(self.init_ops)
if verbose:
print('Running prediction loop...')
feed_dict = {self.is_train: False,
self.monte_carlo: monte_carlo,
self.augmentation: augment_test,
self.total_steps: num_steps}
for h_t, h in zip(self.handles, handles):
feed_dict.update({h_t: h})
feed_dict.update(self.custom_feed_dict)
if return_images:
_X = np.zeros([pred_size] + list(self.input_size), dtype=np.float32)
else:
_X = np.zeros([pred_size] + [4, 4, 3], dtype=np.float32) # Dummy images
_Y_true = np.zeros([pred_size] + self.pred.get_shape().as_list()[1:], dtype=np.float32)
_Y_pred = np.zeros([pred_size] + self.pred.get_shape().as_list()[1:], dtype=np.float32)
_loss_pred = np.zeros(num_steps, dtype=np.float32)
start_time = time.time()
for i in range(num_steps):
try:
X, Y_true, Y_pred, loss_pred = self.session.run([self.X_all, self.Y_all, self.pred, self.loss],
feed_dict=feed_dict)
sidx = i*batch_size
eidx = (i + 1)*batch_size
num_left = pred_size - sidx
if return_images:
_X[sidx:eidx] = X[:num_left]
_Y_true[sidx:eidx] = Y_true[:num_left]
_Y_pred[sidx:eidx] = Y_pred[:num_left]
_loss_pred[i] = loss_pred
except tf.errors.OutOfRangeError:
if verbose:
print('The last iteration ({} data) has been ignored'.format(pred_size - i*batch_size))
if verbose:
print('Total prediction time: {:.2f} sec'.format(time.time() - start_time))
_loss_pred = np.mean(_loss_pred, axis=0)
return _X, _Y_true, _Y_pred, _loss_pred
def features(self, dataset, tensors, max_examples=None, run_init_ops=True, **kwargs): # Return any deep features
batch_size = dataset.batch_size
augment_test = kwargs.get('augment_test', False)
if max_examples is None:
pred_size = dataset.num_examples
else:
pred_size = min(max_examples, dataset.num_examples)
num_steps = np.ceil(pred_size/batch_size).astype(int)
monte_carlo = kwargs.get('monte_carlo', False)
dataset.initialize(self.session)
handles = dataset.get_string_handles(self.session)
if run_init_ops:
self.session.run(self.init_ops)
feed_dict = {self.is_train: False,
self.monte_carlo: monte_carlo,
self.augmentation: augment_test}
for h_t, h in zip(self.handles, handles):
feed_dict.update({h_t: h})
feed_dict.update(self.custom_feed_dict)
if not isinstance(tensors, (list, tuple)):
tensors = [tensors]
batched_features = []
for i in range(num_steps):
feat = self.session.run(tensors, feed_dict=feed_dict)
batched_features.append(feat)
features = []
for feat in zip(*batched_features):
features.append(np.concatenate(feat, axis=0)[:pred_size])
return features
def save_results(self, dataset, save_dir, epoch, max_examples=None, **kwargs): # Save intermediate results
pass
def cond(self, pred, true_fn, false_fn, name=None):
if isinstance(pred, tf.Tensor):
return tf.cond(pred, true_fn, false_fn, name=name)
else:
if pred:
return true_fn()
else:
return false_fn()
def zero_pad(self, x, pad_value=0.0):
with tf.variable_scope('zero_pad'):
shape_tensor = tf.cast(tf.shape(x), dtype=tf.float32)
h = shape_tensor[1]
w = shape_tensor[2]
pad_h = tf.maximum(self._padded_size[0] - h, 0.0)
pad_w = tf.maximum(self._padded_size[1] - w, 0.0)
paddings = [[0, 0],
[tf.cast(tf.floor(pad_h/2), dtype=tf.int32), tf.cast(tf.ceil(pad_h/2), dtype=tf.int32)],
[tf.cast(tf.floor(pad_w/2), dtype=tf.int32), tf.cast(tf.ceil(pad_w/2), dtype=tf.int32)],
[0, 0]]
x = tf.pad(x, paddings, constant_values=pad_value)
return x
def augment_images(self, x, mask=None, **kwargs):
rand_blur = kwargs.get('rand_blur_stddev', 0.0) > 0.0
rand_affine = kwargs.get('rand_affine', False)
rand_crop = kwargs.get('rand_crop', False)
rand_distortion = kwargs.get('rand_distortion', False)
if rand_blur:
x = self.gaussian_blur(x, **kwargs)
if rand_affine:
x, mask = self.affine_augment(x, mask, **kwargs)
if rand_crop:
x, mask = self.rand_crop(x, mask, **kwargs)
else:
x = self.center_crop(x)
if mask is not None:
mask = self.center_crop(mask)
if rand_distortion:
x = self.rand_hue(x, **kwargs)
x = self.rand_saturation(x, **kwargs)
x = self.rand_color_balance(x, **kwargs)
x = self.rand_equalization(x, **kwargs)
x = self.rand_contrast(x, **kwargs)
x = self.rand_brightness(x, **kwargs)
x = self.rand_noise(x, **kwargs)
x = tf.clip_by_value(x, 0.0 - self.image_mean, 1.0 - self.image_mean)
x = self.rand_solarization(x, **kwargs)
x = self.rand_posterization(x, **kwargs)
if mask is None:
return x
else:
return x, mask
def gaussian_blur(self, x, **kwargs):
with tf.variable_scope('gaussian_blur'):
max_stddev = kwargs.get('rand_blur_stddev', 0.0)
scheduling = kwargs.get('rand_blur_scheduling', False)
if scheduling > 0:
max_stddev *= self.linear_schedule_multiplier
elif scheduling < 0:
max_stddev *= 1.0 - self.linear_schedule_multiplier
self._max_stddev = max_stddev
x = tf.map_fn(self.gaussian_blur_fn, x, parallel_iterations=32, back_prop=False)
return x
def gaussian_blur_fn(self, image):
in_channels = image.get_shape().as_list()[-1]
row_base = -0.5*np.array([[7, 6, 5, 4, 3, 2, 1, 0, 1, 2, 3, 4, 5, 6, 7]], dtype=np.float32)**2
column_base = np.transpose(row_base)
row_base = tf.tile(tf.constant(row_base[:, :, np.newaxis, np.newaxis], dtype=tf.float32),
multiples=(1, 1, in_channels, 1))
column_base = tf.tile(tf.constant(column_base[:, :, np.newaxis, np.newaxis], dtype=tf.float32),
multiples=(1, 1, in_channels, 1))
var = tf.random.uniform([], minval=0.0, maxval=self._max_stddev, dtype=tf.float32) ** 2
h_filt = tf.math.exp(column_base/var)
h_filt = h_filt/tf.reduce_sum(h_filt, axis=0, keepdims=True)
w_filt = tf.math.exp(row_base/var)
w_filt = w_filt/tf.reduce_sum(w_filt, axis=1, keepdims=True)
image = image[tf.newaxis, ...]
image = tf.nn.depthwise_conv2d(image, h_filt, strides=[1, 1, 1, 1], padding='SAME')
image = tf.nn.depthwise_conv2d(image, w_filt, strides=[1, 1, 1, 1], padding='SAME')
return image[0, ...]
def affine_augment(self, x, mask=None, **kwargs): # Scale, ratio, translation, rotation, shear, and reflection
scheduling = kwargs.get('rand_affine_scheduling', False)
interpolation = kwargs.get('resize_interpolation', 'bilinear')
rand_interpolation = kwargs.get('rand_interpolation', True)
with tf.variable_scope('affine_augment'):
shape_tensor = tf.shape(x)
batch_size = shape_tensor[0]
h = tf.cast(shape_tensor[1], dtype=tf.float32)
w = tf.cast(shape_tensor[2], dtype=tf.float32)
lower, upper = kwargs.get('rand_scale', (1.0, 1.0))
if scheduling > 0:
lower = 1.0 - (1.0 - lower)*self.linear_schedule_multiplier
upper = 1.0 - (1.0 - upper)*self.linear_schedule_multiplier
elif scheduling < 0:
lower = 1.0 - (1.0 - lower)*(1.0 - self.linear_schedule_multiplier)
upper = 1.0 - (1.0 - upper)*(1.0 - self.linear_schedule_multiplier)
# base = upper/lower
# randvals = tf.random.uniform([batch_size, 1], dtype=tf.float32)
# rand_scale = lower*tf.math.pow(base, randvals)
rand_scale = tf.random.uniform([], lower, upper, dtype=tf.float32)
lower, upper = kwargs.get('rand_ratio', (1.0, 1.0))
if scheduling > 0:
lower = tf.math.pow(lower, self.linear_schedule_multiplier)
upper = tf.math.pow(upper, self.linear_schedule_multiplier)
elif scheduling < 0:
lower = tf.math.pow(lower, 1.0 - self.linear_schedule_multiplier)
upper = tf.math.pow(upper, 1.0 - self.linear_schedule_multiplier)
base = upper/lower
randvals = tf.random.uniform([batch_size, 1], dtype=tf.float32)
rand_ratio = lower*tf.math.pow(base, randvals)
rand_x_scale = tf.math.sqrt(rand_scale*rand_ratio)
rand_y_scale = tf.math.sqrt(rand_scale/rand_ratio)
val = kwargs.get('rand_rotation', 0)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_rotation = (tf.random.uniform([batch_size, 1]) - 0.5)*val*(np.pi/180)
val = kwargs.get('rand_shear', 0)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_shear = (tf.random.uniform([batch_size, 1]) - 0.5)*val*(np.pi/180)
val = kwargs.get('rand_x_trans', 0)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_x_trans = (tf.random.uniform([batch_size, 1]) - 0.5)*val*w \
+ 0.5*w*(1.0 - rand_x_scale*tf.math.cos(rand_rotation)) \
+ 0.5*h*rand_y_scale*tf.math.sin(rand_rotation + rand_shear)
val = kwargs.get('rand_y_trans', 0)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_y_trans = (tf.random.uniform([batch_size, 1]) - 0.5)*val*h \
- 0.5*w*rand_x_scale*tf.math.sin(rand_rotation) \
+ 0.5*h*(1.0 - rand_y_scale*tf.math.cos(rand_rotation + rand_shear))
a0a = rand_x_scale*tf.math.cos(rand_rotation + rand_shear)
a1a = -rand_y_scale*tf.math.sin(rand_rotation)
a2a = rand_x_trans
b0a = rand_x_scale*tf.math.sin(rand_rotation + rand_shear)
b1a = rand_y_scale*tf.math.cos(rand_rotation)
b2a = rand_y_trans
val = kwargs.get('rand_x_reflect', True)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_x_reflect = tf.math.round(tf.random.uniform([batch_size, 1])*val)
val = kwargs.get('rand_y_reflect', False)
if scheduling > 0:
val *= self.linear_schedule_multiplier
elif scheduling < 0:
val *= 1.0 - self.linear_schedule_multiplier
rand_y_reflect = tf.math.round(tf.random.uniform([batch_size, 1])*val)
a0r = 1.0 - 2.0*rand_x_reflect
# a1r = tf.zeros([batch_size, 1], dtype=tf.float32)
a2r = rand_x_reflect*w
# b0r = tf.zeros([batch_size, 1], dtype=tf.float32)
b1r = 1.0 - 2.0*rand_y_reflect
b2r = rand_y_reflect*h
a0 = a0a*a0r
a1 = a1a*a0r
a2 = a2a*a0r + a2r
b0 = b0a*b1r
b1 = b1a*b1r
b2 = b2a*b1r + b2r
c0 = tf.zeros([batch_size, 1], dtype=tf.float32)
c1 = tf.zeros([batch_size, 1], dtype=tf.float32)
transforms = tf.concat([a0, a1, a2, b0, b1, b2, c0, c1], axis=1)
if rand_interpolation:
num = tf.random.uniform([], 0, 2, dtype=tf.int32)
x = tf.cond(tf.cast(num, dtype=tf.bool),
lambda: tf_contrib.image.transform(x, transforms, interpolation='NEAREST'),
lambda: tf_contrib.image.transform(x, transforms, interpolation='BILINEAR'))
elif interpolation.lower() == 'nearest' or interpolation.lower() == 'nearest neighbor':
x = tf_contrib.image.transform(x, transforms, interpolation='NEAREST')
elif interpolation.lower() == 'bilinear':
x = tf_contrib.image.transform(x, transforms, interpolation='BILINEAR')
elif interpolation.lower() == 'bicubic':
warnings.warn('Bicubic interpolation is not supported for GPU. Bilinear is used instead.', UserWarning)
x = tf_contrib.image.transform(x, transforms, interpolation='BILINEAR')
else:
raise ValueError('Interpolation method of {} is not supported.'.format(interpolation))
if mask is not None:
mask = tf_contrib.image.transform(mask, transforms, interpolation='NEAREST')
return x, mask
def rand_crop(self, x, mask=None, **kwargs):
with tf.variable_scope('rand_crop'):
self._crop_scale = kwargs.get('rand_crop_scale', (1.0, 1.0)) # Size of crop windows
self._crop_ratio = kwargs.get('rand_crop_ratio', (1.0, 1.0)) # Aspect ratio of crop windows
self._extend_bbox_index_range = kwargs.get('extend_bbox_index_range', False)
self._min_object_size = kwargs.get('min_object_size', None)
self._interpolation = kwargs.get('resize_interpolation', 'bilinear') # Interpolation method
self._rand_interpolation = kwargs.get('rand_interpolation', True)
self._crop_scheduling = kwargs.get('rand_crop_scheduling', False)
if mask is None:
x = tf.map_fn(self.rand_crop_image, x, parallel_iterations=32, back_prop=False)
else:
x, mask = tf.map_fn(self.rand_crop_image_and_mask, (x, mask), dtype=(tf.float32, tf.float32),
parallel_iterations=32, back_prop=False)
return x, mask
def rand_crop_image(self, x):
image = x
shape_tensor = tf.shape(image)
h = tf.cast(shape_tensor[0], dtype=tf.int32)
w = tf.cast(shape_tensor[1], dtype=tf.int32)
lower, upper = self._crop_scale
if self._crop_scheduling > 0:
lower = 1.0 - (1.0 - lower)*self.linear_schedule_multiplier
upper = 1.0 - (1.0 - upper)*self.linear_schedule_multiplier
elif self._crop_scheduling < 0:
lower = 1.0 - (1.0 - lower)*(1.0 - self.linear_schedule_multiplier)
upper = 1.0 - (1.0 - upper)*(1.0 - self.linear_schedule_multiplier)
scale_lower = lower
# a = upper**2 - lower**2
# b = lower**2
# randval = tf.random.uniform([], dtype=tf.float32)
# rand_scale = tf.math.sqrt(a*randval + b)
rand_scale = tf.random.uniform([], lower, upper, dtype=tf.float32)
lower, upper = self._crop_ratio
if self._crop_scheduling > 0:
lower = tf.math.pow(lower, self.linear_schedule_multiplier)
upper = tf.math.pow(upper, self.linear_schedule_multiplier)
elif self._crop_scheduling < 0:
lower = tf.math.pow(lower, 1.0 - self.linear_schedule_multiplier)
upper = tf.math.pow(upper, 1.0 - self.linear_schedule_multiplier)
base = upper/lower
randval = tf.random.uniform([], dtype=tf.float32)
rand_ratio = lower*tf.math.pow(base, randval)
rand_x_scale = tf.math.sqrt(rand_scale/rand_ratio)
rand_y_scale = tf.math.sqrt(rand_scale*rand_ratio)
size_h_full = tf.cast(tf.math.round(self.input_size[0]*rand_y_scale), dtype=tf.int32)
size_w_full = tf.cast(tf.math.round(self.input_size[1]*rand_x_scale), dtype=tf.int32)
size_h = tf.math.minimum(h, size_h_full)
size_w = tf.math.minimum(w, size_w_full)
offset_h = tf.random.uniform([], 0, h - size_h + 1, dtype=tf.int32)
offset_w = tf.random.uniform([], 0, w - size_w + 1, dtype=tf.int32)
if self._extend_bbox_index_range:
with tf.variable_scope('full_index_range'):
offset_h_full = tf.random.uniform([], 0, h, dtype=tf.int32)
offset_w_full = tf.random.uniform([], 0, w, dtype=tf.int32)
x_min = offset_w_full - size_w_full//2
x_max = tf.math.minimum(x_min + size_w_full, w)
x_min = tf.math.maximum(0, x_min)
y_min = offset_h_full - size_h_full//2
y_max = tf.math.minimum(y_min + size_h_full, h)
y_min = tf.math.maximum(0, y_min)
crop_h = y_max - y_min
crop_w = x_max - x_min
if self._min_object_size is None:
min_object_size = scale_lower
else:
min_object_size = self._min_object_size
min_object_area = min_object_size*tf.cast(h, dtype=tf.float32)*tf.cast(w, dtype=tf.float32)
output_ratio = self.input_size[1]/self.input_size[0]
crop_area = tf.cast(crop_h*crop_w, dtype=tf.float32)
crop_ratio = tf.cast(crop_h, dtype=tf.float32)/tf.cast(crop_w, dtype=tf.float32)*output_ratio