-
Notifications
You must be signed in to change notification settings - Fork 45
/
nnBuildUnits.py
1646 lines (1359 loc) · 70.2 KB
/
nnBuildUnits.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
'''
* Building units for neural networks: conv23D units, residual units, unet units, upsampling unit and so on.
* all kinds of loss functions: softmax, 2d softmax, 3d softmax, dice, multi-organ dice, focal loss, attention based loss...
* kinds of test units
* First implemented in Dec. 2016, and the latest updation is Dec. 2017.
* Dong Nie
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import torch.nn.init as init
import torch.autograd as autograd
from torch.autograd import Variable
from torch.autograd import Function
from itertools import repeat
'''
To have an easy switch between nn.Conv2d and nn.Conv3d
'''
class conv23DUnit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=True, dilation=1, nd=2):
super(conv23DUnit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
elif nd==3:
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
else:
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
def forward(self, x):
return self.conv(x)
'''
To have an easy switch between nn.Conv2d and nn.Conv3d, together with BN
'''
class conv23D_bn_Unit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=True, dilation=1, nd=2):
super(conv23D_bn_Unit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm2d(out_channels)
elif nd==3:
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm3d(out_channels)
else:
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm1d(out_channels)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
# self.relu = nn.ReLU()
def forward(self, x):
return self.bn(self.conv(x))
'''
To have an easy switch between nn.Conv2d and nn.Conv3d, together with BN and relu
'''
class conv23D_bn_relu_Unit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1, bias=True, dilation=1, nd=2):
super(conv23D_bn_relu_Unit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm2d(out_channels)
elif nd==3:
self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm3d(out_channels)
else:
self.conv = nn.Conv1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm1d(out_channels)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
self.relu = nn.ReLU()
def forward(self, x):
# print 'x.shape: ',x.shape
# xx = self.conv(x)
# print 'xx.shape: ', xx.shape
return self.relu(self.bn(self.conv(x)))
'''
To have an easy switch between nn.ConvTranspose2d and nn.ConvTranspose3d
'''
class convTranspose23DUnit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, nd=2):
super(convTranspose23DUnit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
elif nd==3:
self.conv = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
else:
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
def forward(self, x):
return self.conv(x)
'''
To have an easy switch between nn.ConvTranspose2d and nn.ConvTranspose3d, together with BN
'''
class convTranspose23D_bn_Unit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, nd=2):
super(convTranspose23D_bn_Unit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm2d(out_channels)
elif nd==3:
self.conv = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm3d(out_channels)
else:
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm1d(out_channels)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
# self.relu = nn.ReLU()
def forward(self, x):
return self.bn(self.conv(x))
'''
To have an easy switch between nn.ConvTranspose2d and nn.ConvTranspose3d, together with BN and relu
'''
class convTranspose23D_bn_relu_Unit(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, output_padding=0, groups=1, bias=True, dilation=1, nd=2):
super(convTranspose23D_bn_relu_Unit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.conv = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm2d(out_channels)
elif nd==3:
self.conv = nn.ConvTranspose3d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm3d(out_channels)
else:
self.conv = nn.ConvTranspose1d(in_channels, out_channels, kernel_size, stride=stride, padding=padding, output_padding=output_padding, groups=groups, bias=bias, dilation=dilation)
self.bn = nn.BatchNorm1d(out_channels)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
self.relu = nn.ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))
'''
To have an easy switch between nn.Dropout2d and nn.Dropout3d
'''
class dropout23DUnit(nn.Module):
def __init__(self, prob=0, nd=2):
super(dropout23DUnit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.dp = nn.Dropout2d(p=prob)
elif nd==3:
self.dp = nn.Dropout3d(p=prob)
else:
self.dp = nn.Dropout(p=prob)
def forward(self, x):
return self.dp(x)
'''
To have an easy switch between nn.maxPool2D and nn.maxPool3D
'''
class maxPool23DUinit(nn.Module):
def __init__(self, kernel_size, stride, padding=1, dilation=1, nd=2):
super(maxPool23DUinit, self).__init__()
assert nd==1 or nd==2 or nd==3, 'nd is not correctly specified!!!!, it should be {1,2,3}'
if nd==2:
self.pool1 = nn.MaxPool2d(kernel_size=kernel_size,stride=stride,padding=padding, dilation=dilation)
elif nd==3:
self.pool1 = nn.MaxPool3d(kernel_size=kernel_size,stride=stride,padding=padding, dilation=dilation)
else:
self.pool1 = nn.MaxPool1d(kernel_size=kernel_size,stride=stride,padding=padding, dilation=dilation)
def forward(self, x):
return self.pool1(x)
'''
ordinary conv block
'''
class convUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3,stride=1, padding=1, activation=F.relu):
super(convUnit, self).__init__()
self.conv = nn.Conv2d(in_size, out_size, kernel_size, stride, padding)
init.xavier_uniform(self.conv.weight, gain = np.sqrt(2.0))
init.constant(self.conv.bias, 0)
self.bn = nn.BatchNorm2d(out_size)
self.relu = nn.ReLU()
def forward(self, x):
return self.relu(self.bn(self.conv(x)))
'''
two-layer residual unit: two conv without BN and identity mapping
'''
class residualUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3,stride=1, padding=1, activation=F.relu, nd=2):
super(residualUnit, self).__init__()
self.conv1 = conv23DUnit(in_size, out_size, kernel_size, stride, padding, nd=nd)
# init.xavier_uniform(self.conv1.weight, gain = np.sqrt(2.0)) #or gain=1
# init.constant(self.conv1.bias, 0)
self.conv2 = conv23DUnit(out_size, out_size, kernel_size, stride, padding, nd=nd)
# init.xavier_uniform(self.conv2.weight, gain = np.sqrt(2.0)) #or gain=1
# init.constant(self.conv2.bias, 0)
def forward(self, x):
return F.relu(self.conv2(F.elu(self.conv1(x))) + x)
'''
two-layer residual unit: two conv with relu and identity mapping
'''
class residualUnit1(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3,stride=1, padding=1, activation=F.relu, nd=2):
super(residualUnit1, self).__init__()
self.conv1_bn_relu = conv23D_bn_relu_Unit(in_size, out_size, kernel_size, stride, padding, nd=nd)
# self.conv1 = nn.Conv2d(in_size, out_size, kernel_size, stride, padding, bias=False)
# init.xavier_uniform(self.conv1.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv1.bias, 0)
# self.bn1 = nn.BatchNorm2d(out_size)
self.relu = nn.ReLU()
self.conv2_bn_relu = nn.conv23D_bn_relu_Unit(out_size, out_size, kernel_size, stride, padding, nd=nd)
# self.conv2 = nn.Conv2d(out_size, out_size, kernel_size, stride, padding, bias=False)
# init.xavier_uniform(self.conv2.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv2.bias, 0)
# self.bn2 = nn.BatchNorm2d(out_size)
def forward(self, x):
identity_data = x
output = self.conv1_bn_relu(x)
output = self.conv2_bn_relu(output)
# output = self.relu(self.bn1(self.conv1(x)))
# output = self.bn2(self.conv2(output))
output = torch.add(output,identity_data)
output = self.relu(output)
return output
'''
three-layer residual unit: three conv with BN and identity mapping
this one doesn't change the size of channels, which means the in_size is same with out_size
input:
x
output:
bottleneck residual block
By Dong Nie
'''
class residualUnit3(nn.Module):
def __init__(self, in_size, out_size, isDilation=None, isEmptyBranch1=None, activation=F.relu, nd=2):
super(residualUnit3, self).__init__()
# mid_size = in_size/2
mid_size = out_size/2 ###I think it should better be half the out size instead of the input size
# print 'line 74, in and out size are, ',in_size,' ',mid_size
if isDilation:
self.conv1_bn_relu = conv23D_bn_relu_Unit(in_channels=in_size, out_channels=mid_size, kernel_size=1, stride=1, padding=0, dilation=2, nd=nd)
else:
self.conv1_bn_relu = conv23D_bn_relu_Unit(in_channels=in_size, out_channels=mid_size, kernel_size=1, stride=1, padding=0, nd=nd)
# init.xavier_uniform(self.conv1.weight, gain=np.sqrt(2.0)) #or gain=1
# # init.constant(self.conv1.bias, 0)
# self.bn1 = nn.BatchNorm2d(mid_size)
self.relu = nn.ReLU()
if isDilation:
self.conv2_bn_relu = conv23D_bn_relu_Unit(in_channels=mid_size, out_channels=mid_size, kernel_size=3, stride=1, padding=2, dilation=2, nd=nd)
else:
self.conv2_bn_relu = conv23D_bn_relu_Unit(in_channels=mid_size, out_channels=mid_size, kernel_size=3, stride=1, padding=1, nd=nd)
# init.xavier_uniform(self.conv2.weight, gain=np.sqrt(2.0)) #or gain=1
# # init.constant(self.conv2.bias, 0)
# self.bn2 = nn.BatchNorm2d(mid_size)
if isDilation:
self.conv3_bn = conv23D_bn_Unit(in_channels=mid_size, out_channels=out_size, kernel_size=1, stride=1, padding=0, dilation=2, nd=nd)
else:
self.conv3_bn = conv23D_bn_Unit(in_channels=mid_size, out_channels=out_size, kernel_size=1, stride=1, padding=0, nd=nd)
# init.xavier_uniform(self.conv3.weight, gain=np.sqrt(2.0)) #or gain=1
# # init.constant(self.conv3.bias, 0)
# self.bn3 = nn.BatchNorm2d(out_size)
self.isEmptyBranch1 = isEmptyBranch1
if in_size!=out_size or isEmptyBranch1==False:
if isDilation:
self.convX_bn = conv23D_bn_Unit(in_channels=in_size, out_channels=out_size, kernel_size=1, stride=1, padding=0, dilation=2, nd=nd)
else:
self.convX_bn = conv23D_bn_Unit(in_channels=in_size, out_channels=out_size, kernel_size=1, stride=1, padding=0, nd=nd)
# self.bnX = nn.BatchNorm2d(out_size)
def forward(self, x):
identity_data = x
# print 'line 94, size of x is ', x.size()
# output = self.relu(self.bn1(self.conv1(x)))
# output = self.relu(self.bn2(self.conv2(output)))
# output = self.bn3(self.conv3(output))
output = self.conv1_bn_relu(x)
output = self.conv2_bn_relu(output)
output = self.conv3_bn(output)
outSZ = output.size()
idSZ = identity_data.size()
if outSZ[1]!=idSZ[1] or self.isEmptyBranch1==False:
identity_data = self.convX_bn(identity_data)
# identity_data = self.bnX(self.convX(identity_data))
# print output.size(), identity_data.size()
output = torch.add(output,identity_data)
output = self.relu(output)
return output
'''
long-term residual unit, there is a long way (a lot of convs) before the residual addition
By Dong Nie
'''
class longResidualUnit(nn.Module):
def __init__(self,in_size, out_size, kernel_size=3,stride=1, padding=1, activation=F.relu, nd=2):
super(residualUnit1, self).__init__()
self.conv1_bn = conv23D_bn_Unit(in_channels=in_size, out_channels=out_size, kernel_size=kernel_size, stride=stride, padding=padding, nd=nd)
# init.xavier_uniform(self.conv1.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv1.bias, 0)
# self.bn1 = nn.BatchNorm2d(out_size)
self.relu = nn.ReLU()
def forward(self, x):
identity_data = x
output = self.conv1_bn(x)
output = torch.add(output,identity_data)
output = self.relu(output)
return output
'''
Residual upsampling block with long-range residual connection
input:
x: the current layer you want to consider
bridge: the one you want to combine (using summary instead of concatenation) from lower layers
output:
residual output
space_dropout_rate: the rate to make several of the feature maps to be zero (to avoid the correlation within a feature map, we use
spatial dropout instead of traditional dropout
By Dong Nie
'''
class ResUpUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, activation=F.relu, spatial_dropout_rate=0, isConvDilation=None, nd=2):
super(ResUpUnit, self).__init__()
# self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=4, stride=2, padding=1, bias=True)
# init.xavier_uniform(self.up.weight, gain = np.sqrt(2.0)) #or gain=1
# init.constant(self.up.bias, 0)
self.nd = nd
self.up = convTranspose23D_bn_relu_Unit(in_size, out_size, kernel_size=4, stride=2, padding=1, nd=nd)
self.conv = residualUnit3(out_size, out_size, isDilation=isConvDilation, nd=nd)
# self.SpatialDroput = nn.SpatialDropout(space_dropout_rate)
self.dp = dropout23DUnit(prob=spatial_dropout_rate,nd=nd)
# self.dropout2d = nn.Dropout2d(spatial_dropout_rate)
self.spatial_dropout_rate = spatial_dropout_rate
self.conv2 = residualUnit3(out_size, out_size, isDilation=isConvDilation, isEmptyBranch1=False, nd=nd)
# print 'line 147, in_size is ',out_size,' out_size is ',out_size
self.relu = nn.ReLU()
def center_crop(self, layer, target_size): #we should make it adust to 2d/3d
if self.nd ==2:
batch_size, n_channels, layer_width, layer_height = layer.size()
elif self.nd==3:
batch_size, n_channels, layer_width, layer_height, layer_depth = layer.size()
xy1 = (layer_width - target_size) // 2
if self.nd==3:
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
def forward(self, x, bridge):#bridge is the corresponding lower layer
# print 'x.shape: ', x.size()
up = self.up(x)
# print 'up.shape: ',up.size()
# print 'line 158 ',up.size()
#crop1 = self.center_crop(bridge, up.size()[2])
# print 'bridge.size: ', bridge.size()
crop1 = bridge
# crop1_dp = self.SpatialDroput(crop1)
if self.spatial_dropout_rate>0:
crop1 = self.dp(crop1)
out = self.relu(torch.add(up, crop1))
# print 'line 161'
out = self.conv(out)
# print 'line 161 is ', a.size()
# out = self.relu(a)
# out = self.relu(self.conv2(out))
out = self.conv2(out)
# print 'line 163 is ', out.size()
return out
'''
Dilated residual module with two residual block (with diltion k)
Note, here we keep the same resolution size among successive layers
input:
x: input feature map
k: dilation k
output:
y
'''
class DilatedResUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, stride=1, dilation=2, nd=2):
super(DilatedResUnit,self).__init__()
self.nd = nd
mid_size = out_size/1
padding = dilation*(kernel_size-1)/2
self.conv1_bn_relu = conv23D_bn_relu_Unit(in_channels=in_size, out_channels=mid_size, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, nd=nd)
self.conv2_bn_relu = conv23D_bn_relu_Unit(in_channels=mid_size, out_channels=mid_size, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, nd=nd)
self.relu = nn.ReLU()
def forward(self, x):
#dilated module 1
conv1_1 = self.conv1_bn_relu(x)
conv1_2 = self.conv2_bn_relu(conv1_1)
out1 = torch.add(x,conv1_2) # we should make sure x is same size with conv2
#dilated module 2
conv2_1 = self.conv1_bn_relu(out1)
conv2_2 = self.conv2_bn_relu(conv2_1)
out = torch.add(conv2_1,conv2_2)
return out
'''
Basic Residual upsampling block with long-range residual connection. Note we didn't have two
short residual blocks after the long-range residual operation.
input:
x: the current layer you want to consider
bridge: the one you want to combine (using summary instead of concatenation) from lower layers
output:
residual output
By Dong Nie
'''
class BaseResUpUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, activation=F.relu, space_dropout=False, nd=2):
super(BaseResUpUnit, self).__init__()
# self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=4, stride=2, padding=1, bias=True)
# init.xavier_uniform(self.up.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.up.bias, 0)
self.nd = nd
self.up = convTranspose23D_bn_relu_Unit(in_size, out_size, kernel_size=4, stride=2, padding=1, nd=nd)
self.relu = nn.ReLU()
def center_crop(self, layer, target_size): #we should make it adust to 2d/3d
if self.nd ==2:
batch_size, n_channels, layer_width, layer_height = layer.size()
elif self.nd==3:
batch_size, n_channels, layer_width, layer_height, layer_depth = layer.size()
xy1 = (layer_width - target_size) // 2
if self.nd==3:
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
def forward(self, x, bridge):#bridge is the corresponding lower layer
up = self.up(x)
# print 'line 158 ',up.size()
# crop1 = self.center_crop(bridge, up.size()[2])
crop1 = bridge
out = self.relu(torch.add(up, crop1))
# print 'line 161'
# a = self.conv(out)
# # print 'line 161 is ', a.size()
# out = self.relu(a)
# out = self.relu(self.conv2(out))
# print 'line 163 is ', out.size()
return out
'''
upsample unit: first upsample (directly interpolation, and then conv_bn_relu
'''
class upsampleUnit(nn.Module):
# Implements resize-convolution
def __init__(self, in_channels, out_channels, nd=2):
super(upsampleUnit, self).__init__()
self.upsample1 = nn.Upsample(scale_factor=2, mode='nearest')
self.conv1_bn_relu = conv23D_bn_relu_Unit(in_channels, out_channels, 3, stride=1, padding=1, nd=nd)
def forward(self, x):
return self.conv1_bn_relu(x)
'''
unetConvUnit: actually, a basic unit composed of two-layer convolutional layers
'''
class unetConvUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, activation=F.relu, nd=2):
super(unetConvUnit, self).__init__()
# self.conv = nn.Conv2d(in_size, out_size, kernel_size=3, stride=1, padding=1, bias=True)
# init.xavier_uniform(self.conv.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv.bias, 0)
self.conv = conv23DUnit(in_size, out_size, kernel_size=3, stride=1, padding=1, nd=nd)
self.conv2 = conv23DUnit(out_size, out_size, kernel_size=3, stride=1, padding=1, nd=nd)
# self.conv2 = nn.Conv2d(out_size, out_size, kernel_size=3, stride=1, padding=1, bias=True)
# init.xavier_uniform(self.conv2.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv2.bias, 0)
self.activation = activation
def forward(self, x):
out = self.activation(self.conv(x))
out = self.activation(self.conv2(out))
return out
'''
unet upsampling block
'''
class unetUpUnit(nn.Module):
def __init__(self, in_size, out_size, kernel_size=3, activation=F.relu, space_dropout=False, nd=2):
super(unetUpUnit, self).__init__()
# self.up = nn.ConvTranspose2d(in_size, out_size, kernel_size=4, stride=2, padding=1, bias=True)
# init.xavier_uniform(self.up.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.up.bias, 0)
self.up = convTranspose23DUnit(in_size, out_size, kernel_size=4, stride=2, padding=1, nd=nd)
# self.conv = nn.Conv2d(in_size, out_size, kernel_size=3, stride=1, padding=1, bias=True)
# init.xavier_uniform(self.conv.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv.bias, 0)
self.conv = conv23DUnit(in_size, out_size, kernel_size=3, stride=1, padding=1, nd=nd) #has some problem with the in_size
# self.conv2 = nn.Conv2d(out_size, out_size, kernel_size=3, stride=1, padding=1, bias=True)
# init.xavier_uniform(self.conv2.weight, gain=np.sqrt(2.0)) #or gain=1
# init.constant(self.conv2.bias, 0)
self.conv2 = conv23DUnit(out_size, out_size, kernel_size=3, stride=1, padding=1, nd=nd)
self.activation = activation
self.nd = nd
def center_crop(self, layer, target_size): #we should make it adust to 2d/3d
if self.nd ==2:
batch_size, n_channels, layer_width, layer_height = layer.size()
elif self.nd==3:
batch_size, n_channels, layer_width, layer_height, layer_depth = layer.size()
xy1 = (layer_width - target_size) // 2
if self.nd==3:
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
return layer[:, :, xy1:(xy1 + target_size), xy1:(xy1 + target_size)]
def forward(self, x, bridge):#bridge is the corresponding lower layer
up = self.up(x)
# crop1 = self.center_crop(bridge, up.size()[2])
crop1 = bridge
out = torch.cat([up, crop1], 1)
out = self.activation(self.conv(out))
out = self.activation(self.conv2(out))
return out
'''
The weighted cross entropy loss for 3D data, usually used in voxel wise segmentation.
input:
predict: 5D tensor, even Variable: NxCxHXWXD
target: 4D tensor, even Variable: NxHxWxD
weight_map: 4D tensor, NxHxWxD
output:
loss
Feb, 2018
By Dong Nie
'''
class WeightedCrossEntropy3d(nn.Module):
def __init__(self, weight = None, size_average=True, reduce = True, ignore_label=255):
'''weight (Tensor, optional): a manual rescaling weight given to each class.
If given, has to be a Tensor of size "nclasses"'''
super(WeightedCrossEntropy3d, self).__init__()
self.weight = weight
self.size_average = size_average
self.ignore_label = ignore_label
self.nll_loss = nn.NLLLoss(weight, size_average=False, reduce=False)
self.logsoftmax = nn.LogSoftmax(dim=1)
def forward(self, predict, target, weight_map=None):
"""
Args:
predict:(n, c, h, w, d)
target:(n, h, w, d): 0,1,...,C-1
"""
assert not target.requires_grad
assert predict.dim() == 5
assert target.dim() == 4
assert predict.size(0) == target.size(0), "{0} vs {1} ".format(predict.size(0), target.size(0))
assert predict.size(2) == target.size(1), "{0} vs {1} ".format(predict.size(2), target.size(1))
assert predict.size(3) == target.size(2), "{0} vs {1} ".format(predict.size(3), target.size(2))
assert predict.size(4) == target.size(3), "{0} vs {1} ".format(predict.size(4), target.size(3))
n, c, h, w, d = predict.size()
logits = self.logsoftmax(predict) #NxCxWxHxD
voxel_loss = self.nll_loss(logits, target) #NxWxHxD
weighted_voxel_loss = weight_map*voxel_loss
loss = torch.sum(weighted_voxel_loss)/(n*h*w*d)
# print 'cross-entropy-loss: ',type(loss)
return loss
'''
The cross entropy loss for 3D data, usually used in voxel wise segmentation.
input:
predict: 5D tensor, even Variable: NxCxHXWXD
target: 4D tensor, even Variable: NxHxWxD
output:
loss
By Dong Nie
'''
class CrossEntropy3d(nn.Module):
def __init__(self, weight = None, size_average=True, ignore_label=255):
'''weight (Tensor, optional): a manual rescaling weight given to each class.
If given, has to be a Tensor of size "nclasses"'''
super(CrossEntropy3d, self).__init__()
self.weight = weight
self.size_average = size_average
self.ignore_label = ignore_label
def forward(self, predict, target):
"""
Args:
predict:(n, c, h, w, d)
target:(n, h, w, d): 0,1,...,C-1
"""
assert not target.requires_grad
assert predict.dim() == 5
assert target.dim() == 4
assert predict.size(0) == target.size(0), "{0} vs {1} ".format(predict.size(0), target.size(0))
assert predict.size(2) == target.size(1), "{0} vs {1} ".format(predict.size(2), target.size(1))
assert predict.size(3) == target.size(2), "{0} vs {1} ".format(predict.size(3), target.size(2))
assert predict.size(4) == target.size(3), "{0} vs {1} ".format(predict.size(4), target.size(3))
n, c, h, w, d = predict.size()
target_mask = (target >= 0) * (target != self.ignore_label) #actually, it doesn't convert to one-hot format
target = target[target_mask] #N*1
predict = predict.transpose(1, 2).transpose(2, 3).transpose(3, 4).contiguous() # n, h, w, d, c
predict = predict[target_mask.view(n, h, w, d, 1).repeat(1, 1, 1, 1, c)].view(-1, c) #N*C
loss = F.cross_entropy(predict, target, weight = self.weight, size_average = self.size_average)
# print 'cross-entropy-loss: ',type(loss)
return loss
'''
The cross entropy loss for 2D data, usually used in pixel wise segmentation.
input:
predict: 4D tensor, even Variable
target: 3D tensor, even Variable
output:
loss
By Dong Nie
'''
class CrossEntropy2d(nn.Module):
def __init__(self, weight = None, size_average=True, ignore_label=255):
'''weight (Tensor, optional): a manual rescaling weight given to each class.
If given, has to be a Tensor of size "nclasses"'''
super(CrossEntropy2d, self).__init__()
self.weight = weight
self.size_average = size_average
self.ignore_label = ignore_label
def forward(self, predict, target):
"""
Args:
predict:(n, c, h, w)
target:(n, h, w): 0,1,...,C-1
"""
assert not target.requires_grad
assert predict.dim() == 4
assert target.dim() == 3
assert predict.size(0) == target.size(0), "{0} vs {1} ".format(predict.size(0), target.size(0))
assert predict.size(2) == target.size(1), "{0} vs {1} ".format(predict.size(2), target.size(1))
assert predict.size(3) == target.size(2), "{0} vs {1} ".format(predict.size(3), target.size(3))
n, c, h, w = predict.size()
target_mask = (target >= 0) * (target != self.ignore_label)
target = target[target_mask]
predict = predict.transpose(1, 2).transpose(2, 3).contiguous()
predict = predict[target_mask.view(n, h, w, 1).repeat(1, 1, 1, c)].view(-1, c)
loss = F.cross_entropy(predict, target, weight = self.weight, size_average = self.size_average)
# print 'cross-entropy-loss: ',type(loss)
return loss
'''
The cross entropy loss for 2D dataset (usually used in FCN based segmentation)
implemented by using nn.LLLoss2d, we use F.log_softmax to implement log_softmax in 2D.
This one is believed to be stable and also faster
'''
class CrossEntropyLoss2d(nn.Module):
def __init__(self, weight=None, size_average=True):
super(CrossEntropyLoss2d, self).__init__()
self.nll_loss = nn.NLLLoss2d(weight, size_average)
def forward(self, inputs, targets):
return self.nll_loss(F.log_softmax(inputs), targets)
'''
This criterion is a implementation of Focal Loss, which is proposed in
Focal Loss for Dense Object Detection.
Now I implement it in the environment of segmentation
Loss(x, class) = - \alpha (1-softmax(x)[class])^gamma \log(softmax(x)[class])
The losses are averaged across observations for each minibatch.
Input:
class_num: the number of categories
alpha(1D Tensor, Variable) : the scalar factor for this criterion
gamma: aim at reducing the relative loss for the well classified examples, focusing more on hard, misclassified example
size_average: true by default, the losses are averaged over observations for each minibatch, if set by false, it will summaried for each minibatch
inputs: a 4D tensor for the predicted segmentation maps (before softmax), NXCXWXH
targets: a 3D tensor for the ground truth segmentation maps, NXWXH
Output:
The averaged losses
10/31/2017
By Dong Nie
'''
class myFocalLoss(nn.Module):
def __init__(self, class_num, alpha=None, gamma=2, size_average=True):
super(myFocalLoss, self).__init__()
if alpha is None:
self.alpha = Variable(torch.ones(class_num, 1))
else:
if isinstance(alpha, Variable):
self.alpha = alpha
else:
self.alpha = Variable(alpha)
self.gamma = gamma
self.class_num = class_num
self.size_average = size_average
def forward(self, inputs, targets):
assert inputs.dim()==4,'inputs size should be 4: NXCXWXH'
N = inputs.size(0)
C = inputs.size(1)
W = inputs.size(2)
H = inputs.size(3)
P = F.softmax(inputs,dim=1)
## one hot embeding for the targets ##
class_mask = inputs.data.new(N, C, W, H).fill_(0)
class_mask = Variable(class_mask)
targets = torch.unsqueeze(targets,1) #Nx1xHxW
class_mask.scatter_(1, targets, 1) #scatter along the 'numOfDims' dimension
# ids = targets.view(-1, 1)
# class_mask.scatter_(1, ids.data, 1.)
#print(class_mask)
if inputs.is_cuda and not self.alpha.is_cuda:
self.alpha = self.alpha.cuda()
# alpha = self.alpha[ids.data.view(-1)]
alpha = 0.25
probs = (P*class_mask).sum(1).view(-1,1)
log_p = probs.log()
#print('probs size= {}'.format(probs.size()))
#print(probs)
batch_loss = -alpha*(torch.pow((1-probs), self.gamma))*log_p
#print('-----bacth_loss------')
#print(batch_loss)
if self.size_average:
loss = batch_loss.mean()
else:
loss = batch_loss.sum()
return loss
'''
Dice cost function for a single organ
input:
input: a torch variable of size BatchxnclassesxHxW representing probabilities for each class
target: a a also tensor, with batchx1xHxW
output:
Variable scalar loss
succeed for two type segmentation
'''
def myDiceLoss4Organ(input,target):
# assert input.size() == target.size(), "Input sizes must be equal."
assert input.dim() == 4 or input.dim() == 5, "Input must be a 4D Tensor or a 5D tensor."
eps = Variable(torch.cuda.FloatTensor(1).fill_(0.000001))
one = Variable(torch.cuda.FloatTensor(1).fill_(1.0))
two = Variable(torch.cuda.FloatTensor(1).fill_(2.0))
target1 = Variable(torch.unsqueeze(target.data,1)) #Nx1xHxW or Nx1xHxWxD
target_one_hot = Variable(torch.cuda.FloatTensor(input.size()).zero_()) #NxCxHxW or NxCxHxWxD
# target_one_hot = target_one_hot.permute(0,2,3,1) #NxHxWxC
target_one_hot.scatter_(1, target1, 1) #scatter along the 'numOfDims' dimension
uniques=np.unique(target_one_hot.data.cpu().numpy())
assert set(list(uniques))<=set([0,1]), "target must only contain zeros and ones"
# print 'line 330: size: ',target_one_hot.size()
probs = F.softmax(input,dim=1) #maybe it is not necessary
# print 'line 331: size: ',probs.size()
target = target_one_hot.contiguous().view(-1,1).squeeze(1)
result = probs.contiguous().view(-1,1).squeeze(1)
# print 'unique(target): ',unique(target),' unique(result): ',unique(result)
# intersect = torch.dot(result, target) #it doesn't support autograd
intersect_vec = result * target
intersect = torch.sum(intersect_vec)
target_sum = torch.sum(target)
result_sum = torch.sum(result)
union = result_sum + target_sum + (two*eps)
# print 'type of union: ',type(union)
# the target volume can be empty - so we still want to
# end up with a score of 1 if the result is 0/0
IoU = intersect / union
# out = torch.add(out, IoU.data*2)
dice_total = one - two*IoU
# dice_total = -1*torch.sum(dice_eso)/dice_eso.size(0)#divide by batch_sz
# print 'type of dice_total: ', type(dice_total)
return dice_total
'''
This is dice loss for more than one organs, which means you can compute dice loss for more than one organ at a time,
input:
inputs: predicted segmentation map, tensor type, even Variable
targets: real segmentation map, tensor type, even Variable
output:
loss: Variable scalar
succeed for multiple class segmentation problem
'''
def myDiceLoss4Organs(inputs, targets):
eps = Variable(torch.cuda.FloatTensor(1).fill_(0.000001))
one = Variable(torch.cuda.FloatTensor(1).fill_(1.0))
two = Variable(torch.cuda.FloatTensor(1).fill_(2.0))
inputSZ = inputs.size() #it should be sth like NxCxHxW
inputs = F.softmax(inputs,dim=1)
_, results_ = inputs.max(1)
results = torch.squeeze(results_) #NxHxW
numOfCategories = inputSZ[1]
####### Convert categorical to one-hot format
targetSZ = results.size() #NxHxW
## We consider NxHxW 3D tensor
# result1 = torch.unsqueeze(results, 1) #Nx1xHxW
# results_one_hot = Variable(torch.cuda.FloatTensor(inputSZ).zero_()) #NxCxHxW
# results_one_hot.scatter_(1,result1,1) #scatter along the 'numOfDims' dimension
results_one_hot = inputs
target1 = Variable(torch.unsqueeze(targets.data,1)) #Nx1xHxW
targets_one_hot = Variable(torch.cuda.FloatTensor(inputSZ).zero_()) #NxCxHxW
# targets_one_hot = targets_one_hot.permute(0,2,3,1) #NxHxWxC
targets_one_hot.scatter_(1, target1, 1) #scatter along the 'numOfDims' dimension
# print 'line 367: one_hot size: ',targets_one_hot.size()
###### Now the prediction and target has become one-hot format
###### Compute the dice for each organ
# intersects = Variable(torch.FloatTensor(numOfCategories).zero_())
# unions = Variable(torch.FloatTensor(numOfCategories).zero_())
out = Variable(torch.cuda.FloatTensor(1).zero_(), requires_grad = True)
# intersect = Variable(torch.cuda.FloatTensor([1]).zero_(), requires_grad = True)
# union = Variable(torch.cuda.FloatTensor([1]).zero_(), requires_grad = True)
for organID in range(0, numOfCategories):
# target = targets_one_hot[:,organID,:,:].contiguous().view(-1,1).squeeze(1)
# result = results_one_hot[:,organID,:,:].contiguous().view(-1,1).squeeze(1)
target = targets_one_hot[:,organID,...].contiguous().view(-1,1).squeeze(1) #can be used as 2D/3D
result = results_one_hot[:,organID,...].contiguous().view(-1,1).squeeze(1) #can be used as 2D/3D
# print 'unique(target): ',unique(target),' unique(result): ',unique(result)
# intersect = torch.dot(result, target)
intersect_vec = result * target
intersect = torch.sum(intersect_vec)
# print type(intersect)
# binary values so sum the same as sum of squares
result_sum = torch.sum(result)
# print type(result_sum)
target_sum = torch.sum(target)
union = result_sum + target_sum + (two*eps)
# the target volume can be empty - so we still want to
# end up with a score of 1 if the result is 0/0
IoU = intersect / union
# out = torch.add(out, IoU.data*2)
out = out + one - two*IoU
# intersects[organID], unions[organID] = intersect, union
# print('organID: {} union: {:.3f}\t intersect: {:.6f}\t target_sum: {:.0f} IoU: result_sum: {:.0f} IoU {:.7f}'.format(
# organID, union.data[0], intersect.data[0], target_sum.data[0], result_sum.data[0], IoU.data[0])
denominator = Variable(torch.cuda.FloatTensor(1).fill_(numOfCategories))
out = out / denominator
# print type(out)
return out
'''
Function to calculate the Generalised Dice Loss defined in Sudre, C. et. al.
(2017) Generalised Dice overlap as a deep learning loss function for highly
unbalanced segmentations. DLMIA 2017
The only issue I have is that it may only suits to two types
Input:
prediction: the logits (before softmax)
ground_truth: the segmentation ground truth
weight_map:
type_weight: type of weighting allowed between labels (choice
between Square (square of inverse of volume), Simple (inverse of volume)
and Uniform (no weighting))
Output:
the loss
'''
def generalised_dice_loss(prediction, ground_truth, weight_map=None, type_weight='Square'):
ground_truth = tf.to_int64(ground_truth)
n_voxels = ground_truth.get_shape()[0].value
n_classes = prediction.get_shape()[1].value
prediction = tf.nn.softmax(prediction)
ids = tf.constant(np.arange(n_voxels), dtype=tf.int64)
ids = tf.stack([ids, ground_truth], axis=1)
one_hot = tf.SparseTensor(indices=ids,
values=tf.ones([n_voxels], dtype=tf.float32),
dense_shape=[n_voxels, n_classes])
if weight_map is not None:
weight_map_nclasses = tf.reshape(
tf.tile(weight_map, [n_classes]), prediction.get_shape())
ref_vol = tf.sparse_reduce_sum(
weight_map_nclasses * one_hot, reduction_axes=[0])
intersect = tf.sparse_reduce_sum(
weight_map_nclasses * one_hot * prediction, reduction_axes=[0])
seg_vol = tf.reduce_sum(
tf.multiply(weight_map_nclasses, prediction), 0)
else:
ref_vol = tf.sparse_reduce_sum(one_hot, reduction_axes=[0])
intersect = tf.sparse_reduce_sum(one_hot * prediction,
reduction_axes=[0])
seg_vol = tf.reduce_sum(prediction, 0)
if type_weight == 'Square':
weights = tf.reciprocal(tf.square(ref_vol))
elif type_weight == 'Simple':
weights = tf.reciprocal(ref_vol)
elif type_weight == 'Uniform':
weights = tf.ones_like(ref_vol)
else:
raise ValueError("The variable type_weight \"{}\"" \
"is not defined.".format(type_weight))
new_weights = tf.where(tf.is_inf(weights), tf.zeros_like(weights), weights)
weights = tf.where(tf.is_inf(weights), tf.ones_like(weights) *
tf.reduce_max(new_weights), weights)
generalised_dice_numerator = \
2 * tf.reduce_sum(tf.multiply(weights, intersect))
generalised_dice_denominator = \
tf.reduce_sum(tf.multiply(weights, seg_vol + ref_vol))
generalised_dice_score = \
generalised_dice_numerator / generalised_dice_denominator
return 1 - generalised_dice_score
'''