/
models.py
1971 lines (1708 loc) · 76.6 KB
/
models.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
"""
models (networks) for the neurite project
If you use this code, please cite the following, and read function docs for further info/citations
Dalca AV, Guttag J, Sabuncu MR
Anatomical Priors in Convolutional Networks for Unsupervised Biomedical Segmentation,
CVPR 2018. https://arxiv.org/abs/1903.03148
Copyright 2020 Adrian V. Dalca
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing permissions and limitations under
the License.
"""
# core python
import sys
import warnings
# third party
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as KL
from tensorflow.keras.models import Model
import tensorflow.keras.backend as K
from tensorflow.python.keras.constraints import maxnorm
# local
from . import layers
from . import utils
from . import modelio
###############################################################################
# Roughly volume preserving (e.g. high dim to high dim) models
###############################################################################
def dilation_net(nb_features,
input_shape, # input layer shape, vector of size ndims + 1(nb_channels)
nb_levels,
conv_size,
nb_labels,
name='dilation_net',
prefix=None,
feat_mult=1,
pool_size=2,
use_logp=True,
padding='same',
dilation_rate_mult=1,
activation='elu',
use_residuals=False,
final_pred_activation='softmax',
nb_conv_per_level=1,
add_prior_layer=False,
add_prior_layer_reg=0,
layer_nb_feats=None,
batch_norm=None):
return unet(nb_features,
input_shape, # input layer shape, vector of size ndims + 1(nb_channels)
nb_levels,
conv_size,
nb_labels,
name='unet',
prefix=None,
feat_mult=1,
pool_size=2,
use_logp=True,
padding='same',
activation='elu',
use_residuals=False,
dilation_rate_mult=dilation_rate_mult,
final_pred_activation='softmax',
nb_conv_per_level=1,
add_prior_layer=False,
add_prior_layer_reg=0,
layer_nb_feats=None,
batch_norm=None)
def unet(nb_features,
input_shape,
nb_levels,
conv_size,
nb_labels,
name='unet',
prefix=None,
feat_mult=1,
pool_size=2,
use_logp=True,
padding='same',
dilation_rate_mult=1,
activation='elu',
use_residuals=False,
final_pred_activation='softmax',
nb_conv_per_level=1,
add_prior_layer=False,
add_prior_layer_reg=0,
layer_nb_feats=None,
conv_dropout=0,
batch_norm=None,
convL=None): # conv layer function
"""
unet-style keras model with an overdose of parametrization.
downsampling:
for U-net like architecture, we need to use Deconvolution3D.
However, this is not yet available (maybe soon, it's on a dev branch in github I believe)
Until then, we'll upsample and convolve.
TODO: Need to check that UpSampling3D actually does NN-upsampling!
Parameters:
nb_features: the number of features at each convolutional level
see below for `feat_mult` and `layer_nb_feats` for modifiers to this number
if nb_features is a list of lists, they will be taken to specify
the number of filters and layers at each level
overriding other options such as nb_levels and feat_mult
input_shape: input layer shape, vector of size ndims + 1 (nb_channels)
conv_size: the convolution kernel size
nb_levels: the number of Unet levels (number of downsamples) in the "encoder"
(e.g. 4 would give you 4 levels in encoder, 4 in decoder)
nb_labels: number of output channels
name (default: 'unet'): the name of the network
prefix (default: `name` value): prefix to be added to layer names
feat_mult (default: 1) multiple for `nb_features` as we go down the encoder levels.
e.g. feat_mult of 2 and nb_features of 16 would yield 32 features in the
second layer, 64 features in the third layer, etc
pool_size (default: 2): max pooling size (integer or list if specifying per dimension)
use_logp:
padding:
dilation_rate_mult:
activation:
use_residuals:
final_pred_activation:
nb_conv_per_level:
add_prior_layer:
add_prior_layer_reg:
layer_nb_feats:
conv_dropout:
batch_norm:
"""
# naming
model_name = name
if prefix is None:
prefix = model_name
if isinstance(input_shape[0], (tuple, list, np.ndarray)):
# input_shape is a list of lists, and so we need to configure
# multiple inputs here, concatenate, and pass them to the encoder
src_input = []
for i, shape in enumerate(input_shape):
if not np.array_equal(shape[:-1], input_shape[0][:-1]):
raise ValueError('spatial dimensions must match if multiple input shapes '
'are provided, but got shapes '
f'{input_shape[0][:-1]} and {shape[:-1]}')
src_input.append(KL.Input(shape=shape, name=f'{prefix}_input_{i}'))
src = KL.concatenate(src_input, axis=-1, name=f'{prefix}_input_concat')
# also we should set input_shape to the first value for further calls
input_shape = input_shape[0]
else:
src = None
src_input = None
# volume size data
ndims = len(input_shape) - 1
if isinstance(pool_size, int):
pool_size = (pool_size,) * ndims
# if nb_features is a list of lists use it to specify the # of levels
# and the number of filters at each level (in each sublist)
if isinstance(nb_features, list):
if nb_levels is not None:
warnings.warn('nb_levels is not None while ' +
'nb_features list of lists specified - overriding')
if feat_mult is not None:
warnings.warn('feat_mult is not None while ' +
'nb_features list of lists specified - overriding')
nb_levels = len(nb_features)
assert isinstance(nb_features[0], list), \
'nb_features must be a scalar or a list of lists (not a list of scalars)'
# get encoding model
enc_model = conv_enc(nb_features,
input_shape,
nb_levels,
conv_size,
name=model_name,
prefix=prefix,
feat_mult=feat_mult,
pool_size=pool_size,
padding=padding,
dilation_rate_mult=dilation_rate_mult,
activation=activation,
use_residuals=use_residuals,
nb_conv_per_level=nb_conv_per_level,
layer_nb_feats=layer_nb_feats,
conv_dropout=conv_dropout,
batch_norm=batch_norm,
src=src,
src_input=src_input,
convL=convL)
# get decoder
# use_skip_connections=1 makes it a u-net
lnf = layer_nb_feats[(nb_levels * nb_conv_per_level):] if layer_nb_feats is not None else None
dec_model = \
conv_dec(nb_features,
None,
nb_levels,
conv_size,
nb_labels,
name=model_name,
prefix=prefix,
feat_mult=feat_mult,
pool_size=pool_size,
use_skip_connections=1,
padding=padding,
dilation_rate_mult=dilation_rate_mult,
activation=activation,
use_residuals=use_residuals,
final_pred_activation='linear' if add_prior_layer else final_pred_activation,
nb_conv_per_level=nb_conv_per_level,
batch_norm=batch_norm,
layer_nb_feats=lnf,
conv_dropout=conv_dropout,
input_model=enc_model,
convL=convL)
final_model = dec_model
if add_prior_layer:
final_model = add_prior(dec_model,
[*input_shape[:-1], nb_labels],
name=model_name + '_prior',
use_logp=use_logp,
final_pred_activation=final_pred_activation,
add_prior_layer_reg=add_prior_layer_reg)
return final_model
def ae(nb_features,
input_shape,
nb_levels,
conv_size,
nb_labels,
enc_size,
name='ae',
prefix=None,
feat_mult=1,
pool_size=2,
padding='same',
activation='elu',
use_residuals=False,
nb_conv_per_level=1,
batch_norm=None,
enc_batch_norm=None,
ae_type='conv', # 'dense', or 'conv'
enc_lambda_layers=None,
add_prior_layer=False,
add_prior_layer_reg=0,
use_logp=True,
conv_dropout=0,
include_mu_shift_layer=False,
# whether to return a single model, or a tuple of models that can be stacked.
single_model=False,
final_pred_activation='softmax',
src=None,
src_input=None,
do_vae=False,
convL=None): # conv layer function
"""
Convolutional Auto-Encoder.
Optionally Variational.
Optionally Dense middle layer
"Mostly" in that the inner encoding can be (optionally) constructed via dense features.
Parameters:
do_vae (bool): whether to do a variational auto-encoder or not.
enc_lambda_layers functions to try:
K.softsign
a = 1
longtanh = lambda x: K.tanh(x) * K.log(2 + a * abs(x))
"""
# naming
model_name = name
# volume size data
ndims = len(input_shape) - 1
if isinstance(pool_size, int):
pool_size = (pool_size,) * ndims
# get encoding model
enc_model = conv_enc(nb_features,
input_shape,
nb_levels,
conv_size,
name=model_name,
feat_mult=feat_mult,
pool_size=pool_size,
padding=padding,
activation=activation,
use_residuals=use_residuals,
nb_conv_per_level=nb_conv_per_level,
conv_dropout=conv_dropout,
batch_norm=batch_norm,
src=src,
src_input=src_input,
convL=convL)
# middle AE structure
if single_model:
in_input_shape = None
in_model = enc_model
else:
in_input_shape = enc_model.output.shape.as_list()[1:]
in_model = None
mid_ae_model = single_ae(enc_size,
in_input_shape,
conv_size=conv_size,
name=model_name,
ae_type=ae_type,
input_model=in_model,
batch_norm=enc_batch_norm,
enc_lambda_layers=enc_lambda_layers,
include_mu_shift_layer=include_mu_shift_layer,
do_vae=do_vae)
# decoder
if single_model:
in_input_shape = None
in_model = mid_ae_model
else:
in_input_shape = mid_ae_model.output.shape.as_list()[1:]
in_model = None
dec_model = conv_dec(nb_features,
in_input_shape,
nb_levels,
conv_size,
nb_labels,
name=model_name,
feat_mult=feat_mult,
pool_size=pool_size,
use_skip_connections=False,
padding=padding,
activation=activation,
use_residuals=use_residuals,
final_pred_activation=final_pred_activation,
nb_conv_per_level=nb_conv_per_level,
batch_norm=batch_norm,
conv_dropout=conv_dropout,
input_model=in_model,
convL=convL)
if add_prior_layer:
dec_model = add_prior(dec_model,
[*input_shape[:-1], nb_labels],
name=model_name,
prefix=model_name + '_prior',
use_logp=use_logp,
final_pred_activation=final_pred_activation,
add_prior_layer_reg=add_prior_layer_reg)
if single_model:
return dec_model
else:
return (dec_model, mid_ae_model, enc_model)
def add_prior(input_model,
prior_shape,
name='prior_model',
prefix=None,
use_logp=True,
final_pred_activation='softmax',
add_prior_layer_reg=0):
"""
Append post-prior layer to a given model
"""
# naming
model_name = name
if prefix is None:
prefix = model_name
# prior input layer
prior_input_name = '%s-input' % prefix
prior_tensor = KL.Input(shape=prior_shape, name=prior_input_name)
prior_tensor_input = prior_tensor
like_tensor = input_model.output
# operation varies depending on whether we log() prior or not.
if use_logp:
# name = '%s-log' % prefix
# prior_tensor = KL.Lambda(_log_layer_wrap(add_prior_layer_reg), name=name)(prior_tensor)
print("Breaking change: use_logp option now requires log input!", file=sys.stderr)
merge_op = KL.add
else:
# using sigmoid to get the likelihood values between 0 and 1
# note: they won't add up to 1.
name = '%s_likelihood_sigmoid' % prefix
like_tensor = KL.Activation('sigmoid', name=name)(like_tensor)
merge_op = KL.multiply
# merge the likelihood and prior layers into posterior layer
name = '%s_posterior' % prefix
post_tensor = merge_op([prior_tensor, like_tensor], name=name)
# output prediction layer
# we use a softmax to compute P(L_x|I) where x is each location
pred_name = '%s_prediction' % prefix
if final_pred_activation == 'softmax':
assert use_logp, 'cannot do softmax when adding prior via P()'
print("using final_pred_activation %s for %s" % (final_pred_activation, model_name))
softmax_lambda_fcn = lambda x: tf.keras.activations.softmax(x, axis=-1)
pred_tensor = KL.Lambda(softmax_lambda_fcn, name=pred_name)(post_tensor)
else:
pred_tensor = KL.Activation('linear', name=pred_name)(post_tensor)
# create the model
model_inputs = [*input_model.inputs, prior_tensor_input]
model = Model(inputs=model_inputs, outputs=[pred_tensor], name=model_name)
# compile
return model
def single_ae(enc_size,
input_shape,
name='single_ae',
prefix=None,
ae_type='dense', # 'dense', or 'conv'
conv_size=None,
input_model=None,
enc_lambda_layers=None,
batch_norm=True,
padding='same',
activation=None,
include_mu_shift_layer=False,
do_vae=False):
"""
single-layer Autoencoder (i.e. input - encoding - output)
"""
# naming
model_name = name
if prefix is None:
prefix = model_name
if enc_lambda_layers is None:
enc_lambda_layers = []
# prepare input
input_name = '%s_input' % prefix
if input_model is None:
assert input_shape is not None, 'input_shape of input_model is necessary'
input_tensor = KL.Input(shape=input_shape, name=input_name)
last_tensor = input_tensor
else:
input_tensor = input_model.input
last_tensor = input_model.output
input_shape = last_tensor.shape.as_list()[1:]
input_nb_feats = last_tensor.shape.as_list()[-1]
# prepare conv type based on input
if ae_type == 'conv':
ndims = len(input_shape) - 1
convL = getattr(KL, 'Conv%dD' % ndims)
assert conv_size is not None, 'with conv ae, need conv_size'
conv_kwargs = {'padding': padding, 'activation': activation}
# if want to go through a dense layer in the middle of the U, need to:
# - flatten last layer if not flat
# - do dense encoding and decoding
# - unflatten (rehsape spatially) at end
if ae_type == 'dense' and len(input_shape) > 1:
name = '%s_ae_%s_down_flat' % (prefix, ae_type)
last_tensor = KL.Flatten(name=name)(last_tensor)
# recall this layer
pre_enc_layer = last_tensor
# encoding layer
if ae_type == 'dense':
assert len(enc_size) == 1, "enc_size should be of length 1 for dense layer"
enc_size_str = ''.join(['%d_' % d for d in enc_size])[:-1]
name = '%s_ae_mu_enc_dense_%s' % (prefix, enc_size_str)
last_tensor = KL.Dense(enc_size[0], name=name)(pre_enc_layer)
else: # convolution
# convolve then resize. enc_size should be [nb_dim1, nb_dim2, ..., nb_feats]
assert len(enc_size) == len(input_shape), \
"encoding size does not match input shape %d %d" % (len(enc_size), len(input_shape))
if list(enc_size)[:-1] != list(input_shape)[:-1] and \
all([f is not None for f in input_shape[:-1]]) and \
all([f is not None for f in enc_size[:-1]]):
# assert len(enc_size) - 1 == 2, "Sorry, I have not yet implemented non-2D
# resizing -- need to check out interpn!"
name = '%s_ae_mu_enc_conv' % (prefix)
last_tensor = convL(enc_size[-1], conv_size, name=name, **conv_kwargs)(pre_enc_layer)
name = '%s_ae_mu_enc' % (prefix)
zf = [enc_size[:-1][f] / last_tensor.shape.as_list()[1:-1][f]
for f in range(len(enc_size) - 1)]
last_tensor = layers.Resize(zoom_factor=zf, name=name)(last_tensor)
# resize_fn = lambda x: tf.image.resize_bilinear(x, enc_size[:-1])
# last_tensor = KL.Lambda(resize_fn, name=name)(last_tensor)
elif enc_size[-1] is None: # convolutional, but won't tell us bottleneck
name = '%s_ae_mu_enc' % (prefix)
last_tensor = KL.Lambda(lambda x: x, name=name)(pre_enc_layer)
else:
name = '%s_ae_mu_enc' % (prefix)
last_tensor = convL(enc_size[-1], conv_size, name=name, **conv_kwargs)(pre_enc_layer)
if include_mu_shift_layer:
# shift
name = '%s_ae_mu_shift' % (prefix)
last_tensor = layers.LocalBias(name=name)(last_tensor)
# encoding clean-up layers
for layer_fcn in enc_lambda_layers:
lambda_name = layer_fcn.__name__
name = '%s_ae_mu_%s' % (prefix, lambda_name)
last_tensor = KL.Lambda(layer_fcn, name=name)(last_tensor)
if batch_norm is not None:
name = '%s_ae_mu_bn' % (prefix)
last_tensor = KL.BatchNormalization(axis=batch_norm, name=name)(last_tensor)
# have a simple layer that does nothing to have a clear name before sampling
name = '%s_ae_mu' % (prefix)
last_tensor = KL.Lambda(lambda x: x, name=name)(last_tensor)
# if doing variational AE, will need the sigma layer as well.
if do_vae:
mu_tensor = last_tensor
# encoding layer
if ae_type == 'dense':
name = '%s_ae_sigma_enc_dense_%s' % (prefix, enc_size_str)
# kernel_initializer=tf.keras.initializers.RandomNormal(mean=0.0, stddev=1e-5),
# bias_initializer=tf.keras.initializers.RandomNormal(mean=-5.0, stddev=1e-5)
last_tensor = KL.Dense(enc_size[0], name=name)(pre_enc_layer)
else:
if list(enc_size)[:-1] != list(input_shape)[:-1] and \
all([f is not None for f in input_shape[:-1]]) and \
all([f is not None for f in enc_size[:-1]]):
# assert len(enc_size) - 1 == 2,
# "Sorry, I have not yet implemented non-2D resizing..."
name = '%s_ae_sigma_enc_conv' % (prefix)
last_tensor = convL(enc_size[-1], conv_size, name=name,
**conv_kwargs)(pre_enc_layer)
name = '%s_ae_sigma_enc' % (prefix)
zf = [enc_size[:-1][f] / last_tensor.shape.as_list()[1:-1][f]
for f in range(len(enc_size) - 1)]
last_tensor = layers.Resize(zoom_factor=zf, name=name)(last_tensor)
# resize_fn = lambda x: tf.image.resize_bilinear(x, enc_size[:-1])
# last_tensor = KL.Lambda(resize_fn, name=name)(last_tensor)
elif enc_size[-1] is None: # convolutional, but won't tell us bottleneck
name = '%s_ae_sigma_enc' % (prefix)
last_tensor = convL(pre_enc_layer.shape.as_list()
[-1], conv_size, name=name, **conv_kwargs)(pre_enc_layer)
# cannot use lambda, then mu and sigma will be same layer.
# last_tensor = KL.Lambda(lambda x: x, name=name)(pre_enc_layer)
else:
name = '%s_ae_sigma_enc' % (prefix)
last_tensor = convL(enc_size[-1], conv_size, name=name,
**conv_kwargs)(pre_enc_layer)
# encoding clean-up layers
for layer_fcn in enc_lambda_layers:
lambda_name = layer_fcn.__name__
name = '%s_ae_sigma_%s' % (prefix, lambda_name)
last_tensor = KL.Lambda(layer_fcn, name=name)(last_tensor)
if batch_norm is not None:
name = '%s_ae_sigma_bn' % (prefix)
last_tensor = KL.BatchNormalization(axis=batch_norm, name=name)(last_tensor)
# have a simple layer that does nothing to have a clear name before sampling
name = '%s_ae_sigma' % (prefix)
last_tensor = KL.Lambda(lambda x: x, name=name)(last_tensor)
logvar_tensor = last_tensor
# VAE sampling
name = '%s_ae_sample' % (prefix)
last_tensor = layers.SampleNormalLogVar(name=name)([mu_tensor, logvar_tensor])
if include_mu_shift_layer:
# shift
name = '%s_ae_sample_shift' % (prefix)
last_tensor = layers.LocalBias(name=name)(last_tensor)
# decoding layer
if ae_type == 'dense':
name = '%s_ae_%s_dec_flat_%s' % (prefix, ae_type, enc_size_str)
last_tensor = KL.Dense(np.prod(input_shape), name=name)(last_tensor)
# unflatten if dense method
if len(input_shape) > 1:
name = '%s_ae_%s_dec' % (prefix, ae_type)
last_tensor = KL.Reshape(input_shape, name=name)(last_tensor)
else:
if list(enc_size)[:-1] != list(input_shape)[:-1] and \
all([f is not None for f in input_shape[:-1]]) and \
all([f is not None for f in enc_size[:-1]]):
name = '%s_ae_mu_dec' % (prefix)
zf = [input_shape[:-1][f] / enc_size[:-1][f] for f in range(len(enc_size) - 1)]
last_tensor = layers.Resize(zoom_factor=zf, name=name)(last_tensor)
# resize_fn = lambda x: tf.image.resize_bilinear(x, input_shape[:-1])
# last_tensor = KL.Lambda(resize_fn, name=name)(last_tensor)
name = '%s_ae_%s_dec' % (prefix, ae_type)
last_tensor = convL(input_nb_feats, conv_size, name=name, **conv_kwargs)(last_tensor)
if batch_norm is not None:
name = '%s_bn_ae_%s_dec' % (prefix, ae_type)
last_tensor = KL.BatchNormalization(axis=batch_norm, name=name)(last_tensor)
# create the model and retun
model = Model(inputs=input_tensor, outputs=[last_tensor], name=model_name)
return model
def labels_to_image(
in_shape,
in_label_list,
out_label_list=None,
out_shape=None,
num_chan=1,
input_model=None,
mean_min=None,
mean_max=None,
std_min=None,
std_max=None,
zero_background=0.2,
warp_res=[16],
warp_std=0.5,
warp_modulate=True,
bias_res=40,
bias_std=0.3,
bias_modulate=True,
blur_std=1,
blur_modulate=True,
normalize=True,
gamma_std=0.25,
dc_offset=0,
one_hot=True,
seeds={},
return_vel=False,
return_def=False,
id=0,
):
"""
Generative model for augmenting label maps and synthesizing images from them.
Parameters:
in_shape: List of the spatial dimensions of the input label maps.
in_label_list: List of all possible input labels.
out_label_list (optional): List of labels in the output label maps. If
a dictionary is passed, it will be used to convert labels, e.g. to
GM, WM and CSF. All labels not included will be converted to
background with value 0. If 0 is among the output labels, it will be
one-hot encoded. Defaults to the input labels.
out_shape (optional): List of the spatial dimensions of the outputs.
Inputs will be symmetrically cropped or zero-padded to fit.
Defaults to the input shape.
num_chan (optional): Number of image channels to be synthesized.
Defaults to 1.
input_model (optional): Optional input model that feeds directly into
this model.
mean_min (optional): List of lower bounds on the means drawn to generate
the intensities for each label. Defaults to 0 for the background and
25 for all other labels.
mean_max (optional): List of upper bounds on the means drawn to generate
the intensities for each label. Defaults to 225 for each label.
std_min (optional): List of lower bounds on the SDs drawn to generate
the intensities for each label. Defaults to 0 for the background and
5 for all other labels.
std_max (optional): List of upper bounds on the SDs drawn to generate
the intensities for each label. Defaults to 25 for each label.
25 for all other labels.
zero_background (float, optional): Probability that the background is set
to zero. Defaults to 0.2.
warp_res (optional): List of factors N determining the
resultion 1/N relative to the inputs at which the SVF is drawn.
Defaults to 16.
warp_std (float, optional): Upper bound on the SDs used when drawing
the SVF. Defaults to 0.5.
warp_modulate (bool, optional): Whether to draw the SVF with random SDs.
If disabled, each batch will use the maximum SD. Defaults to True.
bias_res (optional): List of factors N determining the
resultion 1/N relative to the inputs at which the bias field is
drawn. Defaults to 40.
bias_std (float, optional): Upper bound on the SDs used when drawing
the bias field. Defaults to 0.3.
bias_modulate (bool, optional): Whether to draw the bias field with
random SDs. If disabled, each batch will use the maximum SD.
Defaults to True.
blur_std (float, optional): Upper bound on the SD of the kernel used
for Gaussian image blurring. Defaults to 1.
blur_modulate (bool, optional): Whether to draw random blurring SDs.
If disabled, each batch will use the maximum SD. Defaults to True.
normalize (bool, optional): Whether the image is min-max normalized.
Defaults to True.
gamma_std (float, optional): SD of random global intensity
exponentiation, i.e. gamma augmentation. Defaults to 0.25.
dc_offset (float, optional): Upper bound on global DC offset drawn and
added to the image after normalization. Defaults to 0.
one_hot (bool, optional): Whether output label maps are one-hot encoded.
Only the specified output labels will be included. Defaults to True.
seeds (dictionary, optional): Integers for reproducible randomization.
return_vel (bool, optional): Whether to append the half-resolution SVF
to the model outputs. Defaults to False.
return_def (bool, optional): Whether to append the combined displacement
field to the model outputs. Defaults to False.
id (int, optional): Model identifier used to create unique layer names
for including this model multiple times. Defaults to 0.
Returns:
Label-augmentation and image-synthesis model.
If you find this model useful, please cite:
M Hoffmann, B Billot, DN Greve, JE Iglesias, B Fischl, AV Dalca
SynthMorph: learning contrast-invariant registration without acquired images
IEEE Transactions on Medical Imaging (TMI), 41 (3), 543-558, 2022
https://doi.org/10.1109/TMI.2021.3116879
Anatomy-specific acquisition-agnostic affine registration learned from fictitious images
M Hoffmann, A Hoopes, B Fischl*, AV Dalca* (*equal contribution)
SPIE Medical Imaging: Image Processing, 12464, p 1246402, 2023
https://doi.org/10.1117/12.2653251
"""
warnings.warn('model `labels_to_image` is deprecated in favor `labels_to_image_new`')
import voxelmorph as vxm
if out_shape is None:
out_shape = in_shape
in_shape, out_shape = map(np.asarray, (in_shape, out_shape))
num_dim = len(in_shape)
# Inputs.
if input_model is None:
labels_input = KL.Input(shape=(*in_shape, 1), name=f'labels_input_{id}')
labels = labels_input
else:
assert len(input_model.outputs) == 1
labels = input_model.outputs[0]
labels_input = input_model.inputs
if not labels.dtype.is_integer:
labels = tf.cast(labels, tf.int32)
batch_size = tf.shape(labels)[0]
# Transform labels into [0, 1, ..., N-1].
in_label_list = np.int32(np.unique(in_label_list))
num_in_labels = len(in_label_list)
new_in_label_list = np.arange(num_in_labels)
in_lut = np.zeros(np.max(in_label_list) + 1, dtype=np.float32)
for i, lab in enumerate(in_label_list):
in_lut[lab] = i
labels = tf.gather(in_lut, indices=labels)
if warp_std > 0:
# Velocity field.
vel_shape = (*out_shape // 2, num_dim)
vel_scale = np.asarray(warp_res) / 2
vel_draw = lambda x: utils.augment.draw_perlin(
vel_shape, scales=vel_scale,
min_std=0 if warp_modulate else warp_std, max_std=warp_std,
seed=seeds.get('warp')
)
# One per batch.
vel_field = KL.Lambda(lambda x: tf.map_fn(
vel_draw, x, fn_output_signature='float32'), name=f'vel_{id}')(labels)
# Deformation field.
def_field = vxm.layers.VecInt(int_steps=5, name=f'vec_int_{id}')(vel_field)
def_field = layers.RescaleValues(2)(def_field)
def_field = layers.Resize(2, interp_method='linear', name=f'def_{id}')(def_field)
# Resampling.
labels = vxm.layers.SpatialTransformer(
interp_method='nearest', fill_value=0, name=f'trans_{id}')([labels, def_field])
labels = tf.cast(labels, tf.int32)
# Intensity means and standard deviations.
if mean_min is None:
mean_min = [0] + [25] * (num_in_labels - 1)
if mean_max is None:
mean_max = [225] * num_in_labels
if std_min is None:
std_min = [0] + [5] * (num_in_labels - 1)
if std_max is None:
std_max = [25] * num_in_labels
m0, m1, s0, s1 = map(np.asarray, (mean_min, mean_max, std_min, std_max))
mean = tf.random.uniform(
shape=(batch_size, num_chan, num_in_labels),
minval=m0, maxval=m1,
seed=seeds.get('mean'),
)
std = tf.random.uniform(
shape=(batch_size, num_chan, num_in_labels),
minval=s0, maxval=s1,
seed=seeds.get('std'),
)
# Synthetic image.
image = tf.random.normal(tf.shape(labels), seed=seeds.get('noise'))
indices = tf.concat([labels + i * num_in_labels for i in range(num_chan)], axis=-1)
gather = lambda x: tf.gather(tf.reshape(x[0], (-1,)), x[1])
mean = KL.Lambda(lambda x: tf.map_fn(gather, x, fn_output_signature='float32'))([mean, indices])
std = KL.Lambda(lambda x: tf.map_fn(gather, x, fn_output_signature='float32'))([std, indices])
image = image * std + mean
# Zero background.
if zero_background > 0:
rand_flip = tf.random.uniform(
shape=(batch_size, *[1] * num_dim, num_chan), seed=seeds.get('background'),
)
rand_flip = tf.less(rand_flip, zero_background)
image *= 1. - tf.cast(tf.logical_and(labels == 0, rand_flip), image.dtype)
# Blur.
if blur_std > 0:
kernels = utils.gaussian_kernel(
[blur_std] * num_dim, separate=True, random=blur_modulate,
dtype=image.dtype, seed=seeds.get('blur'),
)
image = utils.separable_conv(image, kernels, batched=True)
# Bias field.
if bias_std > 0:
bias_shape = (*out_shape, 1)
bias_draw = lambda x: utils.augment.draw_perlin(
bias_shape, scales=bias_res, seed=seeds.get('bias'),
min_std=0 if bias_modulate else bias_std, max_std=bias_std,
)
bias_field = KL.Lambda(lambda x: tf.map_fn(
bias_draw, x, fn_output_signature='float32'))(labels)
image *= tf.exp(bias_field, name=f'bias_{id}')
# Intensity manipulations.
image = tf.clip_by_value(image, clip_value_min=0, clip_value_max=255, name=f'clip_{id}')
if normalize:
image = KL.Lambda(lambda x: tf.map_fn(utils.minmax_norm, x))(image)
if gamma_std > 0:
gamma = tf.random.normal(
shape=(batch_size, *[1] * num_dim, num_chan), stddev=gamma_std, seed=seeds.get('gamma'),
)
image = tf.pow(image, tf.exp(gamma), name=f'gamma_{id}')
if dc_offset > 0:
image += tf.random.uniform(
shape=(batch_size, *[1] * num_dim, num_chan),
maxval=dc_offset,
seed=seeds.get('dc_offset'),
)
# Lookup table for converting the index labels back to the original values,
# setting unwanted labels to background. If the output labels are provided
# as a dictionary, it can be used e.g. to convert labels to GM, WM, CSF.
if out_label_list is None:
out_label_list = in_label_list
if isinstance(out_label_list, (tuple, list, np.ndarray)):
out_label_list = {lab: lab for lab in out_label_list}
out_lut = np.zeros(num_in_labels, dtype='int32')
for i, lab in enumerate(in_label_list):
if lab in out_label_list:
out_lut[i] = out_label_list[lab]
# For one-hot encoding, update the lookup table such that the M desired
# output labels are rebased into the interval [0, M-1[. If the background
# with value 0 is not part of the output labels, set it to -1 to remove it
# from the one-hot maps.
if one_hot:
hot_label_list = np.unique(list(out_label_list.values())) # Sorted.
hot_lut = np.full(hot_label_list[-1] + 1, fill_value=-1, dtype='int32')
for i, lab in enumerate(hot_label_list):
hot_lut[lab] = i
out_lut = hot_lut[out_lut]
# Convert indices to output labels only once.
labels = tf.gather(out_lut, labels, name=f'labels_back_{id}')
if one_hot:
labels = tf.one_hot(labels[..., 0], depth=len(hot_label_list), name=f'one_hot_{id}')
outputs = [image, labels]
if return_vel:
outputs.append(vel_field)
if return_def:
outputs.append(def_field)
return tf.keras.Model(labels_input, outputs, name=f'synth_{id}')
def labels_to_image_new(
labels_in,
labels_out=None,
in_shape=None,
out_shape=None,
input_model=None,
num_chan=1,
aff_shift=0,
aff_rotate=0,
aff_scale=0,
aff_shear=0,
aff_normal_shift=False,
aff_normal_rotate=False,
aff_normal_scale=False,
aff_normal_shear=False,
axes_flip=False,
axes_swap=False,
warp_min=0.01,
warp_max=2,
warp_blur_min=(8, 8),
warp_blur_max=(32, 32),
warp_zero_mean=False,
crop_min=0,
crop_max=0.2,
crop_prob=0,
crop_axes=None,
mean_min=None,
mean_max=None,
noise_min=0.1,
noise_max=0.2,
zero_background=0,
blur_min=0,
blur_max=1,
bias_min=0.01,
bias_max=0.1,
bias_blur_min=32,
bias_blur_max=64,
bias_func=tf.exp,
slice_stride_min=1,
slice_stride_max=8,
slice_prob=0,
slice_axes=None,
normalize=True,
gamma=0.5,
one_hot=True,
half_res=False,
seeds={},
return_im=True,
return_map=True,
return_vel=False,
return_def=False,
return_aff=False,
return_mean=False,
return_bias=False,
id=0,
):
"""Build model that augments label maps and synthesizes images from them.
Parameters:
labels_in: All possible input label values as an iterable. Passing a dictionary will remap
input labels to the generation labels defined by the dictionary values, for example to
draw the same intensity for left and right cortex. Generation labels must be hashable
but not necessarily numeric. Remapping has no effect on the output labels.
labels_out: Subset of the input labels to include in the output label maps, as an iterable.
Passing a dictionary will remap the included input labels, for example to GM, WM, and
CSF. Any input label missing in `labels_out` will be set to 0 (background) or excluded
if one-hot encoding. None means the output labels will be the same as the input labels.
Output labels must be numeric.
in_shape: Spatial dimensions of the input label maps as an iterable.
out_shape: Spatial dimensions of the outputs as an iterable. Inputs will be symmetrically
cropped or zero-padded to fit. None means `in_shape`.
input_model: Model whose outputs will be used as data inputs, and whose inputs will be used
as inputs to the returned model.
num_chan: Number of image channels to synthesize.
aff_shift: Upper bound on the magnitude of translations, drawn uniformly in voxels.