-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_models.py
432 lines (343 loc) · 15.5 KB
/
custom_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
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
# -*- coding: utf-8 -*-
"""models.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1J8jxm1tS8yZLF_jy4v8MFuZ5XS6k7xS3
"""
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, CSVLogger, TensorBoard
from tensorflow.keras.optimizers import Adam
from dataclasses import dataclass
from runner import *
from trainer import *
from initial_parser import *
from splitter import *
from data_provider import *
from custom_metrics import *
from custom_losses import *
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
from iterstrat.ml_stratifiers import MultilabelStratifiedShuffleSplit
import os
import random
from tensorflow.keras.layers.experimental import preprocessing
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import albumentations as A
import numpy as np
from keras.models import Model
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from keras.layers import BatchNormalization
from keras.layers import Add
from keras.layers.core import SpatialDropout2D, Activation
from tensorflow.keras.applications import EfficientNetB0
from keras import backend as K
from keras.layers.merge import concatenate
from keras.utils.data_utils import get_file
from tensorflow import keras
import segmentation_models as sm
import cv2
import datetime
from segmentation_models.losses import bce_jaccard_loss
class efficientnet_bb_unet():
def __init__(self, output_mask_channels):
self.output_mask_channels = output_mask_channels
def build_model(self):
sm.set_framework('tf.keras')
sm.framework()
keras.backend.set_image_data_format('channels_last')
model = sm.Unet('efficientnetb0', classes=self.output_mask_channels, activation='sigmoid')
return model
class seresnext50_bb_unet():
def __init__(self, output_mask_channels):
self.output_mask_channels = output_mask_channels
def build_model(self):
sm.set_framework('tf.keras')
sm.framework()
keras.backend.set_image_data_format('channels_last')
model = sm.Unet('seresnext50', classes=self.output_mask_channels, activation='sigmoid', encoder_weights='imagenet')
return model
class vgg16_bb_unet():
def __init__(self, output_mask_channels):
self.output_mask_channels = output_mask_channels
def build_model(self):
sm.set_framework('tf.keras')
sm.framework()
keras.backend.set_image_data_format('channels_last')
model = sm.Unet('vgg16', classes=self.output_mask_channels, activation='sigmoid', encoder_weights='imagenet')
return model
class fpn_bb_unet():
def __init__(self, output_mask_channels):
self.output_mask_channels = output_mask_channels
def build_model(self):
sm.set_framework('tf.keras')
sm.framework()
keras.backend.set_image_data_format('channels_last')
model = sm.FPN('densenet121', classes=self.output_mask_channels, activation='sigmoid', encoder_weights='imagenet')
return model
class ZF_UNET_224():
def __init__(self, input_channels, output_mask_channels):
self.input_channels = input_channels
self.output_mask_channels = output_mask_channels
def double_conv_layer(self, x, size, dropout=0.0, batch_norm=True):
axis = 3
conv = Conv2D(size, (3, 3), padding='same')(x)
if batch_norm is True:
conv = BatchNormalization(axis=axis)(conv)
conv = Activation('relu')(conv)
conv = Conv2D(size, (3, 3), padding='same')(conv)
if batch_norm is True:
conv = BatchNormalization(axis=axis)(conv)
conv = Activation('relu')(conv)
if dropout > 0:
conv = SpatialDropout2D(dropout)(conv)
return conv
def build_model(self, dropout_val=0.2, weights=None):
inputs = Input((224, 224, self.input_channels))
axis = 3
filters = 32
conv_224 = self.double_conv_layer(inputs, filters)
pool_112 = MaxPooling2D(pool_size=(2, 2))(conv_224)
conv_112 = self.double_conv_layer(pool_112, 2*filters)
pool_56 = MaxPooling2D(pool_size=(2, 2))(conv_112)
conv_56 = self.double_conv_layer(pool_56, 4*filters)
pool_28 = MaxPooling2D(pool_size=(2, 2))(conv_56)
conv_28 = self.double_conv_layer(pool_28, 8*filters)
pool_14 = MaxPooling2D(pool_size=(2, 2))(conv_28)
conv_14 = self.double_conv_layer(pool_14, 16*filters)
pool_7 = MaxPooling2D(pool_size=(2, 2))(conv_14)
conv_7 = self.double_conv_layer(pool_7, 32*filters)
up_14 = concatenate([UpSampling2D(size=(2, 2))(conv_7), conv_14], axis=axis)
up_conv_14 = self.double_conv_layer(up_14, 16*filters)
up_28 = concatenate([UpSampling2D(size=(2, 2))(up_conv_14), conv_28], axis=axis)
up_conv_28 = self.double_conv_layer(up_28, 8*filters)
up_56 = concatenate([UpSampling2D(size=(2, 2))(up_conv_28), conv_56], axis=axis)
up_conv_56 = self.double_conv_layer(up_56, 4*filters)
up_112 = concatenate([UpSampling2D(size=(2, 2))(up_conv_56), conv_112], axis=axis)
up_conv_112 = self.double_conv_layer(up_112, 2*filters)
up_224 = concatenate([UpSampling2D(size=(2, 2))(up_conv_112), conv_224], axis=axis)
up_conv_224 = self.double_conv_layer(up_224, filters, dropout_val)
conv_final = Conv2D(self.output_mask_channels, (1, 1))(up_conv_224)
conv_final = Activation('sigmoid')(conv_final)
model = Model(inputs, conv_final, name="ZF_UNET_224")
if weights == 'generator' and axis == 3 and self.input_channels == 3 and self.output_mask_channels == 1:
weights_path = get_file(
'zf_unet_224_weights_tf_dim_ordering_tf_generator.h5',
ZF_UNET_224_WEIGHT_PATH,
cache_subdir='models',
file_hash='203146f209baf34ac0d793e1691f1ab7')
model.load_weights(weights_path)
return model
import numpy as np
import os
import tensorflow as tf
from tensorflow.keras.applications import EfficientNetB0
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras.applications.vgg16 import VGG16
"""
A Keras implementation of TernausNet16:
https://arxiv.org/abs/1801.05746
https://github.com/ternaus/TernausNet
The architecture is very similar to the original U-net paper:
https://arxiv.org/abs/1505.04597
The key differences are:
- A VGG16 architecture is used for encoder, pretrained on ImageNet
- No batchnorm used
- No dropout used
- Shortcut concatenations are mismatched on number of filters meaning that
a larger number of filters is used in decoder.
"""
class ternaus_net():
def decoder_block_ternausV2(self, inputs, mid_channels, out_channels):
"""
Decoder block as proposed for TernausNet16 here:
https://arxiv.org/abs/1801.05746
See DecoderBlockV2 here:
https://github.com/ternaus/TernausNet/blob/master/unet_models.py
- Concatenate u-net shortcut to input pre-upsample
- Bilinear upsample input to double Height and Width dimensions
- Note: The original ternausNet implementation includes option for
deconvolution instead of bilinear upsampling. Omitted here because I
couldn't find a meaningful performance comparison
"""
conv_kwargs = dict(
activation='relu',
padding='same',
kernel_initializer='he_normal',
data_format='channels_last' # (batch, height, width, channels)
)
x = UpSampling2D(size=(2, 2))(inputs) # interpolation='bilinear' doesn't work?
x = Conv2D(mid_channels, 3, **conv_kwargs)(x)
x = Conv2D(out_channels, 3, **conv_kwargs)(x)
return x
def build_model(self, input_size=(256, 256, 3), output_channels=1):
"""
A Keras implementation of TernausNet16:
https://arxiv.org/abs/1801.05746
https://github.com/ternaus/TernausNet
"""
# input
# convert 1 channel grayscale to 3 channels if needed
inputs = Input(input_size)
if input_size[-1] < 3:
x = Conv2D(3, 1)(inputs) # add channels
input_shape = (input_size[0], input_size[0], 3) # update input size
else:
x = inputs
input_shape = input_size
# Load pretrained VGG, conv layers include relu activation
encoder = VGG16(include_top=False, weights='imagenet', input_shape=input_shape)
# (None, 256, 256, 3)
e1 = encoder.get_layer(name='block1_conv1')(x)
e1 = encoder.get_layer(name='block1_conv2')(e1)
# (None, 256, 256, 64)
e2 = MaxPooling2D(pool_size=(2, 2))(e1)
e2 = encoder.get_layer(name='block2_conv1')(e2)
e2 = encoder.get_layer(name='block2_conv2')(e2)
# (None, 128, 128, 128)
e3 = MaxPooling2D(pool_size=(2, 2))(e2)
e3 = encoder.get_layer(name='block3_conv1')(e3)
e3 = encoder.get_layer(name='block3_conv2')(e3)
e3 = encoder.get_layer(name='block3_conv3')(e3)
# (None, 64, 64, 256)
e4 = MaxPooling2D(pool_size=(2, 2))(e3)
e4 = encoder.get_layer(name='block4_conv1')(e4)
e4 = encoder.get_layer(name='block4_conv2')(e4)
e4 = encoder.get_layer(name='block4_conv3')(e4)
# (None, 32, 32, 512)
e5 = MaxPooling2D(pool_size=(2, 2))(e4)
e5 = encoder.get_layer(name='block5_conv1')(e5)
e5 = encoder.get_layer(name='block5_conv2')(e5)
e5 = encoder.get_layer(name='block5_conv3')(e5)
# (None, 16, 16, 512)
center = MaxPooling2D(pool_size=(2, 2))(e5)
# (None, 8, 8, 512)
center = self.decoder_block_ternausV2(center, 512, 256)
# (None, 16, 16, 256)
d5 = concatenate([e5, center], axis=3)
d5 = self.decoder_block_ternausV2(d5, 512, 256)
# (None, 32, 32, 256)
d4 = concatenate([e4, d5], axis=3)
d4 = self.decoder_block_ternausV2(d4, 512, 128)
# (None, 64, 64, 128)
d3 = concatenate([e3, d4], axis=3)
d3 = self.decoder_block_ternausV2(d3, 256, 64)
# (None, 128, 128, 64)
d2 = concatenate([e2, d3], axis=3)
d2 = self.decoder_block_ternausV2(d2, 128, 64)
# (None, 256, 256, 64)
# Note: no decoder block used at end
d1 = concatenate([e1, d2], axis=3)
d1 = Conv2D(32, 3, padding='same', kernel_initializer='he_normal')(d1)
d1 = ReLU()(d1)
# (None, 256, 256, 32)
# Output
if output_channels > 1:
# untested
op = tf.nn.log_softmax_v2(d1, axis=3)
else:
op = Conv2D(output_channels, 1)(d1)
op = Activation('sigmoid')(op) # note: ternaus excludes
# Build
model = Model(inputs=[inputs], outputs=[op])
print(model.summary())
return model
class simple_unet():
def build_model(self):
inputs = Input((224, 224, 3))
c1 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (inputs)
c1 = BatchNormalization()(c1)
c1 = Dropout(0.1) (c1)
c1 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c1)
c1 = BatchNormalization()(c1)
p1 = MaxPooling2D((2, 2)) (c1)
c2 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p1)
c2 = BatchNormalization()(c2)
c2 = Dropout(0.1) (c2)
c2 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c2)
c2 = BatchNormalization()(c2)
p2 = MaxPooling2D((2, 2)) (c2)
c3 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p2)
c3 = BatchNormalization()(c3)
c3 = Dropout(0.2) (c3)
c3 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c3)
c3 = BatchNormalization()(c3)
p3 = MaxPooling2D((2, 2)) (c3)
c4 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p3)
c4 = BatchNormalization()(c4)
c4 = Dropout(0.2) (c4)
c4 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c4)
c4 = BatchNormalization()(c4)
p4 = MaxPooling2D(pool_size=(2, 2)) (c4)
c5 = Conv2D(512, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p4)
c5 = BatchNormalization()(c5)
c5 = Dropout(0.3) (c5)
c5 = Conv2D(512, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c5)
c5 = BatchNormalization()(c5)
u6 = Conv2DTranspose(128, (2, 2), strides=(2, 2), padding='same') (c5)
u6 = concatenate([u6, c4])
c6 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u6)
c6 = BatchNormalization()(c6)
c6 = Dropout(0.2) (c6)
c6 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c6)
c6 = BatchNormalization()(c6)
u7 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c6)
u7 = concatenate([u7, c3])
c7 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u7)
c7 = BatchNormalization()(c7)
c7 = Dropout(0.2) (c7)
c7 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c7)
c7 = BatchNormalization()(c7)
u8 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (c7)
u8 = concatenate([u8, c2])
c8 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u8)
c8 = BatchNormalization()(c8)
c8 = Dropout(0.1) (c8)
c8 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c8)
c8 = BatchNormalization()(c8)
u9 = Conv2DTranspose(16, (2, 2), strides=(2, 2), padding='same') (c8)
u9 = concatenate([u9, c1], axis=3)
c9 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (u9)
c9 = BatchNormalization()(c9)
c9 = Dropout(0.1) (c9)
c9 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c9)
c9 = BatchNormalization()(c9)
outputs = Conv2D(1, (1, 1), activation='sigmoid') (c9)
model = Model(inputs, outputs)
return model
class custom_fpn():
def build_model(self):
inputs = Input((224, 224, 3))
c1 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (inputs)
c1 = BatchNormalization()(c1)
p1 = MaxPooling2D((2, 2)) (c1)
c2 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p1)
c2 = BatchNormalization()(c2)
p2 = MaxPooling2D((2, 2)) (c2)
c3 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (p2)
c3 = BatchNormalization()(c3)
u6 = Conv2DTranspose(64, (2, 2), strides=(2, 2), padding='same') (c3)
added6 = Add()([u6, c2])
u6 = BatchNormalization()(added6)
u7 = Conv2DTranspose(32, (2, 2), strides=(2, 2), padding='same') (u6)
u7 = BatchNormalization()(u7)
outputs = Conv2D(1, (1, 1), activation='sigmoid') (u7)
model = Model(inputs, outputs)
print(model.summary())
return model
class custom_cnn():
def build_model(self):
inputs = Input((224, 224, 3))
c1 = Conv2D(32, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (inputs)
c1 = BatchNormalization()(c1)
c2 = Conv2D(64, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c1)
c2 = BatchNormalization()(c2)
c3 = Conv2D(128, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c2)
c3 = BatchNormalization()(c3)
c4 = Conv2D(256, (3, 3), activation='elu', kernel_initializer='he_normal', padding='same') (c3)
c4 = BatchNormalization()(c4)
outputs = Conv2D(1, (1, 1), activation='sigmoid') (c4)
model = Model(inputs, outputs)
return model