-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_frcnn.py
418 lines (323 loc) · 15.5 KB
/
train_frcnn.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
from __future__ import division
import random
import pprint
import sys
import time
import boto3
import numpy as np
from optparse import OptionParser
import pickle
sys.path.append('.')
from keras import backend as K
from keras.optimizers import Adam
from keras.layers import Input
from keras.models import Model
from keras_frcnn import config, data_generators
from keras_frcnn import losses as losses
import keras_frcnn.roi_helpers as roi_helpers
from keras.utils import generic_utils
from keras_frcnn.simple_parser import get_data
from keras_frcnn import resnet as nn
from utils.text_classification import process_text_analysis
sys.setrecursionlimit(40000)
parser = OptionParser()
parser.add_option("-p", "--path", dest="train_path", help="Path to training data.", default="annotate.txt")
parser.add_option("-o", "--parser", dest="parser", help="Parser to use. One of simple or pascal_voc",
default="simple")
parser.add_option("-n", "--num_rois", type="int", dest="num_rois", help="Number of RoIs to process at once.",
default=32)
parser.add_option("--network", dest="network", help="Base network to use. Supports vgg or resnet50.",
default='resnet50')
parser.add_option("--hf", dest="horizontal_flips", help="Augment with horizontal flips in training. (Default=false).",
action="store_true", default=False)
parser.add_option("--vf", dest="vertical_flips", help="Augment with vertical flips in training. (Default=false).",
action="store_true", default=False)
parser.add_option("--rot", "--rot_90", dest="rot_90",
help="Augment with 90 degree rotations in training. (Default=false).",
action="store_true", default=False)
parser.add_option("--num_epochs", type="int", dest="num_epochs", help="Number of epochs.", default=50)
parser.add_option("--config_filename", dest="config_filename", help=
"Location to store all the metadata related to the training (to be used when testing).",
default="config.pickle")
parser.add_option("--output_weight_path", dest="output_weight_path", help="Output path for weights.",
default='./model_frcnn.hdf5')
parser.add_option("--input_weight_path", dest="input_weight_path",
help="Input path for weights. If not specified, will try to load default weights provided by keras.",
default='./model_frcnn.hdf5')
(options, args) = parser.parse_args()
if not options.train_path: # if filename is not given
parser.error('Error: path to training data must be specified. Pass --path to command line')
# pass the settings from the command line, and persist them in the config object
C = config.Config()
C.use_horizontal_flips = bool(options.horizontal_flips)
C.use_vertical_flips = bool(options.vertical_flips)
C.rot_90 = bool(options.rot_90)
C.model_path = options.output_weight_path
C.num_rois = int(options.num_rois)
C.network = 'resnet50'
# check if weight path was passed via command line
if options.input_weight_path:
print('opened input weight')
C.base_net_weights = options.input_weight_path
else:
# set the path to weights based on backend and model
C.base_net_weights = nn.get_weight_path()
print('new input weight')
all_imgs, classes_count, class_mapping = get_data(options.train_path)
if 'bg' not in classes_count:
classes_count['bg'] = 0
class_mapping['bg'] = len(class_mapping)
C.class_mapping = class_mapping
inv_map = {v: k for k, v in class_mapping.items()}
print('Training images per class:')
pprint.pprint(classes_count)
print('Num classes (including bg) = {}'.format(len(classes_count)))
config_output_filename = options.config_filename
with open(config_output_filename, 'wb') as config_f:
pickle.dump(C, config_f)
print('Config has been written to {}, and can be loaded when testing to ensure correct results'.format(
config_output_filename))
random.shuffle(all_imgs)
num_imgs = len(all_imgs)
train_imgs = [s for s in all_imgs if s['imageset'] == 'trainval']
val_imgs = [s for s in all_imgs if s['imageset'] == 'test']
print('Num train samples {}'.format(len(train_imgs)))
print('Num val samples {}'.format(len(val_imgs)))
data_gen_train = data_generators.get_anchor_gt(train_imgs, classes_count, C, nn.get_img_output_length,
K.image_dim_ordering(), mode='train')
data_gen_val = data_generators.get_anchor_gt(val_imgs, classes_count, C, nn.get_img_output_length,
K.image_dim_ordering(), mode='val')
if K.image_dim_ordering() == 'th':
input_shape_img = (3, None, None)
else:
input_shape_img = (None, None, 3)
img_input = Input(shape=input_shape_img)
roi_input = Input(shape=(None, 4))
'''
txt_input = Input(shape=(5,))
embedding_dim = 50
maxlen = 5
x = Embedding(1000, embedding_dim, input_length=maxlen)(txt_input)
x = Conv1D(128, 5, activation="relu")(x)
x = GlobalMaxPooling1D()(x)
x = Dense(10, activation='relu')(x)
x = Dense(1, activation='sigmoid')(x)
model_text = Model(txt_input, x)
tokenizer = Tokenizer(num_words=1100)
model_text.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])
'''
# define the base network (resnet here, can be VGG, Inception, etc)
print(img_input)
shared_layers = nn.nn_base(img_input, trainable=True)
# define the RPN, built on the base layers
num_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)
rpn = nn.rpn(shared_layers, num_anchors)
classifier = nn.classifier(shared_layers, roi_input, C.num_rois, nb_classes=len(classes_count), trainable=True)
model_rpn = Model(img_input, rpn[:2])
model_classifier = Model([img_input, roi_input], classifier)
# this is a model that holds both the RPN and the classifier, used to load/save weights for the models
model_all = Model([img_input, roi_input], rpn[:2] + classifier)
try:
print('loading weights from {}'.format(C.base_net_weights))
model_rpn.load_weights(C.base_net_weights, by_name=True)
model_classifier.load_weights(C.base_net_weights, by_name=True)
except:
print('Could not load pretrained model weights. Weights can be found in the keras application folder \
https://github.com/fchollet/keras/tree/master/keras/applications')
optimizer = Adam(lr=1e-5)
optimizer_classifier = Adam(lr=1e-5)
model_rpn.compile(optimizer=optimizer, loss=[losses.rpn_loss_cls(num_anchors), losses.rpn_loss_regr(num_anchors)])
model_classifier.compile(optimizer=optimizer_classifier,
loss=[losses.class_loss_cls, losses.class_loss_regr(len(classes_count) - 1)],
metrics={'dense_class_{}'.format(len(classes_count)): 'accuracy'})
model_all.compile(optimizer='sgd', loss='mae')
epoch_length = 1000
num_epochs = int(options.num_epochs)
iter_num = 0
losses = np.zeros((epoch_length, 5))
rpn_accuracy_rpn_monitor = []
rpn_accuracy_for_epoch = []
start_time = time.time()
best_loss = np.Inf
class_mapping_inv = {v: k for k, v in class_mapping.items()}
s3 = boto3.resource('s3')
b_name = 'buttunscreenshot'
print('Starting training')
vis = True
def label_text_buttons(img_data):
filepath = img_data['filepath']
img_name = filepath.split('/')[-1]
res = process_text_analysis(b_name, img_name)
# img1 = cv2.imread(filepath)
for b in img_data['bboxes']:
rx1, ry1, rx2, ry2 = b['x1'], b['y1'], b['x2'], b['y2']
# cv2.rectangle(img1, (rx1, ry1), (rx2, ry2), (0, 0, 255), 2)
bt_word = ''
for word in res:
dx1, dy1, dx2, dy2 = word[1]
if dx1 > rx1 and dy1 > ry1 and dx2 < rx2 and dy1 < ry2:
# cv2.putText(img1, word[0], (rx1, ry1), cv2.FONT_HERSHEY_DUPLEX, 0.5, (0, 0, 255), 1)
bt_word += f'{word[0]} '
elif word[0] != ' ' and word[0] not in button_txt and word[0] not in backgraund_txt:
backgraund_txt.append(word[0])
# print(f'{word[0]}, bg')
bt_word = bt_word[:-1]
if bt_word != ' ' and bt_word not in button_txt:
button_txt.append(bt_word)
# print(f'{bt_word}, bt')
X_text = []
y_text = []
for bt in button_txt:
if bt in backgraund_txt:
backgraund_txt.remove(bt)
X_text.append(bt)
y_text.append(1)
for bg in backgraund_txt:
if bg:
X_text.append(bg)
y_text.append(0)
return backgraund_txt, button_txt
'''
text_annotate = False
if text_annotate:
# annotate text-data
button_txt = []
backgraund_txt = []
for _ in range(len(train_imgs)):
X, Y, img_data = next(data_gen_train)
label_text_buttons(img_data)
for _ in range(len(val_imgs)):
X, Y, img_data = next(data_gen_val)
label_text_buttons(img_data)
text_data = open('/homes/zahara/PycharmProjects/text_button_detection/data/text_bt.txt', 'w')
for bt in button_txt:
if bt in backgraund_txt:
backgraund_txt.remove(bt)
# print(f'{bt}, bt')
text_data.write(f'{bt}, bt\n')
for bg in backgraund_txt:
if bg:
text_data.write(f'{bg}, bg\n')
# print(f'{bg}, bg')
text_data.close()
print('Done text annotation')
'''
button_txt = []
backgraund_txt = []
for epoch_num in range(num_epochs):
progbar = generic_utils.Progbar(epoch_length)
print('Epoch {}/{}'.format(epoch_num + 1, num_epochs))
while True:
try:
if len(rpn_accuracy_rpn_monitor) == epoch_length and C.verbose:
mean_overlapping_bboxes = float(sum(rpn_accuracy_rpn_monitor)) / len(rpn_accuracy_rpn_monitor)
rpn_accuracy_rpn_monitor = []
print('Average number of overlapping bounding boxes from RPN = {} for {} previous iterations'.format(
mean_overlapping_bboxes, epoch_length))
if mean_overlapping_bboxes == 0:
print(
'RPN is not producing bounding boxes that overlap the ground truth boxes. Check RPN settings or keep training.')
X, Y, img_data = next(data_gen_train)
'''
X_text, y_text = label_text_buttons(img_data)
tokenizer.fit_on_texts(X_text)
X_text = tokenizer.texts_to_sequences(X_text)
X_text = pad_sequences(X_text, padding='post', maxlen=maxlen)
loss_txt = model_text.train_on_batch(X_text, y_text)
pred_text = model_text.predict_on_batch(X_text)
'''
loss_rpn = model_rpn.train_on_batch(X, Y)
P_rpn = model_rpn.predict_on_batch(X)
R = roi_helpers.rpn_to_roi(P_rpn[0], P_rpn[1], C, K.image_dim_ordering(), use_regr=True, overlap_thresh=0.7,
max_boxes=300)
# note: calc_iou converts from (x1,y1,x2,y2) to (x,y,w,h) format
X2, Y1, Y2, IouS = roi_helpers.calc_iou(R, img_data, C, class_mapping)
if X2 is None:
rpn_accuracy_rpn_monitor.append(0)
rpn_accuracy_for_epoch.append(0)
continue
neg_samples = np.where(Y1[0, :, -1] == 1)
pos_samples = np.where(Y1[0, :, -1] == 0)
if len(neg_samples) > 0:
neg_samples = neg_samples[0]
else:
neg_samples = []
if len(pos_samples) > 0:
pos_samples = pos_samples[0]
else:
pos_samples = []
rpn_accuracy_rpn_monitor.append(len(pos_samples))
rpn_accuracy_for_epoch.append((len(pos_samples)))
if C.num_rois > 1:
if len(pos_samples) < C.num_rois // 2:
selected_pos_samples = pos_samples.tolist()
else:
selected_pos_samples = np.random.choice(pos_samples, C.num_rois // 2, replace=False).tolist()
try:
selected_neg_samples = np.random.choice(neg_samples, C.num_rois - len(selected_pos_samples),
replace=False).tolist()
except ValueError:
try:
selected_neg_samples = np.random.choice(
neg_samples, C.num_rois - len(selected_pos_samples), replace=True).tolist()
except:
# The neg_samples is [[1 0 ]] only, therefore there's no negative sample
continue
sel_samples = selected_pos_samples + selected_neg_samples
else:
# in the extreme case where num_rois = 1, we pick a random pos or neg sample
selected_pos_samples = pos_samples.tolist()
selected_neg_samples = neg_samples.tolist()
if np.random.randint(0, 2):
sel_samples = random.choice(neg_samples)
else:
sel_samples = random.choice(pos_samples)
loss_class = model_classifier.train_on_batch([X, X2[:, sel_samples, :]],
[Y1[:, sel_samples, :], Y2[:, sel_samples, :]])
losses[iter_num, 0] = loss_rpn[1]
losses[iter_num, 1] = loss_rpn[2]
losses[iter_num, 2] = loss_class[1]
losses[iter_num, 3] = loss_class[2]
losses[iter_num, 4] = loss_class[3]
# losses[iter_num, 5] = loss_txt[1]
progbar.update(iter_num + 1, [('rpn_cls', losses[iter_num, 0]), ('rpn_regr', losses[iter_num, 1]),
('detect_cls', losses[iter_num, 2]),
('detect_regr', losses[iter_num, 3])
# ,('text_regr', losses[iter_num, 5])
])
iter_num += 1
if iter_num == epoch_length:
loss_rpn_cls = np.mean(losses[:, 0])
loss_rpn_regr = np.mean(losses[:, 1])
loss_class_cls = np.mean(losses[:, 2])
loss_class_regr = np.mean(losses[:, 3])
class_acc = np.mean(losses[:, 4])
# loss_txt_cls = np.mean(losses[:, 5])
mean_overlapping_bboxes = float(sum(rpn_accuracy_for_epoch)) / len(rpn_accuracy_for_epoch)
rpn_accuracy_for_epoch = []
if C.verbose:
print('Mean number of bounding boxes RPN overlapping ground truth boxes: {}'.format(
mean_overlapping_bboxes))
print('Accuracy for bounding boxes RPN: {}'.format(class_acc))
print('Loss RPN class: {}'.format(loss_rpn_cls))
print('Loss RPN regress: {}'.format(loss_rpn_regr))
print('Loss Detect class: {}'.format(loss_class_cls))
print('Loss Detect regress: {}'.format(loss_class_regr))
# print('Loss txt: {}'.format(loss_txt_cls))
print('Elapsed time: {} minutes'.format((time.time() - start_time) / 60))
curr_loss = loss_rpn_cls + loss_rpn_regr + loss_class_cls + loss_class_regr #+ loss_txt_cls
iter_num = 0
start_time = time.time()
if curr_loss < best_loss:
if C.verbose:
print('Total loss decreased from {} to {}, saving weights'.format(best_loss, curr_loss))
best_loss = curr_loss
model_all.save_weights(C.model_path)
break
break
except Exception as e:
print('Exception at end: {}'.format(e))
continue
print('Training complete, exiting.')