-
Notifications
You must be signed in to change notification settings - Fork 1
/
AgeMapper.py
400 lines (353 loc) · 12.7 KB
/
AgeMapper.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
from torch import prod, tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
class AgeMapper(nn.Module):
"""
AgeMapper is a 3D Convolutional Neural Network (CNN) that maps a 3D brain image to a single age value.
The network is composed of a feature extractor and a fully connected layer.
The feature extractor is composed of 5 convolutional layers with max pooling and ReLU activation.
The fully connected layer is composed of 3 fully connected layers with ReLU activation.
The network is trained using the mean squared error loss function.
"""
def __init__(self,
resolution: str = '1mm',
channel_number: list = [32,64,64,64,64],
dropout_rate_1: int = 0,
dropout_rate_2: int = 0,
dropout_rate_3: int = 0,
) -> None:
"""
Parameters:
-----------
resolution: str
The resolution of the input image. It can be either '1mm' or '2mm'.
channel_number: list
The number of channels in each convolutional layer.
dropout_rate_1: int
The dropout rate of the first fully connected layer.
dropout_rate_2: int
The dropout rate of the second fully connected layer.
dropout_rate_3: int
The dropout rate of the third fully connected layer.
Returns:
--------
None
"""
super(AgeMapper, self).__init__()
# Check if the resolution is supported
number_of_layers = len(channel_number)
if resolution=='2mm':
self.Upsample = nn.Upsample(scale_factor=2, mode='trilinear', align_corners=True)
elif resolution=='1mm':
self.Upsample = nn.Identity()
else:
print("ATTENTION! Resolution >>{}<< Not Supported!!!".format(resolution))
# Construct the network. The feature extractor is composed of 5 convolutional layers with max pooling and ReLU activation.
# The fully connected layer is composed of 3 fully connected layers with ReLU activation.
self.Feature_Extractor = nn.Sequential()
for layer_number in range(number_of_layers):
if layer_number == 0:
input_channels = 1
else:
input_channels = channel_number[layer_number - 1]
output_channels = channel_number[layer_number]
self.Feature_Extractor.add_module(
name = 'Convolution_%d' % layer_number,
module = self._convolutional_block(
input_channels,
output_channels,
maxpool_flag = True,
kernel_size = 3,
padding_flag= True
)
)
self.FullyConnected = nn.Sequential()
input_dimensions = 5 * 6 * 5 * output_channels
if dropout_rate_1 > 0:
self.FullyConnected.add_module(
name='Dropout_FullyConnected_3',
module=nn.Dropout(dropout_rate_1)
)
self.FullyConnected.add_module(
name = 'FullyConnected_3',
module=nn.Linear(
in_features=input_dimensions,
out_features=96
)
)
self.FullyConnected.add_module(
name = 'ReluActivation_3',
module= nn.ReLU()
)
if dropout_rate_2 > 0:
self.FullyConnected.add_module(
name='Dropout_FullyConnected_2',
module=nn.Dropout(dropout_rate_2)
)
self.FullyConnected.add_module(
name = 'FullyConnected_2',
module=nn.Linear(
in_features=96,
out_features=32
)
)
self.FullyConnected.add_module(
name = 'ReluActivation_2',
module= nn.ReLU()
)
if dropout_rate_3 > 0:
self.FullyConnected.add_module(
name='Dropout_FullyConnected_1',
module=nn.Dropout(dropout_rate_3)
)
self.FullyConnected.add_module(
name = 'FullyConnected_1',
module= nn.Linear(
in_features=32,
out_features=1,
)
)
self.FullyConnected.add_module(
name = 'LinearActivation',
module= nn.Identity()
)
# This is a static method. It does not require the class to be instantiated. It is used to define the convolutional blocks.
@staticmethod
def _convolutional_block(input_channels: int,
output_channels: int,
maxpool_flag: bool = True,
kernel_size: int = 3,
padding_flag: bool = True,
maxpool_stride: int = 2) -> nn.Sequential:
"""
Static method that defines a convolutional block.
Parameters:
-----------
input_channels: int
The number of input channels.
output_channels: int
The number of output channels.
maxpool_flag: bool
If True, a max pooling layer is added to the block.
kernel_size: int
The kernel size of the convolutional layer.
padding_flag: bool
If True, the convolutional layer is padded.
maxpool_stride: int
The stride of the max pooling layer.
Returns:
--------
layer: nn.Sequential
The convolutional block.
"""
if padding_flag == True:
padding = int((kernel_size - 1) / 2)
else:
padding = 0
if maxpool_flag is True:
layer = nn.Sequential(
nn.Conv3d(
in_channels=input_channels,
out_channels=output_channels,
kernel_size=kernel_size,
padding=padding,
bias=False
),
nn.BatchNorm3d(
num_features=output_channels,
affine=True
),
nn.MaxPool3d(
kernel_size=2,
stride=maxpool_stride
),
nn.ReLU()
)
else:
layer = nn.Sequential(
nn.Conv3d(
in_channels=input_channels,
out_channels=output_channels,
kernel_size=kernel_size,
padding=padding,
bias=False
),
nn.BatchNorm3d(
num_features=output_channels,
affine=True
),
nn.ReLU()
)
return layer
def forward(self,
X: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the network.
Parameters:
-----------
X: torch.Tensor
The input image.
Returns:
--------
X: torch.Tensor
The predicted age.
"""
X = self.Upsample(X)
X = self.Feature_Extractor(X)
X = X.reshape(-1, prod(tensor(X.shape)[1:]))
X = self.FullyConnected(X)
return X
class SFCN(nn.Module):
"""
SFCN is a 3D Convolutional Neural Network (CNN) that maps a 3D brain image to a single age value.
The architecture corresponds to the SFCN network proposed by Han et al. (2021).
The publication can be accessed here: Accurate brain age prediction with lightweight deep neural networks <https://www.sciencedirect.com/science/article/pii/S1361841520302358?via%3Dihub>
"""
def __init__(self,
channel_number: list = [32,64,128,256,256,64],
output_dimension: int = 40,
dropout_flag: bool = True) -> None:
"""
Parameters:
-----------
channel_number: list
The number of channels in each convolutional layer.
output_dimension: int
The number of output channels.
dropout_flag: bool
If True, a dropout layer is added to the network.
Returns:
--------
None
"""
super(SFCN, self).__init__()
number_of_layers = len(channel_number)
self.Feature_Extractor = nn.Sequential()
for layer_number in range(number_of_layers):
if layer_number == 0:
input_channels = 1
else:
input_channels = channel_number[layer_number - 1]
output_channels = channel_number[layer_number]
if layer_number < number_of_layers-1:
self.Feature_Extractor.add_module(
name = 'Convolution_%d' % layer_number,
module = self._convolutional_block(
input_channels,
output_channels,
maxpool_flag = True,
kernel_size = 3,
padding_flag= True
)
)
else:
self.Feature_Extractor.add_module(
name = 'Convolution_%d' % layer_number,
module = self._convolutional_block(
input_channels,
output_channels,
maxpool_flag = False,
kernel_size = 1,
padding_flag= False
)
)
self.Classifier = nn.Sequential()
output_shape = [5,6,5]
self.Classifier.add_module(
name = "Average_Pool",
module = nn.AvgPool3d(output_shape)
)
if dropout_flag == True:
self.Classifier.add_module('Dropout', nn.Dropout(0.5))
input_channels = channel_number[-1]
output_channels = output_dimension
layer_number = number_of_layers
self.Classifier.add_module(
name = 'Convolution_%d' % layer_number,
module = nn.Conv3d(
in_channels=input_channels,
out_channels=output_channels,
padding=0,
kernel_size=1,
bias=True
)
)
@staticmethod
def _convolutional_block(input_channels: int, output_channels: int, maxpool_flag=True, kernel_size=3, padding_flag=True, maxpool_stride=2) -> nn.Sequential:
"""
Static method that defines a convolutional block.
Parameters:
-----------
input_channels: int
The number of input channels.
output_channels: int
The number of output channels.
maxpool_flag: bool
If True, a max pooling layer is added to the block.
kernel_size: int
The kernel size of the convolutional layer.
padding_flag: bool
If True, the convolutional layer is padded.
maxpool_stride: int
The stride of the max pooling layer.
Returns:
--------
layer: nn.Sequential
The convolutional block.
"""
if padding_flag == True:
padding = int((kernel_size - 1) / 2)
else:
padding = 0
if maxpool_flag is True:
layer = nn.Sequential(
nn.Conv3d(
in_channels=input_channels,
out_channels=output_channels,
kernel_size=kernel_size,
padding=padding,
bias=False
),
nn.BatchNorm3d(
num_features=output_channels,
affine=True
),
nn.MaxPool3d(
kernel_size=2,
stride=maxpool_stride
),
nn.ReLU()
)
else:
layer = nn.Sequential(
nn.Conv3d(
in_channels=input_channels,
out_channels=output_channels,
kernel_size=kernel_size,
padding=padding,
bias=False
),
nn.BatchNorm3d(
num_features=output_channels,
affine=True
),
nn.ReLU()
)
return layer
def forward(self, X: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the network.
Parameters:
-----------
X: torch.Tensor
The input image.
Returns:
--------
X: torch.Tensor
The predicted age.
"""
X = self.Feature_Extractor(X)
X = self.Classifier(X)
X = F.log_softmax(X, dim=1)
return X