forked from ChristophReich1996/Cell-DETR
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backbone.py
217 lines (200 loc) · 10.1 KB
/
backbone.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
from typing import Tuple, Type, List
import torch
import torch.nn as nn
class ResNetBlock(nn.Module):
"""
This class implements a simple Res-Net block with two convolutions, each followed by a normalization step and an
activation function, and a residual mapping.
"""
def __init__(self, in_channels: int, out_channels: int, convolution: Type = nn.Conv2d,
normalization: Type = nn.InstanceNorm2d, activation: Type = nn.PReLU,
pooling: Type = nn.AvgPool2d) -> None:
"""
Constructor method
:param in_channels: (int) Number of input channels
:param out_channels: (int) Number of output channels
:param convolution: (Type) Type of convolution to be utilized
:param normalization: (Type) Type of normalization to be utilized
:param activation: (Type) Type of activation function to be utilized
:param pooling: (Type) Type of pooling operation to be utilized
"""
# Call super constructor
super(ResNetBlock, self).__init__()
# Init main mapping
self.main_mapping = nn.Sequential(
convolution(in_channels=in_channels, out_channels=in_channels, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1), bias=True),
normalization(num_features=in_channels, affine=True, track_running_stats=True),
activation(),
convolution(in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1), bias=True),
normalization(num_features=out_channels, affine=True, track_running_stats=True),
activation()
)
# Init residual mapping
self.residual_mapping = convolution(in_channels=in_channels, out_channels=out_channels, kernel_size=(1, 1),
stride=(1, 1), padding=(0, 0),
bias=True) if in_channels != out_channels else nn.Identity()
# Init pooling
self.pooling = pooling(kernel_size=(2, 2))
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""
Forward method
:param input: (torch.Tensor) Input tensor of shape (batch size, input channels, height, width)
:return: (torch.Tensor) Output tensor of shape (batch size, output channels, height // 2, width // 2)
"""
# Perform main mapping
output = self.main_mapping(input)
# Perform residual mapping
output = output + self.residual_mapping(input)
# Perform pooling
output = self.pooling(output)
return output
class StandardBlock(nn.Module):
"""
This class implements a standard convolution block including two convolutions, each followed by a normalization and
an activation function.
"""
def __init__(self, in_channels: int, out_channels: int, convolution: Type = nn.Conv2d,
normalization: Type = nn.InstanceNorm2d, activation: Type = nn.PReLU,
pooling: Type = nn.AvgPool2d) -> None:
"""
Constructor method
:param in_channels: (int) Number of input channels
:param out_channels: (int) Number of output channels
:param convolution: (Type) Type of convolution to be utilized
:param normalization: (Type) Type of normalization to be utilized
:param activation: (Type) Type of activation function to be utilized
:param pooling: (Type) Type of pooling operation to be utilized
"""
# Call super constructor
super(StandardBlock, self).__init__()
# Init main mapping
self.main_mapping = nn.Sequential(
convolution(in_channels=in_channels, out_channels=in_channels, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1), bias=True),
normalization(num_features=in_channels, affine=True, track_running_stats=True),
activation(),
convolution(in_channels=in_channels, out_channels=out_channels, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1), bias=True),
normalization(num_features=out_channels, affine=True, track_running_stats=True),
activation()
)
# Init pooling
self.pooling = pooling(kernel_size=(2, 2))
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""
Forward method
:param input: (torch.Tensor) Input tensor of shape (batch size, input channels, height, width)
:return: (torch.Tensor) Output tensor of shape (batch size, output channels, height // 2, width // 2)
"""
# Perform main mapping
output = self.main_mapping(input)
# Perform pooling
output = self.pooling(output)
return output
class DenseNetBlock(nn.Module):
"""
This class implements a Dense-Net block including two convolutions, each followed by a normalization and
an activation function, and skip connections for each convolution
"""
def __init__(self, in_channels: int, out_channels: int, convolution: Type = nn.Conv2d,
normalization: Type = nn.InstanceNorm2d, activation: Type = nn.PReLU,
pooling: Type = nn.AvgPool2d) -> None:
"""
Constructor method
:param in_channels: (int) Number of input channels
:param out_channels: (int) Number of output channels
:param convolution: (Type) Type of convolution to be utilized
:param normalization: (Type) Type of normalization to be utilized
:param activation: (Type) Type of activation function to be utilized
:param pooling: (Type) Type of pooling operation to be utilized
"""
# Call super constructor
super(DenseNetBlock, self).__init__()
# Calc convolution filters
filters, additional_filters = divmod(out_channels - in_channels, 2)
# Init fist mapping
self.first_mapping = nn.Sequential(
convolution(in_channels=in_channels, out_channels=filters, kernel_size=(3, 3), stride=(1, 1),
padding=(1, 1), bias=True),
normalization(num_features=filters, affine=True, track_running_stats=True),
activation()
)
# Init second mapping
self.second_mapping = nn.Sequential(
convolution(in_channels=in_channels + filters, out_channels=filters + additional_filters,
kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=True),
normalization(num_features=filters + additional_filters, affine=True, track_running_stats=True),
activation()
)
# Init pooling
self.pooling = pooling(kernel_size=(2, 2))
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""
Forward method
:param input: (torch.Tensor) Input tensor of shape (batch size, input channels, height, width)
:return: (torch.Tensor) Output tensor of shape (batch size, output channels, height // 2, width // 2)
"""
# Perform main mapping
output = torch.cat((input, self.first_mapping(input)), dim=1)
# Perform main mapping
output = torch.cat((output, self.second_mapping(output)), dim=1)
# Perform pooling
output = self.pooling(output)
return output
class Backbone(nn.Module):
"""
This class implements the backbone network.
"""
def __init__(self, channels: Tuple[Tuple[int, int], ...] = ((1, 16), (16, 32), (32, 64), (64, 128), (128, 256)),
block: Type = StandardBlock, convolution: Type = nn.Conv2d, normalization: Type = nn.InstanceNorm2d,
activation: Type = nn.PReLU, pooling: Type = nn.AvgPool2d) -> None:
"""
Constructor method
:param channels: (Tuple[Tuple[int, int]]) In and output channels of each block
:param block: (Type) Basic block to be used
:param convolution: (Type) Type of convolution to be utilized
:param normalization: (Type) Type of normalization to be utilized
:param activation: (Type) Type of activation function to be utilized
:param pooling: (Type) Type of pooling operation to be utilized
"""
# Call super constructor
super(Backbone, self).__init__()
# Init input convolution
self.input_convolution = nn.Sequential(convolution(in_channels=channels[0][0], out_channels=channels[0][1],
kernel_size=(7, 7), stride=(1, 1), padding=(3, 3),
bias=True),
pooling(kernel_size=(2, 2)))
# Init blocks
self.blocks = nn.ModuleList([
block(in_channels=channel[0], out_channels=channel[1], convolution=convolution, normalization=normalization,
activation=activation, pooling=pooling) for channel in channels])
# Init weights
for module in self.modules():
# Case if module is convolution
if isinstance(module, nn.Conv2d):
nn.init.kaiming_uniform_(module.weight, a=1)
nn.init.constant_(module.bias, 0)
# Deformable convolution is already initialized in the right way
# Init PReLU
elif isinstance(module, nn.PReLU):
nn.init.constant_(module.weight, 0.2)
def forward(self, input: torch.Tensor) -> Tuple[torch.Tensor, List[torch.Tensor]]:
"""
Forward pass
:param input: (torch.Tensor) Input image of shape (batch size, input channels, height, width)
:return: (torch.Tensor) Output tensor (batch size, output channels, height // 2 ^ depth, width // 2 ^ depth) and
features of each stage of the backbone network
"""
# Init list to store feature maps
feature_maps = []
# Forward pass of all blocks
for index, block in enumerate(self.blocks):
if index == 0:
input = block(input) + self.input_convolution(input)
feature_maps.append(input)
else:
input = block(input)
feature_maps.append(input)
return input, feature_maps