-
Notifications
You must be signed in to change notification settings - Fork 1
/
compact_cnn.py
260 lines (210 loc) · 9.06 KB
/
compact_cnn.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
import tensorflow as tf
import keras
import numpy as np
import cv2
import matplotlib.pyplot as plt
from google.colab.patches import cv2_imshow
import pickle
import datetime
from keras.layers.convolutional import Conv2D, Conv2DTranspose
from keras.layers import (
Input, Dense, Reshape,
Flatten, Dropout,
BatchNormalization, Activation,
Lambda,Layer, Add, Concatenate,
Average,UpSampling2D,
MaxPooling2D, AveragePooling2D,
GlobalMaxPooling2D,GlobalAveragePooling2D,
)
from keras.models import Sequential, Model, model_from_json
from keras.optimizers import Adam
import utils
class CompactModel:
def __init__(self, rst, lr, base_dir):
self.base_dir = base_dir
self.rst = rst
self.lr = lr
self.seg_his = {'loss': [], 'val_loss': []}
self.seg_model = self.segment_model()
self.cls_model = self.classification_model()
self.combined = self.compact_cnn_model()
def _conv_block(self, x, filters, kernel_size=3,
strides=1, activation='relu', name=None,
batch_norm=True):
if name:
cname = 'conv-' + name
bname = 'bn-' + name
else:
cname = bname = None
out = Conv2D(filters, kernel_size=kernel_size,
strides=strides, activation=activation,
kernel_initializer='random_normal',padding='same',
name=cname)(x)
if batch_norm:
out = BatchNormalization(name=bname)(out)
return out
def segment_model(self):
image = Input(shape=(self.rst, self.rst, 1))
# Block 1
x = self._conv_block(image, 32, kernel_size=11, strides=2, name='seg-1')
x = self._conv_block(x, 32, kernel_size=11, name='seg-2')
x = self._conv_block(x, 32, kernel_size=11, name='seg-3')
# Block 2
x = self._conv_block(x, 64, kernel_size=7, strides=2, name='seg-4')
x = self._conv_block(x, 64, kernel_size=7, name='seg-5')
x = self._conv_block(x, 64, kernel_size=7, name='seg-6')
# Block 3
x = self._conv_block(x, 128, kernel_size=3, name='seg-7')
x = self._conv_block(x, 128, kernel_size=3, name='seg-8')
x = self._conv_block(x, 128, kernel_size=3, name='featmap')
# Segmentation
seg = self._conv_block(x, 1, kernel_size=1,
activation='tanh',name='segmap',
batch_norm=False)
model = Model(inputs=image, outputs=seg)
model.compile(optimizer=Adam(self.lr), loss='mse')
return model
def classification_model(self):
seg_map_1 = GlobalMaxPooling2D()(self.seg_model.get_layer('conv-segmap').output)
bn1 = BatchNormalization()(seg_map_1)
seg_map_2 = GlobalAveragePooling2D()(self.seg_model.get_layer('conv-segmap').output)
bn2 = BatchNormalization()(seg_map_2)
bn3 = self._conv_block(self.seg_model.get_layer('bn-featmap').output,
filters=32, kernel_size=1, strides=1)
feat1 = GlobalMaxPooling2D()(bn3)
bn4 = BatchNormalization()(feat1)
feat2 = GlobalAveragePooling2D()(bn3)
bn5 = BatchNormalization()(feat2)
merged = Concatenate()([bn1, bn2, bn4, bn5])
out = Dense(1, activation='sigmoid',
kernel_initializer='random_normal',
name='clsout')(merged)
model = Model(inputs=self.seg_model.input, outputs=out)
for i in range(len(model.layers)):
name = model.layers[i].name
if any([x in name for x in ['seg', 'featmap']]):
model.layers[i].trainable = False
model.compile(optimizer=Adam(self.lr), loss='binary_crossentropy')
return model
def compact_cnn_model(self):
model = Model(
inputs=self.cls_model.input,
outputs=[
self.cls_model.get_layer('conv-segmap').output,
self.cls_model.get_layer('clsout').output,
]
)
model.compile(optimizer=Adam(self.lr),
loss=['mse', 'binary_crossentropy'],
)
return model
@staticmethod
def init_hist():
return {
"seg": {
"loss": [],
"val_loss": [],
},
"cls": {
"loss": [],
"val_loss": [],
}
}
def train_model(self, model, data_gen, test_gen, epochs, class_weight, augment_factor):
print(" ==== Train model {} ====".format(model))
print("Train on {} samples".format(len(data_gen.x)))
history = self.init_hist()
for e in range(epochs):
start_time = datetime.datetime.now()
print("Train epochs {}/{} - ".format(e + 1, epochs), end="")
batch_loss = self.init_hist()
for img, mask, label in data_gen.next_batch(augment_factor):
sample_weight = utils.weighted_samples(label, class_weight)
if model == 'combined':
# combined model
_, seg_loss, cls_loss = self.combined.train_on_batch(img, [mask, label],
sample_weight=sample_weight)
batch_loss['seg']['loss'].append(seg_loss)
batch_loss['cls']['loss'].append(cls_loss)
else:
if model == 'seg':
loss = self.seg_model.train_on_batch(img, mask, sample_weight=sample_weight)
else:
loss = self.cls_model.train_on_batch(img, label, sample_weight=sample_weight)
batch_loss[model]['loss'].append(loss)
# evaluation
_, seg_val_loss, cls_val_loss = self.combined.evaluate(test_gen.x, [test_gen.y, test_gen.labels], verbose=False)
batch_loss['seg']['val_loss'] = seg_val_loss
batch_loss['cls']['val_loss'] = cls_val_loss
mean_loss = {
k: np.mean(np.array(batch_loss[k]['loss'])) \
for k in batch_loss
}
mean_val_loss = {
k: np.mean(np.array(batch_loss[k]['val_loss'])) \
for k in batch_loss
}
for k in mean_loss:
history[k]['loss'].append(mean_loss[k])
history[k]['val_loss'].append(mean_val_loss[k])
print("Loss: {}, Val Loss: {} - {}".format(
mean_loss,mean_val_loss,
datetime.datetime.now() - start_time
))
return history
def train(self, data_gen, test_gen, seg_epochs, cls_epochs, class_weight=None,
mode="combined", augment_factor=0):
if mode == "combined":
losses = self.train_model('combined',
data_gen,
test_gen,
seg_epochs,
class_weight,
augment_factor)
self.seg_his = losses['seg']
self.cls_his = losses['cls']
else:
self.seg_his = self.train_model('seg', data_gen, test_gen, seg_epochs,
class_weight, augment_factor)['seg']
self.cls_his = self.train_model('cls', data_gen, test_gen, cls_epochs,
class_weight, augment_factor)['cls']
self.plot_history(self.seg_his)
self.plot_history(self.cls_his)
@staticmethod
def plot_history(his):
plt.plot(his['loss'], label='train loss')
plt.plot(his['val_loss'], label='val loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.title('Segmentation model')
plt.legend()
plt.show()
def show_output(self, x, y, idx):
shape = (1, self.rst, self.rst, 1)
image = x[idx].reshape((1, self.rst, self.rst, 1))
mask = y[idx].reshape((1, self.rst//4, self.rst//4, 1))
seg = self.seg_model.predict(image)
score = self.cls_model.predict(image)
plt.figure(figsize=(18,10))
plt.subplot(131)
plt.title("Input")
plt.imshow(image[0].reshape(self.rst,self.rst))
plt.subplot(132)
segmap = seg[0].reshape((self.rst//4,self.rst//4))
plt.title("Input")
plt.imshow(segmap.astype('uint8'))
props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
plt.text(0.2, 0.1, f'Score={score[0]}', fontsize=14,
verticalalignment='top', bbox=props)
plt.subplot(133)
plt.imshow(mask[0].reshape(self.rst//4,self.rst//4))
plt.show()
def save_weight(self):
self.seg_model.save_weights(self.base_dir + '/seg_model.h5')
self.cls_model.save_weights(self.base_dir + '/cls_model.h5')
def load_weight(self):
try:
self.seg_model.load_weights(self.base_dir + '/seg_model.h5')
self.cls_model.load_weights(self.base_dir + '/cls_model.h5')
except:
print("Load Weights failed!")