-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
338 lines (250 loc) · 9.89 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
def concat_input(in_type, patch_image, patch_grid):
''' Returns the defined feature (eventually concatenated).'''
if in_type == 'rgb':
patch_in = patch_image
elif in_type == 'xy':
patch_in = patch_grid
else:
patch_in = torch.cat((patch_image, patch_grid.float()), dim=1)
return patch_in
def getmodel(setting, in_chn=5, out_chn=22):
''' Returns a model.
The model can be a CNN, Fully Connected Net, Densenet or U-Net, depending ob the
setting['name'] that has been chosen.
Args:
setting: A dict including the setting for the data, model and training.
Returns:
A Model.
'''
if setting['name'] == "CNN_Net":
model = CNN_Net(in_chn, out_chn, setting['kernel_size'], setting['width'], setting['depth'], setting['input']).to(setting['dev'])
if setting['name'] == "FC_Net":
model = FC_Net(in_chn, out_chn, setting['width'], setting['depth'], setting['input']).to(setting['dev'])
if setting['name'] == "DenseNet":
model = DenseNet(in_chn, out_chn, setting['input']).to(setting['dev'])
if setting['name'] == "UNet":
model = UNet(in_chn, out_chn, width = setting['width'], in_type=setting['input']).to(setting['dev'])
return model
def conv_relu(width, kernel_size):
return nn.Sequential(
nn.Conv2d(width, width, kernel_size=kernel_size, padding=kernel_size//2),
nn.ReLU()
)
def linear_relu(width):
return nn.Sequential(
nn.Linear(width, width),
nn.ReLU()
)
class CNN_Net(nn.Module):
''' CNN-Network
Convolutional Neural Network, with variable width and depth.
'''
def __init__(self, in_chn, out_chn, kernel_size, width, depth, in_type):
''' Initializes the Module CNN_Net.
Args:
in_chn:
number of input channel.
out_chn:
number of output channel.
kernel_size:
convolutional kernel size.
width:
width of convolutional layer.
depth:
depth of convolutional layer.
in_type:
can become: 'rgb', 'xy' or 'rgbxy'. Decides if the network uses
the plain image data, the plain feature or both concatenated as input.
'''
super(CNN_Net, self).__init__()
self.in_chn = in_chn
self.out_chn = out_chn
self.in_type = in_type
assert (kernel_size % 2) == 1
conv_blocks = [conv_relu(width, kernel_size)
for i in range(depth)]
self.model = nn.Sequential(
nn.Conv2d(in_chn, width, kernel_size=kernel_size, padding=kernel_size//2),
nn.LeakyReLU(),
*conv_blocks,
nn.Conv2d(width, out_chn, kernel_size=kernel_size, padding=kernel_size//2)
)
def forward(self, image, grid):
''' Forward Path of the Module CNN_Net.
Args:
image:
the rgb input image.
grid:
the spacial or semantic features.
'''
patch_in = concat_input(self.in_type, image, grid)
x = self.model(patch_in)
return x
class FC_Net(nn.Module):
''' FC-Network
Fully Connected Neural Network, with variable width and depth.
'''
def __init__(self, in_chn, out_chn, width, depth, in_type):
''' Initializes the Module FC_Net.
Args:
in_chn:
number of input channel.
out_chn:
number of output channel.
width:
width of Linear layer.
depth:
depth of Linear layer.
in_type:
can become: 'rgb', 'xy' or 'rgbxy'. Decides if the network uses
the plain image data, the plain feature or both concatenated as input.
'''
super(FC_Net, self).__init__()
self.in_chn = in_chn
self.out_chn = out_chn
self.in_type = in_type
conv_blocks = [linear_relu(width) for i in range(depth)]
self.model = nn.Sequential(
nn.Linear(in_chn, width),
nn.ReLU(),
*conv_blocks,
nn.Linear(width, out_chn),
nn.ReLU()
)
def forward(self, image, grid):
patch_in = concat_input(self.in_type, image, grid)
x = self.model(patch_in)
return x
class DenseNet(nn.Module):
''' Densenet-Network'''
def __init__(self, in_chn, out_chn, in_type):
''' Initializes the Module Densenet.
Args:
in_chn:
number of input channel.
out_chn:
number of output channel.
in_type:
can become: 'rgb', 'xy' or 'rgbxy'. Decides if the network uses
the plain image data, the plain feature or both concatenated as input.
'''
super(DenseNet, self).__init__()
self.in_chn = in_chn
self.out_chn = out_chn
self.in_type = in_type
kernel_size = 7
kernel_size_small = 3
padding = kernel_size//2
self.conv0 = nn.Conv2d(in_chn, 16, kernel_size, padding=padding)
self.conv1 = nn.Conv2d(16*1 + in_chn, 16, kernel_size_small, padding=1)
self.conv2 = nn.Conv2d(16*2 + in_chn, 16, kernel_size_small, padding=1)
self.conv3 = nn.Conv2d(16*3 + in_chn, 16, kernel_size_small, padding=1)
self.conv4 = nn.Conv2d(16*4 + in_chn, out_chn, kernel_size_small, padding=1)
def forward(self, patch_image, patch_grid):
patch_in = concat_input(self.in_type, patch_image, patch_grid)
x = (patch_in)
x = torch.cat((F.relu(self.conv0(x)), x), dim=1)
x = torch.cat((F.relu(self.conv1(x)), x), dim=1)
x = torch.cat((F.relu(self.conv2(x)), x), dim=1)
x = torch.cat((F.relu(self.conv3(x)), x), dim=1)
x = self.conv4(x)
return x
class UNet(nn.Module):
''' U-Net-Network'''
def __init__(self, n_channels, n_classes, width=64, bilinear=True, in_type="rgb"):
''' Initializes the Module UNet.
Args:
n_channels:
number of input channel.
n_classes:
number of output channel.
width:
width of Downscaling and Upscaling layers.
in_type:
can become: 'rgb', 'xy' or 'rgbxy'. Decides if the network uses
the plain image data, the plain feature or both concatenated as input.
'''
super(UNet, self).__init__()
n_classes = n_classes
self.in_chn = n_channels
self.out_chn = n_classes
self.in_type = in_type
self.n_channels = n_channels
self.n_classes = n_classes
self.bilinear = bilinear
width = width
self.inc = DoubleConv(n_channels, width)
self.down1 = Down(width, width*2)
self.down2 = Down(width*2, width*4)
self.down3 = Down(width*4, width*8)
self.down4 = Down(width*8, width*8)
self.up1 = Up(width*16, width*4, bilinear)
self.up2 = Up(width*8, width*2, bilinear)
self.up3 = Up(width*4, width, bilinear)
self.up4 = Up(width*2, width, bilinear)
self.outc = OutConv(width, n_classes)
def forward(self, patch_image, patch_grid):
x = concat_input(self.in_type, patch_image, patch_grid)
x1 = self.inc(x)
x2 = self.down1(x1) # Out:128
x3 = self.down2(x2) # Out:256
x4 = self.down3(x3) # Out:512
x5 = self.down4(x4) # Out:512
x = self.up1(x5, x4) # In: 512,512 Out: 256
x = self.up2(x, x3) # In: 256,256 Out: 128
x = self.up3(x, x2) # In: 128,128 Out: 64
x = self.up4(x, x1) # In: 64,64 Out: 64
logits = self.outc(x)
return logits
class DoubleConv(nn.Module):
"""(convolution => [BN] => ReLU) * 2"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.double_conv = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
def forward(self, x):
return self.double_conv(x)
class Down(nn.Module):
"""Downscaling with maxpool then double conv"""
def __init__(self, in_channels, out_channels):
super().__init__()
self.maxpool_conv = nn.Sequential(
nn.MaxPool2d(2),
DoubleConv(in_channels, out_channels)
)
def forward(self, x):
return self.maxpool_conv(x)
class Up(nn.Module):
"""Upscaling then double conv"""
def __init__(self, in_channels, out_channels, bilinear=True):
super().__init__()
# if bilinear, use the normal convolutions to reduce the number of channels
if bilinear:
self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
else:
self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2)
self.conv = DoubleConv(in_channels, out_channels)
def forward(self, x1, x2):
x1 = self.up(x1)
diffY = torch.tensor([x2.size()[2] - x1.size()[2]])
diffX = torch.tensor([x2.size()[3] - x1.size()[3]])
x1 = F.pad(x1, [diffX // 2, diffX - diffX // 2,
diffY // 2, diffY - diffY // 2])
x = torch.cat([x2, x1], dim=1)
return self.conv(x)
class OutConv(nn.Module):
def __init__(self, in_channels, out_channels):
super(OutConv, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=1)
def forward(self, x):
return self.conv(x)