-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmodels.py
More file actions
1185 lines (1035 loc) · 68.9 KB
/
models.py
File metadata and controls
1185 lines (1035 loc) · 68.9 KB
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
"""
Deep learning models:
- U-Net
- U-Net ensemble
- U-Net+
- U-Net++
- U-Net 3+
- Attention U-Net
TODO:
* Allow models to have a unique number of encoder and decoder levels (e.g. 3 encoder levels and 5 decoder levels)
* Add temporal U-Nets
Author: Andrew Justin ([email protected])
Script version: 2023.8.18.D1
"""
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Concatenate, Input
from utils import unet_utils
import numpy as np
def unet(
input_shape: tuple[int],
num_classes: int,
pool_size: int | tuple[int] | list[int],
upsample_size: int | tuple[int] | list[int],
levels: int,
filter_num: tuple[int] | list[int],
kernel_size: int = 3,
squeeze_dims: int | tuple[int] | list[int] = None,
modules_per_node: int = 5,
batch_normalization: bool = True,
activation: str = 'relu',
padding: str = 'same',
use_bias: bool = True,
kernel_initializer: str = 'glorot_uniform',
bias_initializer: str = 'zeros',
kernel_regularizer: str = None,
bias_regularizer: str = None,
activity_regularizer: str = None,
kernel_constraint: str = None,
bias_constraint: str = None):
"""
Builds a U-Net model.
Parameters
----------
input_shape: tuple
Shape of the inputs. The last number in the tuple represents the number of channels/predictors.
num_classes: int
Number of classes/labels that the U-Net will try to predict.
pool_size: tuple or list
Size of the mask in the MaxPooling layers.
upsample_size: tuple or list
Size of the mask in the UpSampling layers.
levels: int
Number of levels in the U-Net. Must be greater than 1.
filter_num: iterable of ints
Number of convolution filters on each level of the U-Net.
kernel_size: int or tuple
Size of the kernel in the convolution layers.
squeeze_dims: int, tuple, or None
Dimensions/axes of the input to squeeze such that the target (y_true) will be smaller than the input.
- (e.g. to remove the third dimension, set this parameter to 2 [axis=2 for the third dimension])
modules_per_node: int
Number of modules in each node of the U-Net.
batch_normalization: bool
Setting this to True will add a batch normalization layer after every convolution in the modules.
activation: str
Activation function to use in the modules.
Can be any of tf.keras.activations, 'gaussian', 'gcu', 'leaky_relu', 'prelu', 'smelu', 'snake' (case-insensitive).
padding: str
Padding to use in the convolution layers.
use_bias: bool
Setting this to True will implement a bias vector in the convolution layers used in the modules.
kernel_initializer: str or tf.keras.initializers object
Initializer for the kernel weights matrix in the Conv2D/Conv3D layers.
bias_initializer: str or tf.keras.initializers object
Initializer for the bias vector in the Conv2D/Conv3D layers.
kernel_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the kernel weights matrix in the Conv2D/Conv3D layers.
bias_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the bias vector in the Conv2D/Conv3D layers.
activity_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the output of the Conv2D/Conv3D layers.
kernel_constraint: str or tf.keras.constraints object
Constraint function applied to the kernel matrix of the Conv2D/Conv3D layers.
bias_constraint: str or tf.keras.constrains object
Constraint function applied to the bias vector in the Conv2D/Conv3D layers.
Returns
-------
model: tf.keras.models.Model object
U-Net model.
Raises
------
ValueError
If levels < 2
If input_shape does not have 3 nor 4 dimensions
If the length of filter_num does not match the number of levels
References
----------
https://arxiv.org/pdf/1505.04597.pdf
"""
ndims = len(input_shape) - 1 # Number of dimensions in the input image (excluding the last dimension reserved for channels)
if levels < 2:
raise ValueError(f"levels must be greater than 1. Received value: {levels}")
if len(input_shape) > 4 or len(input_shape) < 3:
raise ValueError(f"input_shape can only have 3 or 4 dimensions (2D image + 1 dimension for channels OR a 3D image + 1 dimension for channels). Received shape: {np.shape(input_shape)}")
if len(filter_num) != levels:
raise ValueError(f"length of filter_num ({len(filter_num)}) does not match the number of levels ({levels})")
# Keyword arguments for the convolution modules
module_kwargs = dict({})
module_kwargs['num_modules'] = modules_per_node
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint']:
module_kwargs[arg] = locals()[arg]
# MaxPooling keyword arguments
pool_kwargs = {'pool_size': pool_size}
# Keyword arguments for upsampling
upsample_kwargs = dict({})
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint',
'upsample_size']:
upsample_kwargs[arg] = locals()[arg]
# Keyword arguments for the deep supervision output in the final decoder node
supervision_kwargs = dict({})
for arg in ['padding', 'kernel_initializer', 'bias_initializer', 'kernel_regularizer', 'bias_regularizer', 'activity_regularizer',
'kernel_constraint', 'bias_constraint', 'upsample_size', 'squeeze_dims']:
supervision_kwargs[arg] = locals()[arg]
supervision_kwargs['use_bias'] = True
tensors = dict({}) # Tensors associated with each node and skip connections
""" Setup the first encoder node with an input layer and a convolution module """
tensors['input'] = Input(shape=input_shape, name='Input')
tensors['En1'] = unet_utils.convolution_module(tensors['input'], filters=filter_num[0], name='En1', **module_kwargs)
""" The rest of the encoder nodes are handled here. Each encoder node is connected with a MaxPooling layer and contains convolution modules """
for encoder in np.arange(2, levels+1): # Iterate through the rest of the encoder nodes
current_node, previous_node = f'En{encoder}', f'En{encoder - 1}'
pool_tensor = unet_utils.max_pool(tensors[previous_node], name=f'{previous_node}-{current_node}', **pool_kwargs) # Connect the next encoder node with a MaxPooling layer
tensors[current_node] = unet_utils.convolution_module(pool_tensor, filters=filter_num[encoder - 1], name=current_node, **module_kwargs) # Convolution modules
# Connect the bottom encoder node to a decoder node
upsample_tensor = unet_utils.upsample(tensors[f'En{levels}'], filters=filter_num[levels - 2], name=f'En{levels}-De{levels}', **upsample_kwargs)
""" Bottom decoder node """
current_node, next_node = f'De{levels - 1}', f'De{levels - 2}'
skip_node = f'En{levels - 1}' # node with an incoming skip connection that connects to 'current_node'
tensors[current_node] = Concatenate(name=f'{current_node}_Concatenate')([tensors[skip_node], upsample_tensor]) # Concatenate the upsampled tensor and skip connection
tensors[current_node] = unet_utils.convolution_module(tensors[current_node], filters=filter_num[levels - 2], name=current_node, **module_kwargs) # Convolution module
upsample_tensor = unet_utils.upsample(tensors[current_node], filters=filter_num[levels - 3], name=f'{current_node}-{next_node}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
""" The rest of the decoder nodes (except the final node) are handled in this loop. Each node contains one concatenation of an upsampled tensor and a skip connection """
for decoder in np.arange(2, levels-1)[::-1]:
current_node, next_node = f'De{decoder}', f'De{decoder - 1}'
skip_node = f'En{decoder}' # node with an incoming skip connection that connects to 'current_node'
tensors[current_node] = Concatenate(name=f'{current_node}_Concatenate')([tensors[skip_node], upsample_tensor]) # Concatenate the upsampled tensor and skip connection
tensors[current_node] = unet_utils.convolution_module(tensors[current_node], filters=filter_num[decoder - 1], name=current_node, **module_kwargs) # Convolution module
upsample_tensor = unet_utils.upsample(tensors[current_node], filters=filter_num[decoder - 2], name=f'{current_node}-{next_node}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
""" Final decoder node begins with a concatenation and convolution module, followed by deep supervision """
tensor_De1 = Concatenate(name='De1_Concatenate')([tensors['En1'], upsample_tensor]) # Concatenate the upsampled tensor and skip connection
tensor_De1 = unet_utils.convolution_module(tensor_De1, filters=filter_num[0], name='De1', **module_kwargs) # Convolution module
tensors['output'] = unet_utils.deep_supervision_side_output(tensor_De1, num_classes=num_classes, kernel_size=1, output_level=1, name='final', **supervision_kwargs) # Deep supervision - this layer will output the model's prediction
model = Model(inputs=tensors['input'], outputs=tensors['output'], name=f'unet_{ndims}D')
return model
def unet_ensemble(
input_shape: tuple[int] | list[int],
num_classes: int,
pool_size: int | tuple[int] | list[int],
upsample_size: int | tuple[int] | list[int],
levels: int,
filter_num: tuple[int] | list[int],
kernel_size: int = 3,
squeeze_dims: int | tuple[int] | list[int] = None,
modules_per_node: int = 5,
batch_normalization: bool = True,
activation: str = 'relu',
padding: str = 'same',
use_bias: bool = True,
kernel_initializer: str = 'glorot_uniform',
bias_initializer: str = 'zeros',
kernel_regularizer: str = None,
bias_regularizer: str = None,
activity_regularizer: str = None,
kernel_constraint: str = None,
bias_constraint: str = None):
"""
Builds a U-Net ensemble model.
https://arxiv.org/pdf/1912.05074.pdf
Parameters
----------
input_shape: tuple
Shape of the inputs. The last number in the tuple represents the number of channels/predictors.
num_classes: int
Number of classes/labels that the U-Net will try to predict.
pool_size: tuple or list
Size of the mask in the MaxPooling layers.
upsample_size: tuple or list
Size of the mask in the UpSampling layers.
levels: int
Number of levels in the U-Net. Must be greater than 1.
filter_num: iterable of ints
Number of convolution filters on each level of the U-Net.
kernel_size: int or tuple
Size of the kernel in the convolution layers.
squeeze_dims: int, tuple, or None
Dimensions/axes of the input to squeeze such that the target (y_true) will be smaller than the input.
- (e.g. to remove the third dimension, set this parameter to 2 [axis=2 for the third dimension])
modules_per_node: int
Number of modules in each node of the U-Net.
batch_normalization: bool
Setting this to True will add a batch normalization layer after every convolution in the modules.
activation: str
Activation function to use in the modules.
Can be any of tf.keras.activations, 'gaussian', 'gcu', 'leaky_relu', 'prelu', 'smelu', 'snake' (case-insensitive).
padding: str
Padding to use in the convolution layers.
use_bias: bool
Setting this to True will implement a bias vector in the convolution layers used in the modules.
kernel_initializer: str or tf.keras.initializers object
Initializer for the kernel weights matrix in the Conv2D/Conv3D layers.
bias_initializer: str or tf.keras.initializers object
Initializer for the bias vector in the Conv2D/Conv3D layers.
kernel_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the kernel weights matrix in the Conv2D/Conv3D layers.
bias_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the bias vector in the Conv2D/Conv3D layers.
activity_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the output of the Conv2D/Conv3D layers.
kernel_constraint: str or tf.keras.constraints object
Constraint function applied to the kernel matrix of the Conv2D/Conv3D layers.
bias_constraint: str or tf.keras.constrains object
Constraint function applied to the bias vector in the Conv2D/Conv3D layers.
Returns
-------
model: tf.keras.models.Model object
U-Net model.
Raises
------
ValueError
If levels < 2
If input_shape does not have 3 nor 4 dimensions
If the length of filter_num does not match the number of levels
"""
ndims = len(input_shape) - 1 # Number of dimensions in the input image (excluding the last dimension reserved for channels)
if levels < 2:
raise ValueError(f"levels must be greater than 1. Received value: {levels}")
if len(input_shape) > 4 or len(input_shape) < 3:
raise ValueError(f"input_shape can only have 3 or 4 dimensions (2D image + 1 dimension for channels OR a 3D image + 1 dimension for channels). Received shape: {np.shape(input_shape)}")
if len(filter_num) != levels:
raise ValueError(f"length of filter_num ({len(filter_num)}) does not match the number of levels ({levels})")
# Keyword arguments for the convolution modules
module_kwargs = dict({})
module_kwargs['num_modules'] = modules_per_node
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint']:
module_kwargs[arg] = locals()[arg]
# MaxPooling keyword arguments
pool_kwargs = {'pool_size': pool_size}
# Keyword arguments for upsampling
upsample_kwargs = dict({})
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint',
'upsample_size']:
upsample_kwargs[arg] = locals()[arg]
# Keyword arguments for the deep supervision output in the final decoder node
supervision_kwargs = dict({})
for arg in ['padding', 'kernel_initializer', 'bias_initializer', 'kernel_regularizer', 'bias_regularizer', 'activity_regularizer',
'kernel_constraint', 'bias_constraint', 'upsample_size', 'squeeze_dims', 'num_classes']:
supervision_kwargs[arg] = locals()[arg]
supervision_kwargs['use_bias'] = True
supervision_kwargs['output_level'] = 1
supervision_kwargs['kernel_size'] = 1
tensors = dict({}) # Tensors associated with each node and skip connections
tensors_with_supervision = [] # list of output tensors. If deep supervision is used, more than one output will be produced
""" Setup the first encoder node with an input layer and a convolution module """
tensors['input'] = Input(shape=input_shape, name='Input')
tensors['En1'] = unet_utils.convolution_module(tensors['input'], filters=filter_num[0], name='En1', **module_kwargs)
""" The rest of the encoder nodes are handled here. Each encoder node is connected with a MaxPooling layer and contains convolution modules """
for encoder in np.arange(2, levels+1): # Iterate through the rest of the encoder nodes
current_node, previous_node = f'En{encoder}', f'En{encoder - 1}'
pool_tensor = unet_utils.max_pool(tensors[previous_node], name=f'{previous_node}-{current_node}', **pool_kwargs) # Connect the next encoder node with a MaxPooling layer
tensors[current_node] = unet_utils.convolution_module(pool_tensor, filters=filter_num[encoder - 1], name=current_node, **module_kwargs) # Convolution modules
# Connect the bottom encoder node to a decoder node
upsample_tensor = unet_utils.upsample(tensors[f'En{levels}'], filters=filter_num[levels - 2], name=f'En{levels}-De{levels}', **upsample_kwargs)
""" Bottom decoder node """
current_node, next_node = f'De{levels - 1}', f'De{levels - 2}'
skip_node = f'En{levels - 1}'
tensors[current_node] = Concatenate(name=f'{current_node}_Concatenate')([upsample_tensor, tensors[skip_node]]) # Concatenate the upsampled tensor and skip connection
tensors[current_node] = unet_utils.convolution_module(tensors[current_node], filters=filter_num[levels - 2], name=current_node, **module_kwargs) # Convolution module
upsample_tensor = unet_utils.upsample(tensors[current_node], filters=filter_num[levels - 3], name=f'{current_node}-{next_node}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
for decoder in np.arange(1, levels-1)[::-1]:
num_middle_nodes = levels - decoder - 1
for node in range(1, num_middle_nodes + 1):
if node == 1: # if on the first middle node at the given level
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'En{decoder + 1}'], filters=filter_num[decoder - 2], name=f'En{decoder + 1}-Me{decoder}-1', **upsample_kwargs)
else:
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'Me{decoder + 1}-{node - 1}'], filters=filter_num[decoder - 2], name=f'Me{decoder + 1}-{node - 1}-Me{decoder}-{node}', **upsample_kwargs)
tensors[f'Me{decoder}-{node}'] = Concatenate(name=f'Me{decoder}-{node}_Concatenate')([tensors[f'En{decoder}'], upsample_tensor_for_middle_node])
tensors[f'Me{decoder}-{node}'] = unet_utils.convolution_module(tensors[f'Me{decoder}-{node}'], filters=filter_num[decoder - 1], name=f'Me{decoder}-{node}', **module_kwargs) # Convolution module
if decoder == 1:
tensors[f'sup{decoder}-{node}'] = unet_utils.deep_supervision_side_output(tensors[f'Me{decoder}-{node}'], name=f'sup{decoder}-{node}', **supervision_kwargs) # deep supervision on middle node located on top level
tensors_with_supervision.append(tensors[f'sup{decoder}-{node}'])
tensors[f'De{decoder}'] = Concatenate(name=f'De{decoder}_Concatenate')([tensors[f'En{decoder}'], upsample_tensor]) # Concatenate the upsampled tensor and skip connection
tensors[f'De{decoder}'] = unet_utils.convolution_module(tensors[f'De{decoder}'], filters=filter_num[decoder - 1], name=f'De{decoder}', **module_kwargs) # Convolution module
if decoder != 1: # if not currently on the final decoder node (De1)
upsample_tensor = unet_utils.upsample(tensors[f'De{decoder}'], filters=filter_num[decoder - 2], name=f'De{decoder}-De{decoder - 1}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
else:
tensors['output'] = unet_utils.deep_supervision_side_output(tensors['De1'], name='final', **supervision_kwargs) # Deep supervision - this layer will output the model's prediction
tensors_with_supervision.append(tensors['output'])
model = Model(inputs=tensors['input'], outputs=tensors_with_supervision, name=f'unet_ensemble_{ndims}D')
return model
def unet_plus(
input_shape: tuple[int] | list[int],
num_classes: int,
pool_size: int | tuple[int] | list[int],
upsample_size: int | tuple[int] | list[int],
levels: int,
filter_num: tuple[int] | list[int],
kernel_size: int = 3,
squeeze_dims: int | tuple[int] | list[int] = None,
modules_per_node: int = 5,
batch_normalization: bool = True,
deep_supervision: bool = True,
activation: str = 'relu',
padding: str = 'same',
use_bias: bool = True,
kernel_initializer: str = 'glorot_uniform',
bias_initializer: str = 'zeros',
kernel_regularizer: str = None,
bias_regularizer: str = None,
activity_regularizer: str = None,
kernel_constraint: str = None,
bias_constraint: str = None):
"""
Builds a U-Net+ model.
https://arxiv.org/pdf/1912.05074.pdf
Parameters
----------
input_shape: tuple
Shape of the inputs. The last number in the tuple represents the number of channels/predictors.
num_classes: int
Number of classes/labels that the U-Net will try to predict.
pool_size: tuple or list
Size of the mask in the MaxPooling layers.
upsample_size: tuple or list
Size of the mask in the UpSampling layers.
levels: int
Number of levels in the U-Net. Must be greater than 1.
filter_num: iterable of ints
Number of convolution filters on each level of the U-Net.
kernel_size: int or tuple
Size of the kernel in the convolution layers.
squeeze_dims: int, tuple, or None
Dimensions/axes of the input to squeeze such that the target (y_true) will be smaller than the input.
- (e.g. to remove the third dimension, set this parameter to 2 [axis=2 for the third dimension])
modules_per_node: int
Number of modules in each node of the U-Net.
batch_normalization: bool
Setting this to True will add a batch normalization layer after every convolution in the modules.
deep_supervision: bool
Add deep supervision side outputs to each top node.
NOTE: The final decoder node requires deep supervision and is not affected if this parameter is False.
activation: str
Activation function to use in the modules.
Can be any of tf.keras.activations, 'gaussian', 'gcu', 'leaky_relu', 'prelu', 'smelu', 'snake' (case-insensitive).
padding: str
Padding to use in the convolution layers.
use_bias: bool
Setting this to True will implement a bias vector in the convolution layers used in the modules.
kernel_initializer: str or tf.keras.initializers object
Initializer for the kernel weights matrix in the Conv2D/Conv3D layers.
bias_initializer: str or tf.keras.initializers object
Initializer for the bias vector in the Conv2D/Conv3D layers.
kernel_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the kernel weights matrix in the Conv2D/Conv3D layers.
bias_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the bias vector in the Conv2D/Conv3D layers.
activity_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the output of the Conv2D/Conv3D layers.
kernel_constraint: str or tf.keras.constraints object
Constraint function applied to the kernel matrix of the Conv2D/Conv3D layers.
bias_constraint: str or tf.keras.constrains object
Constraint function applied to the bias vector in the Conv2D/Conv3D layers.
Returns
-------
model: tf.keras.models.Model object
U-Net model.
Raises
------
ValueError
If levels < 2
If input_shape does not have 3 nor 4 dimensions
If the length of filter_num does not match the number of levels
"""
ndims = len(input_shape) - 1 # Number of dimensions in the input image (excluding the last dimension reserved for channels)
if levels < 2:
raise ValueError(f"levels must be greater than 1. Received value: {levels}")
if len(input_shape) > 4 or len(input_shape) < 3:
raise ValueError(f"input_shape can only have 3 or 4 dimensions (2D image + 1 dimension for channels OR a 3D image + 1 dimension for channels). Received shape: {np.shape(input_shape)}")
if len(filter_num) != levels:
raise ValueError(f"length of filter_num ({len(filter_num)}) does not match the number of levels ({levels})")
# Keyword arguments for the convolution modules
module_kwargs = dict({})
module_kwargs['num_modules'] = modules_per_node
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint']:
module_kwargs[arg] = locals()[arg]
# MaxPooling keyword arguments
pool_kwargs = {'pool_size': pool_size}
# Keyword arguments for upsampling
upsample_kwargs = dict({})
for arg in ['activation', 'batch_normalization', 'padding', 'kernel_size', 'use_bias', 'kernel_initializer', 'bias_initializer',
'kernel_regularizer', 'bias_regularizer', 'activity_regularizer', 'kernel_constraint', 'bias_constraint',
'upsample_size']:
upsample_kwargs[arg] = locals()[arg]
# Keyword arguments for the deep supervision output in the final decoder node
supervision_kwargs = dict({})
for arg in ['padding', 'kernel_initializer', 'bias_initializer', 'kernel_regularizer', 'bias_regularizer', 'activity_regularizer',
'kernel_constraint', 'bias_constraint', 'upsample_size', 'squeeze_dims', 'num_classes']:
supervision_kwargs[arg] = locals()[arg]
supervision_kwargs['use_bias'] = True
supervision_kwargs['output_level'] = 1
supervision_kwargs['kernel_size'] = 1
tensors = dict({}) # Tensors associated with each node and skip connections
tensors_with_supervision = [] # list of output tensors. If deep supervision is used, more than one output will be produced
""" Setup the first encoder node with an input layer and a convolution module """
tensors['input'] = Input(shape=input_shape, name='Input')
tensors['En1'] = unet_utils.convolution_module(tensors['input'], filters=filter_num[0], name='En1', **module_kwargs)
""" The rest of the encoder nodes are handled here. Each encoder node is connected with a MaxPooling layer and contains convolution modules """
for encoder in np.arange(2, levels+1): # Iterate through the rest of the encoder nodes
pool_tensor = unet_utils.max_pool(tensors[f'En{encoder - 1}'], name=f'En{encoder - 1}-En{encoder}', **pool_kwargs) # Connect the next encoder node with a MaxPooling layer
tensors[f'En{encoder}'] = unet_utils.convolution_module(pool_tensor, filters=filter_num[encoder - 1], name=f'En{encoder}', **module_kwargs) # Convolution modules
# Connect the bottom encoder node to a decoder node
upsample_tensor = unet_utils.upsample(tensors[f'En{levels}'], filters=filter_num[levels - 2], name=f'En{levels}-De{levels}', **upsample_kwargs)
""" Bottom decoder node """
tensors[f'De{levels - 1}'] = Concatenate(name=f'De{levels - 1}_Concatenate')([upsample_tensor, tensors[f'En{levels - 1}']]) # Concatenate the upsampled tensor and skip connection
tensors[f'De{levels - 1}'] = unet_utils.convolution_module(tensors[f'De{levels - 1}'], filters=filter_num[levels - 2], name=f'De{levels - 1}', **module_kwargs) # Convolution module
upsample_tensor = unet_utils.upsample(tensors[f'De{levels - 1}'], filters=filter_num[levels - 3], name=f'De{levels - 1}-De{levels - 2}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
""" The rest of the decoder nodes (except the final node) are handled in this loop. Each node contains one concatenation of an upsampled tensor and a skip connection """
for decoder in np.arange(1, levels-1)[::-1]:
num_middle_nodes = levels - decoder - 1
for node in range(1, num_middle_nodes + 1):
if node == 1: # if on the first middle node at the given level
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'En{decoder + 1}'], filters=filter_num[decoder - 2], name=f'En{decoder + 1}-Me{decoder}-1', **upsample_kwargs)
tensors[f'Me{decoder}-1'] = Concatenate(name=f'Me{decoder}-1_Concatenate')([tensors[f'En{decoder}'], upsample_tensor_for_middle_node])
else:
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'Me{decoder + 1}-{node - 1}'], filters=filter_num[decoder - 2], name=f'Me{decoder + 1}-{node - 1}-Me{decoder}-{node}', **upsample_kwargs)
tensors[f'Me{decoder}-{node}'] = Concatenate(name=f'Me{decoder}-{node}_Concatenate')([tensors[f'Me{decoder}-{node - 1}'], upsample_tensor_for_middle_node])
tensors[f'Me{decoder}-{node}'] = unet_utils.convolution_module(tensors[f'Me{decoder}-{node}'], filters=filter_num[decoder - 1], name=f'Me{decoder}-{node}', **module_kwargs) # Convolution module
if decoder == 1 and deep_supervision:
tensors[f'sup{decoder}-{node}'] = unet_utils.deep_supervision_side_output(tensors[f'Me{decoder}-{node}'], name=f'sup{decoder}-{node}', **supervision_kwargs) # deep supervision on middle node located on top level
tensors_with_supervision.append(tensors[f'sup{decoder}-{node}'])
tensors[f'De{decoder}'] = Concatenate(name=f'De{decoder}_Concatenate')([tensors[f'Me{decoder}-{num_middle_nodes}'], upsample_tensor]) # Concatenate the upsampled tensor and skip connection
tensors[f'De{decoder}'] = unet_utils.convolution_module(tensors[f'De{decoder}'], filters=filter_num[decoder - 1], name=f'De{decoder}', **module_kwargs) # Convolution module
if decoder != 1: # if not currently on the final decoder node (De1)
upsample_tensor = unet_utils.upsample(tensors[f'De{decoder}'], filters=filter_num[decoder - 2], name=f'De{decoder}-De{decoder - 1}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
else:
tensors['output'] = unet_utils.deep_supervision_side_output(tensors['De1'], **supervision_kwargs) # Deep supervision - this layer will output the model's prediction
tensors_with_supervision.append(tensors['output'])
model = Model(inputs=tensors['input'], outputs=tensors_with_supervision, name=f'unet_plus_{ndims}D')
return model
def unet_2plus(
input_shape: tuple[int] | list[int],
num_classes: int,
pool_size: int | tuple[int] | list[int],
upsample_size: int | tuple[int] | list[int],
levels: int,
filter_num: tuple[int] | list[int],
kernel_size: int = 3,
squeeze_dims: int | tuple[int] | list[int] = None,
modules_per_node: int = 5,
batch_normalization: bool = True,
deep_supervision: bool = True,
activation: str = 'relu',
padding: str = 'same',
use_bias: bool = True,
kernel_initializer: str = 'glorot_uniform',
bias_initializer: str = 'zeros',
kernel_regularizer: str = None,
bias_regularizer: str = None,
activity_regularizer: str = None,
kernel_constraint: str = None,
bias_constraint: str = None):
"""
Builds a U-Net++ model.
https://arxiv.org/pdf/1912.05074.pdf
Parameters
----------
input_shape: tuple
Shape of the inputs. The last number in the tuple represents the number of channels/predictors.
num_classes: int
Number of classes/labels that the U-Net will try to predict.
pool_size: tuple or list
Size of the mask in the MaxPooling layers.
upsample_size: tuple or list
Size of the mask in the UpSampling layers.
levels: int
Number of levels in the U-Net. Must be greater than 1.
filter_num: iterable of ints
Number of convolution filters on each level of the U-Net.
kernel_size: int or tuple
Size of the kernel in the convolution layers.
squeeze_dims: int, tuple, or None
Dimensions/axes of the input to squeeze such that the target (y_true) will be smaller than the input.
- (e.g. to remove the third dimension, set this parameter to 2 [axis=2 for the third dimension])
modules_per_node: int
Number of modules in each node of the U-Net.
batch_normalization: bool
Setting this to True will add a batch normalization layer after every convolution in the modules.
deep_supervision: bool
Add deep supervision side outputs to each top node.
NOTE: The final decoder node requires deep supervision and is not affected if this parameter is False.
activation: str
Activation function to use in the modules.
Can be any of tf.keras.activations, 'gaussian', 'gcu', 'leaky_relu', 'prelu', 'smelu', 'snake' (case-insensitive).
padding: str
Padding to use in the convolution layers.
use_bias: bool
Setting this to True will implement a bias vector in the convolution layers used in the modules.
kernel_initializer: str or tf.keras.initializers object
Initializer for the kernel weights matrix in the Conv2D/Conv3D layers.
bias_initializer: str or tf.keras.initializers object
Initializer for the bias vector in the Conv2D/Conv3D layers.
kernel_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the kernel weights matrix in the Conv2D/Conv3D layers.
bias_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the bias vector in the Conv2D/Conv3D layers.
activity_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the output of the Conv2D/Conv3D layers.
kernel_constraint: str or tf.keras.constraints object
Constraint function applied to the kernel matrix of the Conv2D/Conv3D layers.
bias_constraint: str or tf.keras.constrains object
Constraint function applied to the bias vector in the Conv2D/Conv3D layers.
Returns
-------
model: tf.keras.models.Model object
U-Net model.
Raises
------
ValueError
If levels < 2
If input_shape does not have 3 nor 4 dimensions
If the length of filter_num does not match the number of levels
"""
ndims = len(input_shape) - 1 # Number of dimensions in the input image (excluding the last dimension reserved for channels)
if levels < 2:
raise ValueError(f"levels must be greater than 1. Received value: {levels}")
if len(input_shape) > 4 or len(input_shape) < 3:
raise ValueError(f"input_shape can only have 3 or 4 dimensions (2D image + 1 dimension for channels OR a 3D image + 1 dimension for channels). Received shape: {np.shape(input_shape)}")
if len(filter_num) != levels:
raise ValueError(f"length of filter_num ({len(filter_num)}) does not match the number of levels ({levels})")
# Keyword arguments for the convolution modules
module_kwargs = dict({})
module_kwargs['activation'] = activation
module_kwargs['batch_normalization'] = batch_normalization
module_kwargs['num_modules'] = modules_per_node
module_kwargs['padding'] = padding
module_kwargs['use_bias'] = use_bias
module_kwargs['kernel_initializer'] = kernel_initializer
module_kwargs['bias_initializer'] = bias_initializer
module_kwargs['kernel_regularizer'] = kernel_regularizer
module_kwargs['bias_regularizer'] = bias_regularizer
module_kwargs['activity_regularizer'] = activity_regularizer
module_kwargs['kernel_constraint'] = kernel_constraint
module_kwargs['bias_constraint'] = bias_constraint
# MaxPooling keyword arguments
pool_kwargs = dict({})
pool_kwargs['pool_size'] = pool_size
# Keyword arguments for upsampling
upsample_kwargs = dict({})
upsample_kwargs['activation'] = activation
upsample_kwargs['batch_normalization'] = batch_normalization
upsample_kwargs['padding'] = padding
upsample_kwargs['kernel_initializer'] = kernel_initializer
upsample_kwargs['bias_initializer'] = bias_initializer
upsample_kwargs['kernel_regularizer'] = kernel_regularizer
upsample_kwargs['bias_regularizer'] = bias_regularizer
upsample_kwargs['activity_regularizer'] = activity_regularizer
upsample_kwargs['kernel_constraint'] = kernel_constraint
upsample_kwargs['bias_constraint'] = bias_constraint
upsample_kwargs['upsample_size'] = upsample_size
upsample_kwargs['use_bias'] = use_bias
# Keyword arguments for the deep supervision output in the final decoder node
supervision_kwargs = dict({})
supervision_kwargs['upsample_size'] = upsample_size
supervision_kwargs['use_bias'] = True
supervision_kwargs['squeeze_dims'] = squeeze_dims
supervision_kwargs['padding'] = padding
supervision_kwargs['kernel_initializer'] = kernel_initializer
supervision_kwargs['bias_initializer'] = bias_initializer
supervision_kwargs['kernel_regularizer'] = kernel_regularizer
supervision_kwargs['bias_regularizer'] = bias_regularizer
supervision_kwargs['activity_regularizer'] = activity_regularizer
supervision_kwargs['kernel_constraint'] = kernel_constraint
supervision_kwargs['bias_constraint'] = bias_constraint
tensors = dict({}) # Tensors associated with each node and skip connections
tensors_with_supervision = [] # list of output tensors. If deep supervision is used, more than one output will be produced
""" Setup the first encoder node with an input layer and a convolution module """
tensors['input'] = Input(shape=input_shape, name='Input')
tensors['En1'] = unet_utils.convolution_module(tensors['input'], filters=filter_num[0], kernel_size=kernel_size, name='En1', **module_kwargs)
""" The rest of the encoder nodes are handled here. Each encoder node is connected with a MaxPooling layer and contains convolution modules """
for encoder in np.arange(2, levels+1): # Iterate through the rest of the encoder nodes
pool_tensor = unet_utils.max_pool(tensors[f'En{encoder - 1}'], name=f'En{encoder - 1}-En{encoder}', **pool_kwargs) # Connect the next encoder node with a MaxPooling layer
tensors[f'En{encoder}'] = unet_utils.convolution_module(pool_tensor, filters=filter_num[encoder - 1], kernel_size=kernel_size, name=f'En{encoder}', **module_kwargs) # Convolution modules
# Connect the bottom encoder node to a decoder node
upsample_tensor = unet_utils.upsample(tensors[f'En{levels}'], filters=filter_num[levels - 2], kernel_size=kernel_size, name=f'En{levels}-De{levels}', **upsample_kwargs)
""" Bottom decoder node """
tensors[f'De{levels - 1}'] = Concatenate(name=f'De{levels - 1}_Concatenate')([upsample_tensor, tensors[f'En{levels - 1}']]) # Concatenate the upsampled tensor and skip connection
tensors[f'De{levels - 1}'] = unet_utils.convolution_module(tensors[f'De{levels - 1}'], filters=filter_num[levels - 2], kernel_size=kernel_size, name=f'De{levels - 1}', **module_kwargs) # Convolution module
upsample_tensor = unet_utils.upsample(tensors[f'De{levels - 1}'], filters=filter_num[levels - 3], kernel_size=kernel_size, name=f'De{levels - 1}-De{levels - 2}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
""" The rest of the decoder nodes (except the final node) are handled in this loop. Each node contains one concatenation of an upsampled tensor and a skip connection """
for decoder in np.arange(1, levels-1)[::-1]:
num_middle_nodes = levels - decoder - 1
for node in range(1, num_middle_nodes + 1):
if node == 1: # if on the first middle node at the given level
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'En{decoder + 1}'], filters=filter_num[decoder - 2], kernel_size=kernel_size, name=f'En{decoder + 1}-Me{decoder}-1', **upsample_kwargs)
tensors[f'Me{decoder}-1'] = Concatenate(name=f'Me{decoder}-1_Concatenate')([tensors[f'En{decoder}'], upsample_tensor_for_middle_node])
else:
upsample_tensor_for_middle_node = unet_utils.upsample(tensors[f'Me{decoder + 1}-{node - 1}'], filters=filter_num[decoder - 2], kernel_size=kernel_size, name=f'Me{decoder + 1}-{node - 1}-Me{decoder}-{node}', **upsample_kwargs)
tensors_to_concatenate = [] # Tensors to concatenate in the middle node
connections_to_add = sorted([tensor for tensor in tensors if f'Me{decoder}' in tensor])[::-1] # skip connections to add to the list of tensors to concatenate
for connection in connections_to_add:
tensors_to_concatenate.append(tensors[connection])
tensors_to_concatenate.append(tensors[f'En{decoder}'])
tensors_to_concatenate.append(upsample_tensor_for_middle_node)
tensors[f'Me{decoder}-{node}'] = Concatenate(name=f'Me{decoder}-{node}_Concatenate')(tensors_to_concatenate)
tensors[f'Me{decoder}-{node}'] = unet_utils.convolution_module(tensors[f'Me{decoder}-{node}'], filters=filter_num[decoder - 1], kernel_size=kernel_size, name=f'Me{decoder}-{node}', **module_kwargs) # Convolution module
if decoder == 1 and deep_supervision:
tensors[f'sup{decoder}-{node}'] = unet_utils.deep_supervision_side_output(tensors[f'Me{decoder}-{node}'], num_classes=num_classes, output_level=1, kernel_size=1, name=f'sup{decoder}-{node}', **supervision_kwargs) # deep supervision on middle node located on top level
tensors_with_supervision.append(tensors[f'sup{decoder}-{node}'])
tensors_to_concatenate = [] # tensors to concatenate in the decoder node
connections_to_add = sorted([tensor for tensor in tensors if f'Me{decoder}' in tensor])[::-1] # skip connections to add to the list of tensors to concatenate
for connection in connections_to_add:
tensors_to_concatenate.append(tensors[connection])
tensors_to_concatenate.append(tensors[f'En{decoder}'])
tensors_to_concatenate.append(upsample_tensor)
tensors[f'De{decoder}'] = Concatenate(name=f'De{decoder}_Concatenate')(tensors_to_concatenate) # Concatenate the upsampled tensor and skip connection
tensors[f'De{decoder}'] = unet_utils.convolution_module(tensors[f'De{decoder}'], filters=filter_num[decoder - 1], kernel_size=kernel_size, name=f'De{decoder}', **module_kwargs) # Convolution module
if decoder != 1: # if not currently on the final decoder node (De1)
upsample_tensor = unet_utils.upsample(tensors[f'De{decoder}'], filters=filter_num[decoder - 2], kernel_size=kernel_size, name=f'De{decoder}-De{decoder - 1}', **upsample_kwargs) # Connect the bottom decoder node to the next decoder node
else:
tensors['output'] = unet_utils.deep_supervision_side_output(tensors['De1'], num_classes=num_classes, kernel_size=1, output_level=1, name='final', **supervision_kwargs) # Deep supervision - this layer will output the model's prediction
tensors_with_supervision.append(tensors['output'])
model = Model(inputs=tensors['input'], outputs=tensors_with_supervision, name=f'unet_2plus_{ndims}D')
return model
def unet_3plus(
input_shape: tuple[int] | list[int],
num_classes: int,
pool_size: int | tuple[int] | list[int],
upsample_size: int | tuple[int] | list[int],
levels: int,
filter_num: tuple[int] | list[int],
filter_num_skip: int = None,
filter_num_aggregate: tuple[int] | list[int] = None,
kernel_size: int = 3,
first_encoder_connections: bool = True,
squeeze_dims: int | tuple[int] | list[int] = None,
modules_per_node: int = 5,
batch_normalization: bool = True,
deep_supervision: bool = True,
activation: str = 'relu',
padding: str = 'same',
use_bias: bool = True,
kernel_initializer: str = 'glorot_uniform',
bias_initializer: str = 'zeros',
kernel_regularizer: str = None,
bias_regularizer: str = None,
activity_regularizer: str = None,
kernel_constraint: str = None,
bias_constraint: str = None):
"""
Creates a U-Net 3+.
https://arxiv.org/ftp/arxiv/papers/2004/2004.08790.pdf
Parameters
----------
input_shape: tuple
Shape of the inputs. The last number in the tuple represents the number of channels/predictors.
num_classes: int
Number of classes/labels that the U-Net 3+ will try to predict.
pool_size: tuple or list
Size of the mask in the MaxPooling layers.
upsample_size: tuple or list
Size of the mask in the UpSampling layers.
levels: int
Number of levels in the U-Net 3+. Must be greater than 2.
filter_num: iterable of ints
Number of convolution filters in each encoder of the U-Net 3+. The length must be equal to 'levels'.
filter_num_skip: int or None
Number of convolution filters in the conventional skip connections, full-scale skip connections, and aggregated feature maps.
NOTE: When left as None, this will default to the first value in the 'filter_num' iterable.
filter_num_aggregate: int or None
Number of convolution filters in the decoder nodes after images are concatenated.
When left as None, this will be equal to the product of filter_num_skip and the number of levels.
kernel_size: int or tuple
Size of the kernel in the convolution layers.
first_encoder_connections: bool
Setting this to True will create full-scale skip connections attached to the first encoder node.
squeeze_dims: int, tuple, or None
Dimensions/axes of the input to squeeze such that the target (y_true) will be smaller than the input.
- (e.g. to remove the third dimension, set this parameter to 2 [axis=2 for the third dimension])
modules_per_node: int
Number of modules in each node of the U-Net 3+.
batch_normalization: bool
Setting this to True will add a batch normalization layer after every convolution in the modules.
deep_supervision: bool
Add deep supervision side outputs to each decoder node.
NOTE: The final decoder node requires deep supervision and is not affected if this parameter is False.
activation: str
Activation function to use in the modules.
Can be any of tf.keras.activations, 'gaussian', 'gcu', 'leaky_relu', 'prelu', 'smelu', 'snake' (case-insensitive).
padding: str
Padding to use in the convolution layers.
use_bias: bool
Setting this to True will implement a bias vector in the convolution layers used in the modules.
kernel_initializer: str or tf.keras.initializers object
Initializer for the kernel weights matrix in the Conv2D/Conv3D layers.
bias_initializer: str or tf.keras.initializers object
Initializer for the bias vector in the Conv2D/Conv3D layers.
kernel_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the kernel weights matrix in the Conv2D/Conv3D layers.
bias_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the bias vector in the Conv2D/Conv3D layers.
activity_regularizer: str or tf.keras.regularizers object
Regularizer function applied to the output of the Conv2D/Conv3D layers.
kernel_constraint: str or tf.keras.constraints object
Constraint function applied to the kernel matrix of the Conv2D/Conv3D layers.
bias_constraint: str or tf.keras.constrains object
Constraint function applied to the bias vector in the Conv2D/Conv3D layers.
Returns
-------
model: tf.keras.models.Model object
U-Net 3+ model.
"""
ndims = len(input_shape) - 1 # Number of dimensions in the input image (excluding the last dimension reserved for channels)
if levels < 3:
raise ValueError(f"levels must be greater than 2. Received value: {levels}")
if len(input_shape) > 4 or len(input_shape) < 3:
raise ValueError(f"input_shape can only have 3 or 4 dimensions (2D image + 1 dimension for channels OR a 3D image + 1 dimension for channels). Received shape: {np.shape(input_shape)}")
if len(filter_num) != levels:
raise ValueError(f"length of filter_num ({len(filter_num)}) does not match the number of levels ({levels})")
if filter_num_skip is None:
filter_num_skip = filter_num[0]
if filter_num_aggregate is None:
filter_num_aggregate = levels * filter_num_skip
# print(f"\nCreating model: {ndims}D U-Net 3+")
module_kwargs = dict({})
module_kwargs['kernel_size'] = kernel_size
module_kwargs['activation'] = activation
module_kwargs['batch_normalization'] = batch_normalization
module_kwargs['num_modules'] = modules_per_node
module_kwargs['padding'] = padding
module_kwargs['use_bias'] = use_bias
module_kwargs['kernel_initializer'] = kernel_initializer
module_kwargs['bias_initializer'] = bias_initializer
module_kwargs['kernel_regularizer'] = kernel_regularizer
module_kwargs['bias_regularizer'] = bias_regularizer
module_kwargs['activity_regularizer'] = activity_regularizer
module_kwargs['kernel_constraint'] = kernel_constraint
module_kwargs['bias_constraint'] = bias_constraint
pool_kwargs = dict({})
pool_kwargs['pool_size'] = pool_size
upsample_kwargs = dict({})
upsample_kwargs['activation'] = activation
upsample_kwargs['batch_normalization'] = batch_normalization
upsample_kwargs['kernel_size'] = kernel_size
upsample_kwargs['filters'] = filter_num_skip
upsample_kwargs['padding'] = padding
upsample_kwargs['kernel_initializer'] = kernel_initializer
upsample_kwargs['bias_initializer'] = bias_initializer
upsample_kwargs['kernel_regularizer'] = kernel_regularizer
upsample_kwargs['bias_regularizer'] = bias_regularizer
upsample_kwargs['activity_regularizer'] = activity_regularizer
upsample_kwargs['kernel_constraint'] = kernel_constraint
upsample_kwargs['bias_constraint'] = bias_constraint
upsample_kwargs['upsample_size'] = upsample_size
upsample_kwargs['use_bias'] = use_bias
conventional_kwargs = dict({})
conventional_kwargs['filters'] = filter_num_skip
conventional_kwargs['kernel_size'] = kernel_size
conventional_kwargs['activation'] = activation
conventional_kwargs['batch_normalization'] = batch_normalization
conventional_kwargs['padding'] = padding
conventional_kwargs['use_bias'] = use_bias
conventional_kwargs['kernel_initializer'] = kernel_initializer
conventional_kwargs['bias_initializer'] = bias_initializer
conventional_kwargs['kernel_regularizer'] = kernel_regularizer
conventional_kwargs['bias_regularizer'] = bias_regularizer
conventional_kwargs['activity_regularizer'] = activity_regularizer
conventional_kwargs['kernel_constraint'] = kernel_constraint
conventional_kwargs['bias_constraint'] = bias_constraint
full_scale_kwargs = dict({})
full_scale_kwargs['filters'] = filter_num_skip
full_scale_kwargs['kernel_size'] = kernel_size
full_scale_kwargs['activation'] = activation
full_scale_kwargs['batch_normalization'] = batch_normalization
full_scale_kwargs['use_bias'] = use_bias
full_scale_kwargs['padding'] = padding
full_scale_kwargs['pool_size'] = pool_size
full_scale_kwargs['kernel_initializer'] = kernel_initializer
full_scale_kwargs['bias_initializer'] = bias_initializer
full_scale_kwargs['kernel_regularizer'] = kernel_regularizer
full_scale_kwargs['bias_regularizer'] = bias_regularizer
full_scale_kwargs['activity_regularizer'] = activity_regularizer
full_scale_kwargs['kernel_constraint'] = kernel_constraint
full_scale_kwargs['bias_constraint'] = bias_constraint
aggregated_kwargs = dict({})
aggregated_kwargs['filters'] = filter_num_skip
aggregated_kwargs['kernel_size'] = kernel_size
aggregated_kwargs['activation'] = activation
aggregated_kwargs['batch_normalization'] = batch_normalization
aggregated_kwargs['padding'] = padding
aggregated_kwargs['upsample_size'] = upsample_size
aggregated_kwargs['use_bias'] = use_bias
aggregated_kwargs['kernel_initializer'] = kernel_initializer
aggregated_kwargs['bias_initializer'] = bias_initializer
aggregated_kwargs['kernel_regularizer'] = kernel_regularizer
aggregated_kwargs['bias_regularizer'] = bias_regularizer
aggregated_kwargs['activity_regularizer'] = activity_regularizer
aggregated_kwargs['kernel_constraint'] = kernel_constraint
aggregated_kwargs['bias_constraint'] = bias_constraint
supervision_kwargs = dict({})
supervision_kwargs['upsample_size'] = upsample_size
supervision_kwargs['kernel_size'] = kernel_size
supervision_kwargs['use_bias'] = True
supervision_kwargs['padding'] = padding
supervision_kwargs['squeeze_dims'] = squeeze_dims
supervision_kwargs['kernel_initializer'] = kernel_initializer
supervision_kwargs['bias_initializer'] = bias_initializer
supervision_kwargs['kernel_regularizer'] = kernel_regularizer
supervision_kwargs['bias_regularizer'] = bias_regularizer
supervision_kwargs['activity_regularizer'] = activity_regularizer
supervision_kwargs['kernel_constraint'] = kernel_constraint
supervision_kwargs['bias_constraint'] = bias_constraint
tensors = dict({}) # Tensors associated with each node and skip connections
tensors_with_supervision = [] # Outputs of deep supervision
""" Setup the first encoder node with an input layer and a convolution module (we are not using skip connections here) """
tensors['input'] = Input(shape=input_shape, name='Input')
tensors['En1'] = unet_utils.convolution_module(tensors['input'], filters=filter_num[0], name='En1', **module_kwargs)
if first_encoder_connections is True:
for full_connection in range(2, levels):
tensors[f'1---{full_connection}_full-scale'] = unet_utils.full_scale_skip_connection(tensors[f'En1'], level1=1, level2=full_connection, name=f'1---{full_connection}_full-scale', **full_scale_kwargs)
""" The rest of the encoder nodes are handled here. Each encoder node is connected with a MaxPooling layer and contains convolution modules """
for encoder in np.arange(2, levels): # Iterate through the rest of the encoder nodes
pool_tensor = unet_utils.max_pool(tensors[f'En{encoder - 1}'], name=f'En{encoder - 1}-En{encoder}', **pool_kwargs) # Connect the next encoder node with a MaxPooling layer
tensors[f'En{encoder}'] = unet_utils.convolution_module(pool_tensor, filters=filter_num[encoder - 1], name=f'En{encoder}', **module_kwargs) # Convolution modules
tensors[f'{encoder}---{encoder}_skip'] = unet_utils.conventional_skip_connection(tensors[f'En{encoder}'], name=f'{encoder}---{encoder}_skip', **conventional_kwargs)
# Create full-scale skip connections
for full_connection in range(encoder + 1, levels):
tensors[f'{encoder}---{full_connection}_full-scale'] = unet_utils.full_scale_skip_connection(tensors[f'En{encoder}'], level1=encoder, level2=full_connection, name=f'{encoder}---{full_connection}_full-scale', **full_scale_kwargs)
# Bottom encoder node
tensors[f'En{levels}'] = unet_utils.max_pool(tensors[f'En{levels - 1}'], name=f'En{levels - 1}-En{levels}', **pool_kwargs)
tensors[f'En{levels}'] = unet_utils.convolution_module(tensors[f'En{levels}'], filters=filter_num[levels - 1], name=f'En{levels}', **module_kwargs)
if deep_supervision:
tensors[f'sup{levels}_output'] = unet_utils.deep_supervision_side_output(tensors[f'En{levels}'], num_classes=num_classes, output_level=levels, name=f'sup{levels}', **supervision_kwargs)
tensors_with_supervision.append(tensors[f'sup{levels}_output'])
# Add aggregated feature maps using the bottom encoder node
for feature_map in range(1, levels - 1):
tensors[f'{levels}---{feature_map}_feature'] = unet_utils.aggregated_feature_map(tensors[f'En{levels}'], level1=levels, level2=feature_map, name=f'{levels}---{feature_map}_feature', **aggregated_kwargs)
""" Build the rest of the decoder nodes """
for decoder in np.arange(1, levels)[::-1]:
""" The lowest decoder node (levels - 1) is attached to the bottom encoder node via upsampling, so concatenation is slightly different """
if decoder == levels - 1:
tensors[f'De{decoder}'] = unet_utils.upsample(tensors[f'En{levels}'], name=f'En{levels}-De{decoder}', **upsample_kwargs)
# Tensors to concatenate in the Concatenate layer
tensors_to_concatenate = [tensors[f'De{decoder}'], ]
connections_to_add = sorted([tensor for tensor in tensors if f'---{decoder}' in tensor])[::-1]
for connection in connections_to_add:
tensors_to_concatenate.append(tensors[connection])
else:
tensors[f'De{decoder}'] = unet_utils.upsample(tensors[f'De{decoder + 1}'], name=f'De{decoder + 1}-De{decoder}', **upsample_kwargs)
# Tensors to concatenate in the Concatenate layer
tensors_to_concatenate = sorted([tensor for tensor in tensors if f'---{decoder}' in tensor])[::-1]
for index in range(len(tensors_to_concatenate)):
tensors_to_concatenate[index] = tensors[tensors_to_concatenate[index]]
tensors_to_concatenate.insert(levels - 1 - decoder, tensors[f'De{decoder}'])
# Concatenate tensors, pass through convolution modules, then use deep supervision to create a side output
tensors[f'De{decoder}'] = Concatenate(name=f'De{decoder}_Concatenate')(tensors_to_concatenate)
tensors[f'De{decoder}'] = unet_utils.convolution_module(tensors[f'De{decoder}'], filters=filter_num_aggregate, name=f'De{decoder}', **module_kwargs)
if deep_supervision or decoder == 1: # Decoder node 1 must always have deep supervision
tensors[f'sup{decoder}_output'] = unet_utils.deep_supervision_side_output(tensors[f'De{decoder}'], num_classes=num_classes, output_level=decoder, name=f'sup{decoder}', **supervision_kwargs)
tensors_with_supervision.append(tensors[f'sup{decoder}_output'])
""" Add aggregated feature maps """
for feature_map in range(1, decoder - 1):