Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

model_architecture.py 16 KB

You have to be logged in to leave a comment. Sign In
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
  1. # Keras implementation of the paper:
  2. # 3D MRI Brain Tumor Segmentation Using Autoencoder Regularization
  3. # by Myronenko A. (https://arxiv.org/pdf/1810.11654.pdf)
  4. # Author of this code: Suyog Jadhav (https://github.com/IAmSUyogJadhav)
  5. import keras.backend as K
  6. from keras.losses import mse
  7. from keras.layers import Conv3D, Activation, Add, UpSampling3D, Lambda, Dense
  8. from keras.layers import Input, Reshape, Flatten, Dropout, SpatialDropout3D
  9. from keras.optimizers import Adam as adam
  10. from keras.models import Model
  11. try:
  12. from group_norm import GroupNormalization
  13. except ImportError:
  14. import urllib.request
  15. print('Downloading group_norm.py in the current directory...')
  16. url = 'https://raw.githubusercontent.com/titu1994/Keras-Group-Normalization/master/group_norm.py'
  17. urllib.request.urlretrieve(url, "group_norm.py")
  18. from group_norm import GroupNormalization
  19. def green_block(inp, filters, data_format='channels_first', name=None):
  20. """
  21. green_block(inp, filters, name=None)
  22. ------------------------------------
  23. Implementation of the special residual block used in the paper. The block
  24. consists of two (GroupNorm --> ReLu --> 3x3x3 non-strided Convolution)
  25. units, with a residual connection from the input `inp` to the output. Used
  26. internally in the model. Can be used independently as well.
  27. Parameters
  28. ----------
  29. `inp`: An keras.layers.layer instance, required
  30. The keras layer just preceding the green block.
  31. `filters`: integer, required
  32. No. of filters to use in the 3D convolutional block. The output
  33. layer of this green block will have this many no. of channels.
  34. `data_format`: string, optional
  35. The format of the input data. Must be either 'chanels_first' or
  36. 'channels_last'. Defaults to `channels_first`, as used in the paper.
  37. `name`: string, optional
  38. The name to be given to this green block. Defaults to None, in which
  39. case, keras uses generated names for the involved layers. If a string
  40. is provided, the names of individual layers are generated by attaching
  41. a relevant prefix from [GroupNorm_, Res_, Conv3D_, Relu_, ], followed
  42. by _1 or _2.
  43. Returns
  44. -------
  45. `out`: A keras.layers.Layer instance
  46. The output of the green block. Has no. of channels equal to `filters`.
  47. The size of the rest of the dimensions remains same as in `inp`.
  48. """
  49. inp_res = Conv3D(
  50. filters=filters,
  51. kernel_size=(1, 1, 1),
  52. strides=1,
  53. data_format=data_format,
  54. name=f'Res_{name}' if name else None)(inp)
  55. # axis=1 for channels_first data format
  56. # No. of groups = 8, as given in the paper
  57. x = GroupNormalization(
  58. groups=8,
  59. axis=1 if data_format == 'channels_first' else 0,
  60. name=f'GroupNorm_1_{name}' if name else None)(inp)
  61. x = Activation('relu', name=f'Relu_1_{name}' if name else None)(x)
  62. x = Conv3D(
  63. filters=filters,
  64. kernel_size=(3, 3, 3),
  65. strides=1,
  66. padding='same',
  67. data_format=data_format,
  68. name=f'Conv3D_1_{name}' if name else None)(x)
  69. x = GroupNormalization(
  70. groups=8,
  71. axis=1 if data_format == 'channels_first' else 0,
  72. name=f'GroupNorm_2_{name}' if name else None)(x)
  73. x = Activation('relu', name=f'Relu_2_{name}' if name else None)(x)
  74. x = Conv3D(
  75. filters=filters,
  76. kernel_size=(3, 3, 3),
  77. strides=1,
  78. padding='same',
  79. data_format=data_format,
  80. name=f'Conv3D_2_{name}' if name else None)(x)
  81. out = Add(name=f'Out_{name}' if name else None)([x, inp_res])
  82. return out
  83. # From keras-team/keras/blob/master/examples/variational_autoencoder.py
  84. def sampling(args):
  85. """Reparameterization trick by sampling from an isotropic unit Gaussian.
  86. # Arguments
  87. args (tensor): mean and log of variance of Q(z|X)
  88. # Returns
  89. z (tensor): sampled latent vector
  90. """
  91. z_mean, z_var = args
  92. batch = K.shape(z_mean)[0]
  93. dim = K.int_shape(z_mean)[1]
  94. # by default, random_normal has mean = 0 and std = 1.0
  95. epsilon = K.random_normal(shape=(batch, dim))
  96. return z_mean + K.exp(0.5 * z_var) * epsilon
  97. def dice_coefficient(y_true, y_pred):
  98. intersection = K.sum(K.abs(y_true * y_pred), axis=[-3,-2,-1])
  99. dn = K.sum(K.square(y_true) + K.square(y_pred), axis=[-3,-2,-1]) + 1e-8
  100. return K.mean(2 * intersection / dn, axis=[0,1])
  101. def loss_gt(e=1e-8):
  102. """
  103. loss_gt(e=1e-8)
  104. ------------------------------------------------------
  105. Since keras does not allow custom loss functions to have arguments
  106. other than the true and predicted labels, this function acts as a wrapper
  107. that allows us to implement the custom loss used in the paper. This function
  108. only calculates - L<dice> term of the following equation. (i.e. GT Decoder part loss)
  109. L = - L<dice> + weight_L2 ∗ L<L2> + weight_KL ∗ L<KL>
  110. Parameters
  111. ----------
  112. `e`: Float, optional
  113. A small epsilon term to add in the denominator to avoid dividing by
  114. zero and possible gradient explosion.
  115. Returns
  116. -------
  117. loss_gt_(y_true, y_pred): A custom keras loss function
  118. This function takes as input the predicted and ground labels, uses them
  119. to calculate the dice loss.
  120. """
  121. def loss_gt_(y_true, y_pred):
  122. intersection = K.sum(K.abs(y_true * y_pred), axis=[-3,-2,-1])
  123. dn = K.sum(K.square(y_true) + K.square(y_pred), axis=[-3,-2,-1]) + e
  124. return 1 - K.mean(2 * intersection / dn, axis=[0,1])
  125. return loss_gt_
  126. def loss_VAE(input_shape, z_mean, z_var, weight_L2=0.1, weight_KL=0.1):
  127. """
  128. loss_VAE(input_shape, z_mean, z_var, weight_L2=0.1, weight_KL=0.1)
  129. ------------------------------------------------------
  130. Since keras does not allow custom loss functions to have arguments
  131. other than the true and predicted labels, this function acts as a wrapper
  132. that allows us to implement the custom loss used in the paper. This function
  133. calculates the following equation, except for -L<dice> term. (i.e. VAE decoder part loss)
  134. L = - L<dice> + weight_L2 ∗ L<L2> + weight_KL ∗ L<KL>
  135. Parameters
  136. ----------
  137. `input_shape`: A 4-tuple, required
  138. The shape of an image as the tuple (c, H, W, D), where c is
  139. the no. of channels; H, W and D is the height, width and depth of the
  140. input image, respectively.
  141. `z_mean`: An keras.layers.Layer instance, required
  142. The vector representing values of mean for the learned distribution
  143. in the VAE part. Used internally.
  144. `z_var`: An keras.layers.Layer instance, required
  145. The vector representing values of variance for the learned distribution
  146. in the VAE part. Used internally.
  147. `weight_L2`: A real number, optional
  148. The weight to be given to the L2 loss term in the loss function. Adjust to get best
  149. results for your task. Defaults to 0.1.
  150. `weight_KL`: A real number, optional
  151. The weight to be given to the KL loss term in the loss function. Adjust to get best
  152. results for your task. Defaults to 0.1.
  153. Returns
  154. -------
  155. loss_VAE_(y_true, y_pred): A custom keras loss function
  156. This function takes as input the predicted and ground labels, uses them
  157. to calculate the L2 and KL loss.
  158. """
  159. def loss_VAE_(y_true, y_pred):
  160. c, H, W, D = input_shape
  161. n = c * H * W * D
  162. loss_L2 = K.mean(K.square(y_true - y_pred), axis=(1, 2, 3, 4)) # original axis value is (1,2,3,4).
  163. loss_KL = (1 / n) * K.sum(
  164. K.exp(z_var) + K.square(z_mean) - 1. - z_var,
  165. axis=-1
  166. )
  167. return weight_L2 * loss_L2 + weight_KL * loss_KL
  168. return loss_VAE_
  169. def build_model(input_shape=(4, 160, 192, 128), output_channels=3, weight_L2=0.1, weight_KL=0.1, dice_e=1e-8):
  170. """
  171. build_model(input_shape=(4, 160, 192, 128), output_channels=3, weight_L2=0.1, weight_KL=0.1)
  172. -------------------------------------------
  173. Creates the model used in the BRATS2018 winning solution
  174. by Myronenko A. (https://arxiv.org/pdf/1810.11654.pdf)
  175. Parameters
  176. ----------
  177. `input_shape`: A 4-tuple, optional.
  178. Shape of the input image. Must be a 4D image of shape (c, H, W, D),
  179. where, each of H, W and D are divisible by 2^4, and c is divisible by 4.
  180. Defaults to the crop size used in the paper, i.e., (4, 160, 192, 128).
  181. `output_channels`: An integer, optional.
  182. The no. of channels in the output. Defaults to 3 (BraTS 2018 format).
  183. `weight_L2`: A real number, optional
  184. The weight to be given to the L2 loss term in the loss function. Adjust to get best
  185. results for your task. Defaults to 0.1.
  186. `weight_KL`: A real number, optional
  187. The weight to be given to the KL loss term in the loss function. Adjust to get best
  188. results for your task. Defaults to 0.1.
  189. `dice_e`: Float, optional
  190. A small epsilon term to add in the denominator of dice loss to avoid dividing by
  191. zero and possible gradient explosion. This argument will be passed to loss_gt function.
  192. Returns
  193. -------
  194. `model`: A keras.models.Model instance
  195. The created model.
  196. """
  197. c, H, W, D = input_shape
  198. assert len(input_shape) == 4, "Input shape must be a 4-tuple"
  199. assert (c % 4) == 0, "The no. of channels must be divisible by 4"
  200. assert (H % 16) == 0 and (W % 16) == 0 and (D % 16) == 0, \
  201. "All the input dimensions must be divisible by 16"
  202. # -------------------------------------------------------------------------
  203. # Encoder
  204. # -------------------------------------------------------------------------
  205. ## Input Layer
  206. inp = Input(input_shape)
  207. ## The Initial Block
  208. x = Conv3D(
  209. filters=32,
  210. kernel_size=(3, 3, 3),
  211. strides=1,
  212. padding='same',
  213. data_format='channels_first',
  214. name='Input_x1')(inp)
  215. ## Dropout (0.2)
  216. x = SpatialDropout3D(0.2, data_format='channels_first')(x)
  217. ## Green Block x1 (output filters = 32)
  218. x1 = green_block(x, 32, name='x1')
  219. x = Conv3D(
  220. filters=32,
  221. kernel_size=(3, 3, 3),
  222. strides=2,
  223. padding='same',
  224. data_format='channels_first',
  225. name='Enc_DownSample_32')(x1)
  226. ## Green Block x2 (output filters = 64)
  227. x = green_block(x, 64, name='Enc_64_1')
  228. x2 = green_block(x, 64, name='x2')
  229. x = Conv3D(
  230. filters=64,
  231. kernel_size=(3, 3, 3),
  232. strides=2,
  233. padding='same',
  234. data_format='channels_first',
  235. name='Enc_DownSample_64')(x2)
  236. ## Green Blocks x2 (output filters = 128)
  237. x = green_block(x, 128, name='Enc_128_1')
  238. x3 = green_block(x, 128, name='x3')
  239. x = Conv3D(
  240. filters=128,
  241. kernel_size=(3, 3, 3),
  242. strides=2,
  243. padding='same',
  244. data_format='channels_first',
  245. name='Enc_DownSample_128')(x3)
  246. ## Green Blocks x4 (output filters = 256)
  247. x = green_block(x, 256, name='Enc_256_1')
  248. x = green_block(x, 256, name='Enc_256_2')
  249. x = green_block(x, 256, name='Enc_256_3')
  250. x4 = green_block(x, 256, name='x4')
  251. # -------------------------------------------------------------------------
  252. # Decoder
  253. # -------------------------------------------------------------------------
  254. ## GT (Groud Truth) Part
  255. # -------------------------------------------------------------------------
  256. ### Green Block x1 (output filters=128)
  257. x = Conv3D(
  258. filters=128,
  259. kernel_size=(1, 1, 1),
  260. strides=1,
  261. data_format='channels_first',
  262. name='Dec_GT_ReduceDepth_128')(x4)
  263. x = UpSampling3D(
  264. size=2,
  265. data_format='channels_first',
  266. name='Dec_GT_UpSample_128')(x)
  267. x = Add(name='Input_Dec_GT_128')([x, x3])
  268. x = green_block(x, 128, name='Dec_GT_128')
  269. ### Green Block x1 (output filters=64)
  270. x = Conv3D(
  271. filters=64,
  272. kernel_size=(1, 1, 1),
  273. strides=1,
  274. data_format='channels_first',
  275. name='Dec_GT_ReduceDepth_64')(x)
  276. x = UpSampling3D(
  277. size=2,
  278. data_format='channels_first',
  279. name='Dec_GT_UpSample_64')(x)
  280. x = Add(name='Input_Dec_GT_64')([x, x2])
  281. x = green_block(x, 64, name='Dec_GT_64')
  282. ### Green Block x1 (output filters=32)
  283. x = Conv3D(
  284. filters=32,
  285. kernel_size=(1, 1, 1),
  286. strides=1,
  287. data_format='channels_first',
  288. name='Dec_GT_ReduceDepth_32')(x)
  289. x = UpSampling3D(
  290. size=2,
  291. data_format='channels_first',
  292. name='Dec_GT_UpSample_32')(x)
  293. x = Add(name='Input_Dec_GT_32')([x, x1])
  294. x = green_block(x, 32, name='Dec_GT_32')
  295. ### Blue Block x1 (output filters=32)
  296. x = Conv3D(
  297. filters=32,
  298. kernel_size=(3, 3, 3),
  299. strides=1,
  300. padding='same',
  301. data_format='channels_first',
  302. name='Input_Dec_GT_Output')(x)
  303. ### Output Block
  304. out_GT = Conv3D(
  305. filters=output_channels, # No. of tumor classes is 3
  306. kernel_size=(1, 1, 1),
  307. strides=1,
  308. data_format='channels_first',
  309. activation='sigmoid',
  310. name='Dec_GT_Output')(x)
  311. ## VAE (Variational Auto Encoder) Part
  312. # -------------------------------------------------------------------------
  313. ### VD Block (Reducing dimensionality of the data)
  314. x = GroupNormalization(groups=8, axis=1, name='Dec_VAE_VD_GN')(x4)
  315. x = Activation('relu', name='Dec_VAE_VD_relu')(x)
  316. x = Conv3D(
  317. filters=16,
  318. kernel_size=(3, 3, 3),
  319. strides=2,
  320. padding='same',
  321. data_format='channels_first',
  322. name='Dec_VAE_VD_Conv3D')(x)
  323. # Not mentioned in the paper, but the author used a Flattening layer here.
  324. x = Flatten(name='Dec_VAE_VD_Flatten')(x)
  325. x = Dense(256, name='Dec_VAE_VD_Dense')(x)
  326. ### VDraw Block (Sampling)
  327. z_mean = Dense(128, name='Dec_VAE_VDraw_Mean')(x)
  328. z_var = Dense(128, name='Dec_VAE_VDraw_Var')(x)
  329. x = Lambda(sampling, name='Dec_VAE_VDraw_Sampling')([z_mean, z_var])
  330. ### VU Block (Upsizing back to a depth of 256)
  331. x = Dense((c//4) * (H//16) * (W//16) * (D//16))(x)
  332. x = Activation('relu')(x)
  333. x = Reshape(((c//4), (H//16), (W//16), (D//16)))(x)
  334. x = Conv3D(
  335. filters=256,
  336. kernel_size=(1, 1, 1),
  337. strides=1,
  338. data_format='channels_first',
  339. name='Dec_VAE_ReduceDepth_256')(x)
  340. x = UpSampling3D(
  341. size=2,
  342. data_format='channels_first',
  343. name='Dec_VAE_UpSample_256')(x)
  344. ### Green Block x1 (output filters=128)
  345. x = Conv3D(
  346. filters=128,
  347. kernel_size=(1, 1, 1),
  348. strides=1,
  349. data_format='channels_first',
  350. name='Dec_VAE_ReduceDepth_128')(x)
  351. x = UpSampling3D(
  352. size=2,
  353. data_format='channels_first',
  354. name='Dec_VAE_UpSample_128')(x)
  355. x = green_block(x, 128, name='Dec_VAE_128')
  356. ### Green Block x1 (output filters=64)
  357. x = Conv3D(
  358. filters=64,
  359. kernel_size=(1, 1, 1),
  360. strides=1,
  361. data_format='channels_first',
  362. name='Dec_VAE_ReduceDepth_64')(x)
  363. x = UpSampling3D(
  364. size=2,
  365. data_format='channels_first',
  366. name='Dec_VAE_UpSample_64')(x)
  367. x = green_block(x, 64, name='Dec_VAE_64')
  368. ### Green Block x1 (output filters=32)
  369. x = Conv3D(
  370. filters=32,
  371. kernel_size=(1, 1, 1),
  372. strides=1,
  373. data_format='channels_first',
  374. name='Dec_VAE_ReduceDepth_32')(x)
  375. x = UpSampling3D(
  376. size=2,
  377. data_format='channels_first',
  378. name='Dec_VAE_UpSample_32')(x)
  379. x = green_block(x, 32, name='Dec_VAE_32')
  380. ### Blue Block x1 (output filters=32)
  381. x = Conv3D(
  382. filters=32,
  383. kernel_size=(3, 3, 3),
  384. strides=1,
  385. padding='same',
  386. data_format='channels_first',
  387. name='Input_Dec_VAE_Output')(x)
  388. ### Output Block
  389. out_VAE = Conv3D(
  390. filters=4,
  391. kernel_size=(1, 1, 1),
  392. strides=1,
  393. data_format='channels_first',
  394. name='Dec_VAE_Output')(x)
  395. # Build and Compile the model
  396. out = out_GT
  397. model = Model(inp, outputs=[out, out_VAE]) # Create the model
  398. model.compile(
  399. adam(lr=1e-4),
  400. [loss_gt(dice_e), loss_VAE(input_shape, z_mean, z_var, weight_L2=weight_L2, weight_KL=weight_KL)],
  401. metrics=[dice_coefficient]
  402. )
  403. return model
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...