forked from jocicmarko/ultrasound-nerve-segmentation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
251 lines (194 loc) · 8.91 KB
/
train.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
from __future__ import print_function
import cv2
import numpy as np
from sklearn.cross_validation import KFold, LabelKFold
from keras.models import Model
from keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D, Dropout
from keras.optimizers import Adam
from keras.optimizers import Adadelta
from keras.optimizers import sgd
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras.utils import np_utils
from keras import backend as K
from data import load_train_data, load_test_data
img_rows = 64
img_cols = 80
batch_size = 32
epochs = 20
folds = 10
smooth = 1.
dropout = 0.
def dice_coef(y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def _dice_coef(y_true, y_pred):
y_true_f = K.batch_flatten(y_true)
y_pred_f = K.batch_flatten(y_pred)
intersection = 2. * K.sum(y_true_f * y_pred_f, axis=1, keepdims=True) + smooth
union = K.sum(y_true_f, axis=1, keepdims=True) + K.sum(y_pred_f, axis=1, keepdims=True) + smooth
return K.mean(intersection / union)
def dice_coef_loss(y_true, y_pred):
return -dice_coef(y_true, y_pred)
def get_unet():
inputs = Input((1, img_rows, img_cols))
conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same', init='he_normal')(inputs)
conv1 = Convolution2D(32, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
d1 = Dropout(dropout)(pool1)
conv2 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', init='he_normal')(pool1)
conv2 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2))(conv2)
d2 = Dropout(dropout)(pool2)
conv3 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', init='he_normal')(pool2)
conv3 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2))(conv3)
d3 = Dropout(dropout)(pool3)
conv4 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', init='he_normal')(pool3)
conv4 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2))(conv4)
d4 = Dropout(dropout)(pool4)
conv5 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', init='he_normal')(pool4)
conv5 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv5)
up6 = merge([UpSampling2D(size=(2, 2))(conv5), conv4], mode='concat', concat_axis=1)
conv6 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', init='he_normal')(up6)
conv6 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv6)
up7 = merge([UpSampling2D(size=(2, 2))(conv6), conv3], mode='concat', concat_axis=1)
conv7 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', init='he_normal')(up7)
conv7 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv7)
up8 = merge([UpSampling2D(size=(2, 2))(conv7), conv2], mode='concat', concat_axis=1)
conv8 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', init='he_normal')(up8)
conv8 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv8)
up9 = merge([UpSampling2D(size=(2, 2))(conv8), conv1], mode='concat', concat_axis=1)
conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same', init='he_normal')(up9)
conv9 = Convolution2D(32, 3, 3, activation='relu', border_mode='same', init='he_normal')(conv9)
conv10 = Convolution2D(1, 1, 1, activation='sigmoid', init='he_normal')(conv9)
model = Model(input=inputs, output=conv10)
model.compile(optimizer=Adam(lr=1e-4), loss=dice_coef_loss, metrics=[dice_coef])
return model
def preprocess(imgs):
imgs_p = np.ndarray((imgs.shape[0], imgs.shape[1], img_rows, img_cols), dtype=np.uint8)
for i in range(imgs.shape[0]):
imgs_p[i, 0] = cv2.resize(imgs[i, 0], (img_cols, img_rows), interpolation=cv2.INTER_CUBIC)
return imgs_p
def stan(X, Y=None, mean=None, std=None):
X = X.astype('float32')
if mean is None:
mean = np.mean(X) # mean for data centering
if std is None:
std = np.std(X) # std for data normalization
X-= mean
X/= std
if Y is not None:
Y= Y.astype('float32')
Y/= 255. # scale masks to [0, 1]
return X,Y,mean,std
else:
return X
def run_cross_validation(nfolds=5):
random_state = 51
print('-'*30)
print('Loading and preprocessing train data...')
print('-'*30)
train_data, train_target = load_train_data()
train_data, train_target, mean, std = stan(preprocess(train_data), preprocess(train_target))
imgs_test, imgs_id_test = load_test_data()
imgs_test = stan(preprocess(imgs_test), None, mean, std)
print('-'*30)
print('Data augmentation-aware CV...')
print('-'*30)
foldcolumn = np.zeros(train_data.shape[0])
for i in range(foldcolumn.shape[0]/3):
foldcolumn[3*i+0]=i
foldcolumn[3*i+1]=i
foldcolumn[3*i+2]=i
print(foldcolumn[0:20])
yfull_train = dict()
yfull_test = []
kf = LabelKFold(foldcolumn, n_folds=nfolds)
num_fold = 0
sum_score = 0
for train_index, valid_index in kf:
X_train, X_valid = train_data[train_index], train_data[valid_index]
Y_train, Y_valid = train_target[train_index], train_target[valid_index]
num_fold += 1
print('Start KFold number {} from {}'.format(num_fold, nfolds))
print('Split train: ', len(X_train), len(Y_train))
print('Split valid: ', len(X_valid), len(Y_valid))
callbacks = [
EarlyStopping(monitor='val_loss', patience=20, verbose=0),
ModelCheckpoint('unet.' + str(num_fold) + '.hdf5', monitor='loss', save_best_only=True)
]
print('-'*30)
print('Creating and compiling model...')
print('-'*30)
model = get_unet()
print('-'*30)
print('Fitting model...')
print('-'*30)
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=epochs,
shuffle=True, verbose=2, validation_data=(X_valid, Y_valid),
callbacks=callbacks)
print('-'*30)
print('Making predictions...')
print('-'*30)
## Load best model
model.load_weights('unet.' + str(num_fold) + '.hdf5')
# Store valid predictions
predictions_valid = model.predict(X_valid, batch_size=batch_size, verbose=1)
for i in range(len(valid_index)):
yfull_train[valid_index[i]] = predictions_valid[i]
np.save('imgs_mask_train.pred.fold' + str(num_fold) + '.npy', predictions_valid)
np.save('imgs_mask_train.image.fold' + str(num_fold) + '.npy', X_valid)
np.save('imgs_mask_train.actual.fold' + str(num_fold) + '.npy', Y_valid)
# Store test predictions
test_prediction = model.predict(imgs_test, batch_size=batch_size, verbose=2)
yfull_test.append(test_prediction)
print('-'*30)
print('Predicting masks on test data...')
print('-'*30)
np.save('imgs_mask_test.fold' + str(num_fold) + '.npy', test_prediction)
test_res = merge_several_folds_mean(yfull_test, nfolds)
np.save('imgs_mask_test.npy', test_res)
#np.save('imgs_mask_train_cv.npy', yfull_train)
def run_main_model():
print('-'*30)
print('Loading and preprocessing train data...')
print('-'*30)
train_data, train_target = load_train_data()
train_data, train_target, mean, std = stan(preprocess(train_data), preprocess(train_target))
imgs_test, imgs_id_test = load_test_data()
imgs_test = stan(preprocess(imgs_test), None, mean, std)
X_train = train_data
Y_train = train_target
print('Main Model')
print('Len train: ', len(X_train), len(Y_train))
callbacks = [
ModelCheckpoint('unet.hdf5', monitor='loss', save_best_only=True)
]
print('-'*30)
print('Creating and compiling model...')
print('-'*30)
model = get_unet()
# If existing model -> load it
#model.load_weights('unet.hdf5')
print('-'*30)
print('Fitting model...')
print('-'*30)
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=epochs,
shuffle=True, verbose=2, callbacks=callbacks)
## Load best model
model.load_weights('unet.hdf5')
test_prediction = model.predict(imgs_test, verbose=2)
np.save('imgs_mask_test.npy', test_prediction)
def merge_several_folds_mean(data, nfolds):
a = np.array(data[0])
for i in range(1, nfolds):
a += np.array(data[i])
a /= nfolds
return a.tolist()
if __name__ == '__main__':
#run_cross_validation(folds)
run_main_model()