forked from daniCh8/road-segmentation-eth-cil-2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.py
183 lines (153 loc) · 8.32 KB
/
model.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
import keras
from keras.models import load_model
import keras.backend as K
from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
from DataGenerator import DataGenerator
from TestData import TestData
from Labelizer import Labelizer
from visualization import display_predictions
from utils import preprocess_test_images, merge_predictions, submission_outputs
from nets.u_xception import create_model as u_xception_net
from nets.u_resnet50v2 import create_model as u_resnet50v2_net
from nets.unet import create_model as u_net
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
def create_callbacks(loss='bce', checkpoint_path='../checkpoints/model_checkpoint.h5', with_val=False):
if with_val:
monitor_prefix = 'val_'
else:
monitor_prefix = ''
if loss == 'bce':
to_monitor = monitor_prefix+'acc'
else:
to_monitor = monitor_prefix+'dice_coef'
reduce_lr = ReduceLROnPlateau(monitor=to_monitor, patience=3, mode='max', factor=0.5)
early_stop = EarlyStopping(monitor=to_monitor, mode='max', patience=10)
# checkpoint = ModelCheckpoint(checkpoint_path, monitor=to_monitor, mode='max', save_best_only=True)
# checkpoints usually slow down the process
return [reduce_lr, early_stop] # , checkpoint]
def iou_coef(y_true, y_pred, smooth=1):
intersection = K.sum(K.abs(y_true * y_pred), axis=[1,2,3])
union = K.sum(y_true,[1,2,3])+K.sum(y_pred,[1,2,3])-intersection
iou = K.mean((intersection + smooth) / (union + smooth), axis=0)
return iou
def dice_coef(y_true, y_pred, smooth = 1):
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 soft_dice_loss(y_true, y_pred):
return 1-dice_coef(y_true, y_pred)
class NNet:
def __init__(self, val_split=.0, model_to_load='None', net_type='u_xception', load_weights='None', data_paths=None):
assert net_type in ['u_xception', 'u_resnet50v2', 'unet'], "net_type must be one of ['u_xception', 'u_resnet50v2', 'unet']"
self.net_type = net_type
print('creating model: {}'.format(net_type))
if model_to_load == 'None':
if net_type == 'u_xception':
self.model = u_xception_net()
elif net_type == 'u_resnet50v2':
self.model = u_resnet50v2_net()
elif net_type == 'unet':
self.model = u_net()
print('created model: {}'.format(self.model.name))
if load_weights != 'None':
weights = np.load(load_weights, allow_pickle=True)
self.model.set_weights(weights)
print('loaded weights: {}'.format(load_weights))
else:
self.model = load_model(model_to_load, custom_objects={'soft_dice_loss': soft_dice_loss,
'dice_coef': dice_coef,
'iou_coef': iou_coef})
print('loaded model: {}'.format(model_to_load))
print('model name: {}'.format(self.model.name))
self.data = None
self.valid_set = None
self.val_split = val_split
self.load_data(val_split=val_split, paths=data_paths)
if data_paths is None:
self.test_data_gen = TestData()
else:
self.test_data_gen = TestData(data_paths['test_data_path'])
self.test_images = self.test_data_gen.get_test_data()
self.preprocessed_test_images = preprocess_test_images(self.test_images)/255
self.test_images_predictions = None
def load_data(self, val_split=.0, paths=None):
self.val_split = val_split
if paths is None:
self.data = DataGenerator(val_split=val_split)
else:
self.data = DataGenerator(val_split=val_split,
image_path=paths['image_path'],
groundtruth_path=paths['groundtruth_path'],
additional_images_path=paths['additional_images_path'],
additional_masks_path=paths['additional_masks_path'])
if self.val_split != .0:
self.valid_set = self.data.return_validation_set()
else:
self.valid_set = next(self.data.generator(len(self.data.images)))
def train(self, loss='bce', epochs=100, l_rate=.0001, batch_size=8, train_on='competition_data', verb=1):
assert loss in ['bce', 'dice'], "loss must be one of ['bce', 'dice']"
assert train_on in ['competition_data', 'google_data'], "train_on must be one of ['competition_data', 'google_data']"
optimizer = keras.optimizers.adam(l_rate)
metrics = ['acc', iou_coef, dice_coef]
if loss == 'bce':
self.model.compile(optimizer=optimizer, loss='binary_crossentropy', metrics=metrics)
else:
self.model.compile(optimizer=optimizer, loss=soft_dice_loss, metrics=metrics)
if train_on == 'competition_data':
steps = len(self.data.images) // batch_size
if self.val_split != .0:
self.model.fit_generator(generator=self.data.generator(batch_size),
validation_data=self.valid_set,
epochs=epochs, steps_per_epoch=steps,
callbacks=create_callbacks(loss, with_val=True),
verbose=verb)
else:
self.model.fit_generator(generator=self.data.generator(batch_size),
epochs=epochs,
steps_per_epoch=steps,
callbacks=create_callbacks(loss),
verbose=verb)
else:
steps = len(self.data.additional_images) // batch_size
# val_data = (np.array(self.data.images)/255, np.round(np.expand_dims(np.array(self.data.truths), -1)/255))
self.model.fit_generator(generator=self.data.additional_generator(batch_size),
epochs=epochs,
steps_per_epoch=steps,
callbacks=create_callbacks(loss),
verbose=verb)
def check_outputs(self):
plt.figure(figsize=(15, 15))
gen = self.data.generator(30)
batch = next(gen)
display_predictions(batch[0], self.model.predict(batch[0]), batch[1])
def evaluate_model(self):
labelizer = Labelizer()
val_predictions = self.model.predict(self.valid_set[0]).reshape(-1, 400, 400,)
predictions_labs = labelizer.make_submission(val_predictions)[0]
groundtruths = labelizer.make_submission(self.valid_set[1])[0]
print(accuracy_score(groundtruths, predictions_labs))
def save_model(self, path=None):
if path is None:
path = "model-{}.npy".format(self.net_type)
weights = self.model.get_weights()
np.save(path, weights)
def predict_test_data(self):
predictions = self.model.predict(self.preprocessed_test_images)
self.test_images_predictions = merge_predictions(predictions.reshape(-1, 400, 400,), mode='max')
return self.test_images_predictions
def display_test_predictions(self, submission_path, samples_number=5, figure_size=(15, 15)):
plt.figure(figsize=figure_size)
display_predictions(self.test_images,
self.test_images_predictions,
submission_outputs=submission_outputs(submission_path, self.test_data_gen.numbers),
samples=samples_number)
def create_submission_file(self, path='submission.csv', treshold=.25):
labelizer = Labelizer(treshold)
submission = labelizer.make_submission(self.test_images_predictions, self.test_data_gen.numbers)
submission_df = pd.DataFrame({'id': submission[1], 'prediction': submission[0]})
submission_df.to_csv(path, index=False)
return submission_df