forked from leetenki/YOLOv2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
yolov2.py
480 lines (433 loc) · 29.3 KB
/
yolov2.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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from chainer import cuda, Function, gradient_check, Variable, optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.links as L
import chainer.functions as F
from lib.utils import *
from lib.functions import *
import copy
class YOLOv2(Chain):
"""
YOLOv2
- It takes (416, 416, 3) sized image as input
"""
def __init__(self, n_classes, n_boxes):
super(YOLOv2, self).__init__(
##### common layers for both pretrained layers and yolov2 #####
conv1 = L.Convolution2D(3, 32, ksize=3, stride=1, pad=1, nobias=True),
bn1 = L.BatchNormalization(32, use_beta=False, eps=2e-5),
bias1 = L.Bias(shape=(32,)),
conv2 = L.Convolution2D(32, 64, ksize=3, stride=1, pad=1, nobias=True),
bn2 = L.BatchNormalization(64, use_beta=False, eps=2e-5),
bias2 = L.Bias(shape=(64,)),
conv3 = L.Convolution2D(64, 128, ksize=3, stride=1, pad=1, nobias=True),
bn3 = L.BatchNormalization(128, use_beta=False, eps=2e-5),
bias3 = L.Bias(shape=(128,)),
conv4 = L.Convolution2D(128, 64, ksize=1, stride=1, pad=0, nobias=True),
bn4 = L.BatchNormalization(64, use_beta=False, eps=2e-5),
bias4 = L.Bias(shape=(64,)),
conv5 = L.Convolution2D(64, 128, ksize=3, stride=1, pad=1, nobias=True),
bn5 = L.BatchNormalization(128, use_beta=False, eps=2e-5),
bias5 = L.Bias(shape=(128,)),
conv6 = L.Convolution2D(128, 256, ksize=3, stride=1, pad=1, nobias=True),
bn6 = L.BatchNormalization(256, use_beta=False, eps=2e-5),
bias6 = L.Bias(shape=(256,)),
conv7 = L.Convolution2D(256, 128, ksize=1, stride=1, pad=0, nobias=True),
bn7 = L.BatchNormalization(128, use_beta=False, eps=2e-5),
bias7 = L.Bias(shape=(128,)),
conv8 = L.Convolution2D(128, 256, ksize=3, stride=1, pad=1, nobias=True),
bn8 = L.BatchNormalization(256, use_beta=False, eps=2e-5),
bias8 = L.Bias(shape=(256,)),
conv9 = L.Convolution2D(256, 512, ksize=3, stride=1, pad=1, nobias=True),
bn9 = L.BatchNormalization(512, use_beta=False, eps=2e-5),
bias9 = L.Bias(shape=(512,)),
conv10 = L.Convolution2D(512, 256, ksize=1, stride=1, pad=0, nobias=True),
bn10 = L.BatchNormalization(256, use_beta=False, eps=2e-5),
bias10 = L.Bias(shape=(256,)),
conv11 = L.Convolution2D(256, 512, ksize=3, stride=1, pad=1, nobias=True),
bn11 = L.BatchNormalization(512, use_beta=False, eps=2e-5),
bias11 = L.Bias(shape=(512,)),
conv12 = L.Convolution2D(512, 256, ksize=1, stride=1, pad=0, nobias=True),
bn12 = L.BatchNormalization(256, use_beta=False, eps=2e-5),
bias12 = L.Bias(shape=(256,)),
conv13 = L.Convolution2D(256, 512, ksize=3, stride=1, pad=1, nobias=True),
bn13 = L.BatchNormalization(512, use_beta=False, eps=2e-5),
bias13 = L.Bias(shape=(512,)),
conv14 = L.Convolution2D(512, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn14 = L.BatchNormalization(1024, use_beta=False, eps=2e-5),
bias14 = L.Bias(shape=(1024,)),
conv15 = L.Convolution2D(1024, 512, ksize=1, stride=1, pad=0, nobias=True),
bn15 = L.BatchNormalization(512, use_beta=False, eps=2e-5),
bias15 = L.Bias(shape=(512,)),
conv16 = L.Convolution2D(512, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn16 = L.BatchNormalization(1024, use_beta=False, eps=2e-5),
bias16 = L.Bias(shape=(1024,)),
conv17 = L.Convolution2D(1024, 512, ksize=1, stride=1, pad=0, nobias=True),
bn17 = L.BatchNormalization(512, use_beta=False, eps=2e-5),
bias17 = L.Bias(shape=(512,)),
conv18 = L.Convolution2D(512, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn18 = L.BatchNormalization(1024, use_beta=False, eps=2e-5),
bias18 = L.Bias(shape=(1024,)),
###### new layer
conv19 = L.Convolution2D(1024, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn19 = L.BatchNormalization(1024, use_beta=False),
bias19 = L.Bias(shape=(1024,)),
conv20 = L.Convolution2D(1024, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn20 = L.BatchNormalization(1024, use_beta=False),
bias20 = L.Bias(shape=(1024,)),
conv21 = L.Convolution2D(3072, 1024, ksize=3, stride=1, pad=1, nobias=True),
bn21 = L.BatchNormalization(1024, use_beta=False),
bias21 = L.Bias(shape=(1024,)),
conv22 = L.Convolution2D(1024, n_boxes * (5 + n_classes), ksize=1, stride=1, pad=0, nobias=True),
bias22 = L.Bias(shape=(n_boxes * (5 + n_classes),)),
)
self.train = False
self.finetune = False
self.n_boxes = n_boxes
self.n_classes = n_classes
def __call__(self, x, target=22):
##### common layer
h = F.leaky_relu(self.bias1(self.bn1(self.conv1(x), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.max_pooling_2d(h, ksize=2, stride=2, pad=0)
h = F.leaky_relu(self.bias2(self.bn2(self.conv2(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.max_pooling_2d(h, ksize=2, stride=2, pad=0)
h = F.leaky_relu(self.bias3(self.bn3(self.conv3(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias4(self.bn4(self.conv4(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias5(self.bn5(self.conv5(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.max_pooling_2d(h, ksize=2, stride=2, pad=0)
h = F.leaky_relu(self.bias6(self.bn6(self.conv6(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias7(self.bn7(self.conv7(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias8(self.bn8(self.conv8(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.max_pooling_2d(h, ksize=2, stride=2, pad=0)
h = F.leaky_relu(self.bias9(self.bn9(self.conv9(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias10(self.bn10(self.conv10(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias11(self.bn11(self.conv11(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias12(self.bn12(self.conv12(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias13(self.bn13(self.conv13(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
high_resolution_feature = reorg(h) # 高解像度特徴量をreorgでサイズ落として保存しておく
h = F.max_pooling_2d(h, ksize=2, stride=2, pad=0)
h = F.leaky_relu(self.bias14(self.bn14(self.conv14(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias15(self.bn15(self.conv15(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias16(self.bn16(self.conv16(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias17(self.bn17(self.conv17(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias18(self.bn18(self.conv18(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
###### new layer
h = F.leaky_relu(self.bias19(self.bn19(self.conv19(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.leaky_relu(self.bias20(self.bn20(self.conv20(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = F.concat((high_resolution_feature, h), axis=1) # output concatnation
h = F.leaky_relu(self.bias21(self.bn21(self.conv21(h), test=not self.train, finetune=self.finetune)), slope=0.1)
target = self.get_h(target, h)
h = self.bias22(self.conv22(h))
target = self.get_h(target, h)
return h
def get_h(self, target, h):
target-=1
if target == 0:
self.gcamout = h
return target
class YOLOv2Predictor(Chain):
def __init__(self, predictor):
super(YOLOv2Predictor, self).__init__(predictor=predictor)
#self.anchors = [[5.375, 5.03125], [5.40625, 4.6875], [2.96875, 2.53125], [2.59375, 2.78125], [1.9375, 3.25]]
self.anchors = [[0.738768, 0.874946], [2.42204, 2.65704], [4.30971, 7.04493], [10.246, 4.59428], [12.6868, 11.8741]]
self.thresh = 0.5
self.seen = 0
self.unstable_seen = 5000
def __call__(self, input_x, t, target=100):
output = self.predictor(input_x, target)
batch_size, _, grid_h, grid_w = output.shape
self.seen += batch_size
x, y, w, h, conf, prob = F.split_axis(F.reshape(output, (batch_size, self.predictor.n_boxes, self.predictor.n_classes+5, grid_h, grid_w)), (1, 2, 3, 4, 5), axis=2)
x = F.sigmoid(x) # xのactivation
y = F.sigmoid(y) # yのactivation
conf = F.sigmoid(conf) # confのactivation
prob = F.transpose(prob, (0, 2, 1, 3, 4))
prob = F.softmax(prob) # probablitiyのacitivation
# 教師データの用意
tw = np.zeros(w.shape, dtype=np.float32) # wとhが0になるように学習(e^wとe^hは1に近づく -> 担当するbboxの倍率1)
th = np.zeros(h.shape, dtype=np.float32)
tx = np.tile(0.5, x.shape).astype(np.float32) # 活性化後のxとyが0.5になるように学習()
ty = np.tile(0.5, y.shape).astype(np.float32)
if self.seen < self.unstable_seen: # centerの存在しないbbox誤差学習スケールは基本0.1
box_learning_scale = np.tile(0.1, x.shape).astype(np.float32)
else:
box_learning_scale = np.tile(0.0, x.shape).astype(np.float32)
tconf = np.zeros(conf.shape, dtype=np.float32) # confidenceのtruthは基本0、iouがthresh以上のものは学習しない、ただしobjectの存在するgridのbest_boxのみ真のIOUに近づかせる
conf_learning_scale = np.tile(0.1, conf.shape).astype(np.float32)
tprob = prob.data.copy() # best_anchor以外は学習させない(自身との二乗和誤差 = 0)
# 全bboxとtruthのiouを計算(batch単位で計算する)
x_shift = Variable(np.broadcast_to(np.arange(grid_w, dtype=np.float32), x.shape[1:]))
y_shift = Variable(np.broadcast_to(np.arange(grid_h, dtype=np.float32).reshape(grid_h, 1), y.shape[1:]))
w_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 0], (self.predictor.n_boxes, 1, 1, 1)), w.shape[1:]))
h_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 1], (self.predictor.n_boxes, 1, 1, 1)), h.shape[1:]))
#x_shift.to_gpu(), y_shift.to_gpu(), w_anchor.to_gpu(), h_anchor.to_gpu()
best_ious = []
for batch in range(batch_size):
box_x = (x[batch] + x_shift) / grid_w
box_y = (y[batch] + y_shift) / grid_h
box_w = F.exp(w[batch]) * w_anchor / grid_w
box_h = F.exp(h[batch]) * h_anchor / grid_h
ious = []
n_truth_boxes = len(t[batch])
for truth_index in range(n_truth_boxes):
truth_box_x = Variable(np.broadcast_to(np.array(t[batch][truth_index]["x"], dtype=np.float32), box_x.shape))
truth_box_y = Variable(np.broadcast_to(np.array(t[batch][truth_index]["y"], dtype=np.float32), box_y.shape))
truth_box_w = Variable(np.broadcast_to(np.array(t[batch][truth_index]["w"], dtype=np.float32), box_w.shape))
truth_box_h = Variable(np.broadcast_to(np.array(t[batch][truth_index]["h"], dtype=np.float32), box_h.shape))
#truth_box_x.to_gpu(), truth_box_y.to_gpu(), truth_box_w.to_gpu(), truth_box_h.to_gpu()
#ious.append(multi_box_iou(Box(box_x, box_y, box_w, box_h), Box(truth_box_x, truth_box_y, truth_box_w, truth_box_h)).data.get())
ious.append(multi_box_iou(Box(box_x, box_y, box_w, box_h), Box(truth_box_x, truth_box_y, truth_box_w, truth_box_h)).data)
ious = np.array(ious)
best_ious.append(np.max(ious, axis=0))
best_ious = np.array(best_ious)
# 一定以上のiouを持つanchorに対しては、confを0に下げないようにする(truthの周りのgridはconfをそのまま維持)。
#tconf[best_ious > self.thresh] = conf.data.get()[best_ious > self.thresh]
tconf[best_ious > self.thresh] = conf.data[best_ious > self.thresh]
conf_learning_scale[best_ious > self.thresh] = 0
# objectの存在するanchor boxのみ、x、y、w、h、conf、probを個別修正
abs_anchors = self.anchors / np.array([grid_w, grid_h])
for batch in range(batch_size):
for truth_box in t[batch]:
truth_w = int(float(truth_box["x"]) * grid_w)
truth_h = int(float(truth_box["y"]) * grid_h)
truth_n = 0
best_iou = 0.0
for anchor_index, abs_anchor in enumerate(abs_anchors):
iou = box_iou(Box(0, 0, float(truth_box["w"]), float(truth_box["h"])), Box(0, 0, abs_anchor[0], abs_anchor[1]))
if best_iou < iou:
best_iou = iou
truth_n = anchor_index
# objectの存在するanchorについて、centerを0.5ではなく、真の座標に近づかせる。anchorのスケールを1ではなく真のスケールに近づかせる。学習スケールを1にする。
box_learning_scale[batch, truth_n, :, truth_h, truth_w] = 1.0
tx[batch, truth_n, :, truth_h, truth_w] = float(truth_box["x"]) * grid_w - truth_w
ty[batch, truth_n, :, truth_h, truth_w] = float(truth_box["y"]) * grid_h - truth_h
tw[batch, truth_n, :, truth_h, truth_w] = np.log(float(truth_box["w"]) / abs_anchors[truth_n][0])
th[batch, truth_n, :, truth_h, truth_w] = np.log(float(truth_box["h"]) / abs_anchors[truth_n][1])
tprob[batch, :, truth_n, truth_h, truth_w] = 1
tprob[batch, int(truth_box["label"]), truth_n, truth_h, truth_w] = 0
# IOUの観測
full_truth_box = Box(float(truth_box["x"]), float(truth_box["y"]), float(truth_box["w"]), float(truth_box["h"]))
#predicted_box = Box(
# (x[batch][truth_n][0][truth_h][truth_w].data.get() + truth_w) / grid_w,
# (y[batch][truth_n][0][truth_h][truth_w].data.get() + truth_h) / grid_h,
# np.exp(w[batch][truth_n][0][truth_h][truth_w].data.get()) * abs_anchors[truth_n][0],
# np.exp(h[batch][truth_n][0][truth_h][truth_w].data.get()) * abs_anchors[truth_n][1]
#)
predicted_box = Box(
(x[batch][truth_n][0][truth_h][truth_w].data + truth_w) / grid_w,
(y[batch][truth_n][0][truth_h][truth_w].data + truth_h) / grid_h,
np.exp(w[batch][truth_n][0][truth_h][truth_w].data) * abs_anchors[truth_n][0],
np.exp(h[batch][truth_n][0][truth_h][truth_w].data) * abs_anchors[truth_n][1]
)
predicted_iou = box_iou(full_truth_box, predicted_box)
tconf[batch, truth_n, :, truth_h, truth_w] = predicted_iou
conf_learning_scale[batch, truth_n, :, truth_h, truth_w] = 10.0
# debug prints
maps = F.transpose(prob[batch], (2, 3, 1, 0)).data
print("best confidences and best conditional probability and predicted class of each grid:")
for i in range(grid_h):
for j in range(grid_w):
s = "{:2d} {:2d} {:2d} ".format(
int(conf[batch, :, :, i, j].data.max() * 100),
maps[i][j][int(maps[i][j].max(axis=1).argmax())].argmax(),
int(maps[i][j][int(maps[i][j].max(axis=1).argmax())].max()*100)
)
print s
print("best default iou: %.2f predicted iou: %.2f confidence: %.2f class: %s" % (best_iou, predicted_iou, conf[batch][truth_n][0][truth_h][truth_w].data, t[batch][0]["label"]))
print("-------------------------------")
print("seen = %d" % self.seen)
# loss計算
tx, ty, tw, th, tconf, tprob = Variable(tx), Variable(ty), Variable(tw), Variable(th), Variable(tconf), Variable(tprob)
box_learning_scale, conf_learning_scale = Variable(box_learning_scale), Variable(conf_learning_scale)
#tx.to_gpu(), ty.to_gpu(), tw.to_gpu(), th.to_gpu(), tconf.to_gpu(), tprob.to_gpu()
#box_learning_scale.to_gpu()
#conf_learning_scale.to_gpu()
x_loss = F.sum((tx - x) ** 2 * box_learning_scale) / 2
y_loss = F.sum((ty - y) ** 2 * box_learning_scale) / 2
w_loss = F.sum((tw - w) ** 2 * box_learning_scale) / 2
h_loss = F.sum((th - h) ** 2 * box_learning_scale) / 2
c_loss = F.sum((tconf - conf) ** 2 * conf_learning_scale) / 2
p_loss = F.sum((tprob - prob) ** 2) / 2
print("x_loss: %f y_loss: %f w_loss: %f h_loss: %f c_loss: %f p_loss: %f" %
(F.sum(x_loss).data, F.sum(y_loss).data, F.sum(w_loss).data, F.sum(h_loss).data, F.sum(c_loss).data, F.sum(p_loss).data)
)
loss = x_loss + y_loss + w_loss + h_loss + c_loss + p_loss
return loss
def gcam(self, input_x, t, target=22):
output = self.predictor(input_x, target)
batch_size, _, grid_h, grid_w = output.shape
self.seen += batch_size
x, y, w, h, conf, prob = F.split_axis(F.reshape(output, (batch_size, self.predictor.n_boxes, self.predictor.n_classes+5, grid_h, grid_w)), (1, 2, 3, 4, 5), axis=2)
x = F.sigmoid(x) # xのactivation
y = F.sigmoid(y) # yのactivation
conf = F.sigmoid(conf) # confのactivation
prob = F.transpose(prob, (0, 2, 1, 3, 4))
prob = F.softmax(prob) # probablitiyのacitivation
# 教師データの用意
tw = np.zeros(w.shape, dtype=np.float32) # wとhが0になるように学習(e^wとe^hは1に近づく -> 担当するbboxの倍率1)
th = np.zeros(h.shape, dtype=np.float32)
tx = np.tile(0.5, x.shape).astype(np.float32) # 活性化後のxとyが0.5になるように学習()
ty = np.tile(0.5, y.shape).astype(np.float32)
#tw = copy.copy(w.data)
#th = copy.copy(h.data)
#tx = copy.copy(x.data)
#ty = copy.copy(y.data)
if self.seen < self.unstable_seen: # centerの存在しないbbox誤差学習スケールは基本0.1
box_learning_scale = np.tile(0.1, x.shape).astype(np.float32)
else:
box_learning_scale = np.tile(0.0, x.shape).astype(np.float32)
tconf = np.zeros(conf.shape, dtype=np.float32) # confidenceのtruthは基本0、iouがthresh以上のものは学習しない、ただしobjectの存在するgridのbest_boxのみ真のIOUに近づかせる
conf_learning_scale = np.tile(1.0, conf.shape).astype(np.float32)
tprob = prob.data.copy() # best_anchor以外は学習させない(自身との二乗和誤差 = 0)
#tprob = np.zeros(prob.data.shape, dtype=np.float32)
#tprob = np.ones(prob.data.shape, dtype=np.float32)
# 全bboxとtruthのiouを計算(batch単位で計算する)
x_shift = Variable(np.broadcast_to(np.arange(grid_w, dtype=np.float32), x.shape[1:]))
y_shift = Variable(np.broadcast_to(np.arange(grid_h, dtype=np.float32).reshape(grid_h, 1), y.shape[1:]))
w_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 0], (self.predictor.n_boxes, 1, 1, 1)), w.shape[1:]))
h_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 1], (self.predictor.n_boxes, 1, 1, 1)), h.shape[1:]))
#x_shift.to_gpu(), y_shift.to_gpu(), w_anchor.to_gpu(), h_anchor.to_gpu()
best_ious = []
for batch in range(batch_size):
box_x = (x[batch] + x_shift) / grid_w
box_y = (y[batch] + y_shift) / grid_h
box_w = F.exp(w[batch]) * w_anchor / grid_w
box_h = F.exp(h[batch]) * h_anchor / grid_h
ious = []
if len(t):
n_truth_boxes = len(t[batch])
else:
n_truth_boxes = 0
ious.append(0.0)
for truth_index in range(n_truth_boxes):
truth_box_x = Variable(np.broadcast_to(np.array(t[batch][truth_index]["x"], dtype=np.float32), box_x.shape))
truth_box_y = Variable(np.broadcast_to(np.array(t[batch][truth_index]["y"], dtype=np.float32), box_y.shape))
truth_box_w = Variable(np.broadcast_to(np.array(t[batch][truth_index]["w"], dtype=np.float32), box_w.shape))
truth_box_h = Variable(np.broadcast_to(np.array(t[batch][truth_index]["h"], dtype=np.float32), box_h.shape))
#truth_box_x.to_gpu(), truth_box_y.to_gpu(), truth_box_w.to_gpu(), truth_box_h.to_gpu()
#ious.append(multi_box_iou(Box(box_x, box_y, box_w, box_h), Box(truth_box_x, truth_box_y, truth_box_w, truth_box_h)).data.get())
ious.append(multi_box_iou(Box(box_x, box_y, box_w, box_h), Box(truth_box_x, truth_box_y, truth_box_w, truth_box_h)).data)
ious = np.array(ious)
best_ious.append(np.max(ious, axis=0))
best_ious = np.array(best_ious)
# 一定以上のiouを持つanchorに対しては、confを0に下げないようにする(truthの周りのgridはconfをそのまま維持)。
#tconf[best_ious > self.thresh] = conf.data.get()[best_ious > self.thresh]
tconf[best_ious > self.thresh] = conf.data[best_ious > self.thresh]
conf_learning_scale[best_ious > self.thresh] = 15.0
# objectの存在するanchor boxのみ、x、y、w、h、conf、probを個別修正
abs_anchors = self.anchors / np.array([grid_w, grid_h])
for batch in range(batch_size):
if len(t) == 0:
continue
for truth_box in t[batch]:
truth_w = int(float(truth_box["x"]) * grid_w)
truth_h = int(float(truth_box["y"]) * grid_h)
truth_n = 0
best_iou = 0.0
for anchor_index, abs_anchor in enumerate(abs_anchors):
iou = box_iou(Box(0, 0, float(truth_box["w"]), float(truth_box["h"])), Box(0, 0, abs_anchor[0], abs_anchor[1]))
if best_iou < iou:
best_iou = iou
truth_n = anchor_index
# objectの存在するanchorについて、centerを0.5ではなく、真の座標に近づかせる。anchorのスケールを1ではなく真のスケールに近づかせる。学習スケールを1にする。
box_learning_scale[batch, truth_n, :, truth_h, truth_w] = 1.0
tx[batch, truth_n, :, truth_h, truth_w] = float(truth_box["x"]) * grid_w - truth_w
ty[batch, truth_n, :, truth_h, truth_w] = float(truth_box["y"]) * grid_h - truth_h
tw[batch, truth_n, :, truth_h, truth_w] = np.log(float(truth_box["w"]) / abs_anchors[truth_n][0])
th[batch, truth_n, :, truth_h, truth_w] = np.log(float(truth_box["h"]) / abs_anchors[truth_n][1])
tprob[batch, :, truth_n, truth_h, truth_w] = 1
tprob[batch, int(truth_box["label"]), truth_n, truth_h, truth_w] = 0
# IOUの観測
full_truth_box = Box(float(truth_box["x"]), float(truth_box["y"]), float(truth_box["w"]), float(truth_box["h"]))
#predicted_box = Box(
# (x[batch][truth_n][0][truth_h][truth_w].data.get() + truth_w) / grid_w,
# (y[batch][truth_n][0][truth_h][truth_w].data.get() + truth_h) / grid_h,
# np.exp(w[batch][truth_n][0][truth_h][truth_w].data.get()) * abs_anchors[truth_n][0],
# np.exp(h[batch][truth_n][0][truth_h][truth_w].data.get()) * abs_anchors[truth_n][1]
#)
predicted_box = Box(
(x[batch][truth_n][0][truth_h][truth_w].data + truth_w) / grid_w,
(y[batch][truth_n][0][truth_h][truth_w].data + truth_h) / grid_h,
np.exp(w[batch][truth_n][0][truth_h][truth_w].data) * abs_anchors[truth_n][0],
np.exp(h[batch][truth_n][0][truth_h][truth_w].data) * abs_anchors[truth_n][1]
)
predicted_iou = box_iou(full_truth_box, predicted_box)
tconf[batch, truth_n, :, truth_h, truth_w] = predicted_iou
#conf_learning_scale[batch, truth_n, :, truth_h, truth_w] = 10.0
# debug prints
maps = F.transpose(prob[batch], (2, 3, 1, 0)).data
print("best confidences and best conditional probability and predicted class of each grid:")
for i in range(grid_h):
for j in range(grid_w):
s = "{:2d} {:2d} {:2d} ".format(
int(conf[batch, :, :, i, j].data.max() * 100),
maps[i][j][int(maps[i][j].max(axis=1).argmax())].argmax(),
int(maps[i][j][int(maps[i][j].max(axis=1).argmax())].max()*100)
)
print s
print("best default iou: %.2f predicted iou: %.2f confidence: %.2f class: %s" % (best_iou, predicted_iou, conf[batch][truth_n][0][truth_h][truth_w].data, t[batch][0]["label"]))
print("-------------------------------")
print("seen = %d" % self.seen)
# loss計算
tx, ty, tw, th, tconf, tprob = Variable(tx), Variable(ty), Variable(tw), Variable(th), Variable(tconf), Variable(tprob)
box_learning_scale, conf_learning_scale = Variable(box_learning_scale), Variable(conf_learning_scale)
#tx.to_gpu(), ty.to_gpu(), tw.to_gpu(), th.to_gpu(), tconf.to_gpu(), tprob.to_gpu()
#box_learning_scale.to_gpu()
#conf_learning_scale.to_gpu()
x_loss = F.sum((tx - x) ** 2 * box_learning_scale) / 2
y_loss = F.sum((ty - y) ** 2 * box_learning_scale) / 2
w_loss = F.sum((tw - w) ** 2 * box_learning_scale) / 2
h_loss = F.sum((th - h) ** 2 * box_learning_scale) / 2
c_loss = F.sum((tconf - conf) ** 2 * conf_learning_scale) / 2
p_loss = F.sum((tprob - prob) ** 2) / 2
print("x_loss: %f y_loss: %f w_loss: %f h_loss: %f c_loss: %f p_loss: %f" %
(F.sum(x_loss).data, F.sum(y_loss).data, F.sum(w_loss).data, F.sum(h_loss).data, F.sum(c_loss).data, F.sum(p_loss).data)
)
loss = x_loss + y_loss + w_loss + h_loss + c_loss + p_loss
return loss
def init_anchor(self, anchors):
self.anchors = anchors
def predict(self, input_x):
output = self.predictor(input_x)
batch_size, input_channel, input_h, input_w = input_x.shape
batch_size, _, grid_h, grid_w = output.shape
x, y, w, h, conf, prob = F.split_axis(F.reshape(output, (batch_size, self.predictor.n_boxes, self.predictor.n_classes+5, grid_h, grid_w)), (1, 2, 3, 4, 5), axis=2)
x = F.sigmoid(x) # xのactivation
y = F.sigmoid(y) # yのactivation
conf = F.sigmoid(conf) # confのactivation
prob = F.transpose(prob, (0, 2, 1, 3, 4))
prob = F.softmax(prob) # probablitiyのacitivation
prob = F.transpose(prob, (0, 2, 1, 3, 4))
# x, y, w, hを絶対座標へ変換
x_shift = Variable(np.broadcast_to(np.arange(grid_w, dtype=np.float32), x.shape))
y_shift = Variable(np.broadcast_to(np.arange(grid_h, dtype=np.float32).reshape(grid_h, 1), y.shape))
w_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 0], (self.predictor.n_boxes, 1, 1, 1)), w.shape))
h_anchor = Variable(np.broadcast_to(np.reshape(np.array(self.anchors, dtype=np.float32)[:, 1], (self.predictor.n_boxes, 1, 1, 1)), h.shape))
#x_shift.to_gpu(), y_shift.to_gpu(), w_anchor.to_gpu(), h_anchor.to_gpu()
box_x = (x + x_shift) / grid_w
box_y = (y + y_shift) / grid_h
box_w = F.exp(w) * w_anchor / grid_w
box_h = F.exp(h) * h_anchor / grid_h
return box_x, box_y, box_w, box_h, conf, prob