-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunet.py
191 lines (154 loc) · 9.43 KB
/
unet.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
# https://github.com/zhixuhao/unet
# os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from keras.callbacks import *
from keras.layers import *
from keras.models import Model
from keras.optimizers import *
from keras import backend as K
import config as configuration
import metrics
from keras_slice_generator import SliceGenerator
from read_data import BRATSReader
import keras.metrics
from predict_callback import PredictCallback
import keras.losses as losses
from tkinter import *
import augmentation
import eval
from keras.utils.vis_utils import plot_model
class Unet(object):
def __init__(self, config, weight_file='unet.hdf5'):
self.config = config
self.img_rows = 224
self.img_cols = 224
self.model = self.__get_unet()
self.weights_file = weight_file
if os.path.isfile(self.weights_file):
print('Loading weights from ', self.weights_file)
self.model.load_weights(self.weights_file)
def __inception_pool(self, input, filters, block_num, drop_prob=.3, activation='relu', padding='same', init='he_uniform'):
block_num = str(block_num)
prefix = 'conv' + block_num + '_'
reg = tf.keras.regularizers.l2(1e-5)
filters = input._keras_shape[-1]
ones = Conv2D(filters//2, 1, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '1x1_1')(input)
threes = Conv2D(filters//4, 1, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '1x1_3')(input)
threes = Conv2D(filters // 2 + filters // 4, 3, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '3x3_3')(threes)
fives = Conv2D(filters//4, 1, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '1x1_5')(input)
fives = Conv2D(filters // 4 + filters // 8, 5, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '3x3_5p1')(fives)
pool = MaxPool2D(pool_size=(3, 3), strides=1, padding=padding, name=block_num + 'pool3x3')(input)
pool = Conv2D(filters//4, 1, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '1x1')(pool)
bottle_neck = concatenate([ones, threes, fives, pool], axis=3, name=block_num + '_bottleneck')
pooled = MaxPooling2D(pool_size=(2, 2), name='pool' + block_num)(bottle_neck)
if drop_prob is not None:
pooled = Dropout(drop_prob, name='dropdown' + block_num)(pooled)
return bottle_neck, pooled
def __pool_layer(self, input, filters, block_num, drop_prob=.3, activation='linear', padding='same',
init='he_uniform'):
block_num = str(block_num)
prefix = 'conv' + block_num + '_'
reg = tf.keras.regularizers.l2(.0)
conv1 = Conv2D(filters, 3, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '1')(input)
conv1 = LeakyReLU()(conv1)
conv1 = BatchNormalization()(conv1)
conv1 = Conv2D(filters, 3, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '2')(conv1)
conv1 = LeakyReLU()(conv1)
conv1 = BatchNormalization()(conv1)
# TODO: Try AveragePooling, or strided convolutions
pool1 = MaxPooling2D(pool_size=(2, 2), name='pool' + block_num)(conv1)
if drop_prob is not None:
pool1 = Dropout(drop_prob, name='dropdown' + block_num)(pool1)
return conv1, pool1
def __unpool_block(self, pooled, prepooled, block_num, drop_prob=.2, activation='linear', padding='same',
init='he_uniform'):
filters = prepooled._keras_shape[-1]
block_num = str(block_num)
prefix = 'upconv' + block_num + '_'
reg = tf.keras.regularizers.l2(.0)
# conv1 = Deconv2D(filters=filters, kernel_size=(3, 3), strides=2, padding=padding, activation=activation, kernel_initializer=init, kernel_regularizer=reg, name=prefix + '1')(pooled)
# up1 = UpSampling2D(size=(2, 2), name='upsample' + block_num)(pooled)
# conv1 = Conv2D(filters=filters, kernel_size=2, activation=activation, padding=padding, kernel_initializer=init,
# kernel_regularizer=reg, name=prefix + '1')(up1)
conv1 = Conv2DTranspose(filters, kernel_size=(4, 4), strides=2, padding=padding, activation=activation,
kernel_initializer=init, kernel_regularizer=reg, name=prefix + '1')(pooled)
conv1 = LeakyReLU()(conv1)
conv1 = BatchNormalization()(conv1)
merged = concatenate([prepooled, conv1], axis=3, name='merge' + block_num)
conv1 = Conv2D(filters=filters, kernel_size=2, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '2')(merged)
conv1 = LeakyReLU()(conv1)
conv1 = BatchNormalization()(conv1)
conv1 = Conv2D(filters=filters, kernel_size=2, activation=activation, padding=padding, kernel_initializer=init,
kernel_regularizer=reg, name=prefix + '3')(conv1)
conv1 = LeakyReLU()(conv1)
conv1 = BatchNormalization()(conv1)
if drop_prob is not None:
conv1 = Dropout(drop_prob, name='dropup' + block_num)(conv1)
return conv1
def __get_unet(self):
inputs = Input((self.img_rows, self.img_cols, 4)) # (b, 224, 224, 1)
filters = 16 # 64
stem = inputs
conv224, p112 = self.__pool_layer(stem, filters=filters, block_num=1) # (b, 112, 112, 64)
conv112, p56 = self.__pool_layer(p112, filters=filters * 2, block_num=2) # (b, 56, 56, 128)
conv56, p28 = self.__pool_layer(p56, filters=filters * 4, block_num=3) # (b, 28, 28, 256)
conv28, p14 = self.__pool_layer(p28, filters=filters * 8, block_num=4) # (b, 14, 14, 512)
conv14, _ = self.__pool_layer(p14, filters=filters * 16, block_num=5) # (b, 14, 14, 512)
# conv14 = Dropout(0.5)(conv14)
u28 = self.__unpool_block(pooled=conv14, prepooled=conv28, block_num=1)
u56 = self.__unpool_block(pooled=u28, prepooled=conv56, block_num=2)
u112 = self.__unpool_block(pooled=u56, prepooled=conv112, block_num=3)
u224 = self.__unpool_block(pooled=u112, prepooled=conv224, block_num=4)
predictions = Conv2D(filters=4, kernel_size=1, activation='softmax', name='predictions')(u224)
mask = Lambda(metrics.compute_mask)(inputs)
masked_predictions = Lambda(lambda mask_n_preds: mask_n_preds[0] * mask_n_preds[1])(
[mask, predictions]) # multiply([mask, predictions])
model = Model(inputs=inputs, outputs=masked_predictions)
model.compile(optimizer=Adam(lr=1e-3), loss=metrics.keras_dice_coef_loss(),
metrics=[metrics.wt_dice,
metrics.tc_dice,
metrics.et_dice])
model.summary()
plot_model(model, self.config.results_path + '/model.png', show_shapes=True, show_layer_names=True)
return model
def train(self, train_gen, val_gen):
print('Fitting model...')
predict_train_callback = PredictCallback(train_gen, self.config, 'train')
predict_val_callback = PredictCallback(val_gen, self.config, 'val')
model_checkpoint = ModelCheckpoint(self.config.results_path + '/' + self.weights_file,
monitor='val_loss',
verbose=1,
save_best_only=True)
logger = CSVLogger(self.config.results_path + '/results.csv')
tensorboard = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)
earlystopping = EarlyStopping(monitor='val_loss', patience=50)
callbacks = [TerminateOnNaN(), earlystopping, model_checkpoint, predict_train_callback, predict_val_callback,
logger, tensorboard]
history = self.model.fit_generator(generator=train_gen,
steps_per_epoch=len(train_gen),
validation_data=val_gen,
validation_steps=len(val_gen),
epochs=9000,
verbose=1,
callbacks=callbacks)
return history
if __name__ == '__main__':
config = configuration.Config()
net = Unet(config)
brats = BRATSReader(use_hgg=True, use_lgg=True)
# print(brats.get_mean_dev(.15, 't1ce'))
train_ids, val_ids, test_ids = brats.get_case_ids(config.brats_val_split)
height, width, slices = brats.get_dims()
train_datagen = SliceGenerator(brats, slices, train_ids, dim=(config.slice_batch_size, height, width, 4),
config=config, augmentor=augmentation.train_augmentation, use_all_cross_sections=False)
val_datagen = SliceGenerator(brats, slices, val_ids, dim=(config.slice_batch_size, height, width, 4), config=config,
augmentor=augmentation.test_augmentation, use_all_cross_sections=False)
net.train(train_datagen, val_datagen)