|
7 | 7 | from pymic.layer.activation import get_acti_func |
8 | 8 | from pymic.layer.convolution import ConvolutionLayer |
9 | 9 | from pymic.layer.deconvolution import DeconvolutionLayer |
10 | | -from pymic.net3d.unet2d5_ag import UNetBlock |
11 | 10 |
|
| 11 | +class UNetBlock(nn.Module): |
| 12 | + def __init__(self, in_channels, out_chnannels, |
| 13 | + dim, resample, acti_func, acti_func_param): |
| 14 | + super(UNetBlock, self).__init__() |
| 15 | + |
| 16 | + self.in_chns = in_channels |
| 17 | + self.out_chns = out_chnannels |
| 18 | + self.dim = dim |
| 19 | + self.resample = resample # resample should be 'down', 'up', or None |
| 20 | + self.acti_func = acti_func |
| 21 | + |
| 22 | + self.conv1 = ConvolutionLayer(in_channels, out_chnannels, kernel_size = 3, padding=1, |
| 23 | + dim = self.dim, acti_func=get_acti_func(acti_func, acti_func_param)) |
| 24 | + self.conv2 = ConvolutionLayer(out_chnannels, out_chnannels, kernel_size = 3, padding=1, |
| 25 | + dim = self.dim, acti_func=get_acti_func(acti_func, acti_func_param)) |
| 26 | + if(self.resample == 'down'): |
| 27 | + if(self.dim == 2): |
| 28 | + self.resample_layer = nn.MaxPool2d(kernel_size = 2, stride = 2) |
| 29 | + else: |
| 30 | + self.resample_layer = nn.MaxPool3d(kernel_size = 2, stride = 2) |
| 31 | + elif(self.resample == 'up'): |
| 32 | + self.resample_layer = DeconvolutionLayer(out_chnannels, out_chnannels, kernel_size = 2, |
| 33 | + dim = self.dim, stride = 2, acti_func = get_acti_func(acti_func, acti_func_param)) |
| 34 | + else: |
| 35 | + assert(self.resample == None) |
| 36 | + |
| 37 | + def forward(self, x): |
| 38 | + x_shape = list(x.shape) |
| 39 | + if(self.dim == 2 and len(x_shape) == 5): |
| 40 | + [N, C, D, H, W] = x_shape |
| 41 | + new_shape = [N*D, C, H, W] |
| 42 | + x = torch.transpose(x, 1, 2) |
| 43 | + x = torch.reshape(x, new_shape) |
| 44 | + output = self.conv1(x) |
| 45 | + output = self.conv2(output) |
| 46 | + resample = None |
| 47 | + if(self.resample is not None): |
| 48 | + resample = self.resample_layer(output) |
| 49 | + |
| 50 | + if(self.dim == 2 and len(x_shape) == 5): |
| 51 | + new_shape = [N, D] + list(output.shape)[1:] |
| 52 | + output = torch.reshape(output, new_shape) |
| 53 | + output = torch.transpose(output, 1, 2) |
| 54 | + if(resample is not None): |
| 55 | + resample_shape = list(resample.shape) |
| 56 | + new_shape = [N, D] + resample_shape[1:] |
| 57 | + resample = torch.reshape(resample, new_shape) |
| 58 | + resample = torch.transpose(resample, 1, 2) |
| 59 | + return output, resample |
12 | 60 |
|
13 | 61 | class UNet2D5(nn.Module): |
14 | 62 | def __init__(self, params): |
|
0 commit comments