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 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
|
from __future__ import division, print_function
import tensorflow as tf
slim = tf.contrib.slim
from utils.layer_utils import conv2d, darknet53_body, yolo_block, upsample_layer
class yolov3(object):
def __init__(self, class_num, anchors, use_label_smooth=False, use_focal_loss=False, batch_norm_decay=0.999, weight_decay=5e-4): """ yolov3 class :param class_num: 类别数目 :param anchors: anchors,一般来说是9个anchors :param use_label_smooth: 是否使用label smooth,默认为False :param use_focal_loss: 是否使用focal loss,默认为False :param batch_norm_decay: BN的衰减系数 :param weight_decay: 权重衰减系数 """ self.class_num = class_num self.anchors = anchors self.batch_norm_decay = batch_norm_decay self.use_label_smooth = use_label_smooth self.use_focal_loss = use_focal_loss self.weight_decay = weight_decay
def forward(self, inputs, is_training=False, reuse=False): """ 进行正向传播,返回的是若干特征图 :param inputs: shape: [N, height, width, channel] :param is_training: :param reuse: :return: """
self.img_size = tf.shape(inputs)[1:3]
batch_norm_params = { 'decay': self.batch_norm_decay, 'epsilon': 1e-05, 'scale': True, 'is_training': is_training, 'fused': None, }
with slim.arg_scope([slim.conv2d, slim.batch_norm], reuse=reuse): with slim.arg_scope([slim.conv2d], normalizer_fn=slim.batch_norm, normalizer_params=batch_norm_params, biases_initializer=None, activation_fn=lambda x: tf.nn.leaky_relu(x, alpha=0.1), weights_regularizer=slim.l2_regularizer(self.weight_decay)):
with tf.variable_scope('darknet53_body'): route_1, route_2, route_3 = darknet53_body(inputs)
with tf.variable_scope('yolov3_head'):
inter1, net = yolo_block(route_3, 512)
feature_map_1 = slim.conv2d(net, 3 * (5 + self.class_num), 1, stride=1, normalizer_fn=None, activation_fn=None, biases_initializer=tf.zeros_initializer()) feature_map_1 = tf.identity(feature_map_1, name='feature_map_1')
inter1 = conv2d(inter1, 256, 1) inter1 = upsample_layer(inter1, tf.shape(route_2)) concat1 = tf.concat([inter1, route_2], axis=3)
inter2, net = yolo_block(concat1, 256) feature_map_2 = slim.conv2d(net, 3 * (5 + self.class_num), 1, stride=1, normalizer_fn=None, activation_fn=None, biases_initializer=tf.zeros_initializer()) feature_map_2 = tf.identity(feature_map_2, name='feature_map_2')
inter2 = conv2d(inter2, 128, 1) inter2 = upsample_layer(inter2, tf.shape(route_1)) concat2 = tf.concat([inter2, route_1], axis=3)
_, feature_map_3 = yolo_block(concat2, 128) feature_map_3 = slim.conv2d(feature_map_3, 3 * (5 + self.class_num), 1, stride=1, normalizer_fn=None, activation_fn=None, biases_initializer=tf.zeros_initializer()) feature_map_3 = tf.identity(feature_map_3, name='feature_map_3') return feature_map_1, feature_map_2, feature_map_3
def reorg_layer(self, feature_map, anchors): ''' feature_map: a feature_map from [feature_map_1, feature_map_2, feature_map_3] returned from `forward` function anchors: shape: [3, 2] ''' """需要注意的是,我们在下面的代码中会经常涉及到height, width这两个概念,在YOLOv3中,height表示的是竖直方向, width表示的是水平方向,同样,x的方向也表示的是水平方向,y的方向是竖直方向""" grid_size = tf.shape(feature_map)[1:3]
ratio = tf.cast(self.img_size / grid_size, tf.float32)
rescaled_anchors = [(anchor[0] / ratio[1], anchor[1] / ratio[0]) for anchor in anchors]
feature_map = tf.reshape(feature_map, [-1, grid_size[0], grid_size[1], 3, 5 + self.class_num])
box_centers, box_sizes, conf_logits, prob_logits = tf.split(feature_map, [2, 2, 1, self.class_num], axis=-1)
box_centers = tf.nn.sigmoid(box_centers)
grid_x = tf.range(grid_size[1], dtype=tf.int32) grid_y = tf.range(grid_size[0], dtype=tf.int32)
grid_x, grid_y = tf.meshgrid(grid_x, grid_y) x_offset = tf.reshape(grid_x, (-1, 1)) y_offset = tf.reshape(grid_y, (-1, 1))
x_y_offset = tf.concat([x_offset, y_offset], axis=-1) x_y_offset = tf.cast(tf.reshape(x_y_offset, [grid_size[0], grid_size[1], 1, 2]), tf.float32)
box_centers = box_centers + x_y_offset
box_centers = box_centers * ratio[::-1]
box_sizes = tf.exp(box_sizes) * rescaled_anchors box_sizes = box_sizes * ratio[::-1]
boxes = tf.concat([box_centers, box_sizes], axis=-1)
return x_y_offset, boxes, conf_logits, prob_logits
def predict(self, feature_maps): ''' Receive the returned feature_maps from `forward` function, the produce the output predictions at the test stage. ''' feature_map_1, feature_map_2, feature_map_3 = feature_maps
feature_map_anchors = [(feature_map_1, self.anchors[6:9]), (feature_map_2, self.anchors[3:6]), (feature_map_3, self.anchors[0:3])]
reorg_results = [self.reorg_layer(feature_map, anchors) for (feature_map, anchors) in feature_map_anchors]
def _reshape(result): x_y_offset, boxes, conf_logits, prob_logits = result
grid_size = tf.shape(x_y_offset)[:2]
boxes = tf.reshape(boxes, [-1, grid_size[0] * grid_size[1] * 3, 4]) conf_logits = tf.reshape(conf_logits, [-1, grid_size[0] * grid_size[1] * 3, 1]) prob_logits = tf.reshape(prob_logits, [-1, grid_size[0] * grid_size[1] * 3, self.class_num]) return boxes, conf_logits, prob_logits
boxes_list, confs_list, probs_list = [], [], [] for result in reorg_results: boxes, conf_logits, prob_logits = _reshape(result)
confs = tf.sigmoid(conf_logits) probs = tf.sigmoid(prob_logits)
boxes_list.append(boxes) confs_list.append(confs) probs_list.append(probs)
boxes = tf.concat(boxes_list, axis=1) confs = tf.concat(confs_list, axis=1) probs = tf.concat(probs_list, axis=1)
center_x, center_y, width, height = tf.split(boxes, [1, 1, 1, 1], axis=-1) x_min = center_x - width / 2 y_min = center_y - height / 2 x_max = center_x + width / 2 y_max = center_y + height / 2
boxes = tf.concat([x_min, y_min, x_max, y_max], axis=-1)
return boxes, confs, probs
def loss_layer(self, feature_map_i, y_true, anchors): ''' calc loss function from a certain scale input: feature_map_i: feature maps of a certain scale. shape: [N, 13, 13, 3*(5 + num_class)] etc. y_true: y_ture from a certain scale. shape: [N, 13, 13, 3, 5 + num_class + 1] etc. anchors: shape [9, 2] '''
grid_size = tf.shape(feature_map_i)[1:3]
ratio = tf.cast(self.img_size / grid_size, tf.float32)
N = tf.cast(tf.shape(feature_map_i)[0], tf.float32)
x_y_offset, pred_boxes, pred_conf_logits, pred_prob_logits = self.reorg_layer(feature_map_i, anchors)
object_mask = y_true[..., 4:5]
valid_true_boxes = tf.boolean_mask(y_true[..., 0:4], tf.cast(object_mask[..., 0], 'bool'))
valid_true_box_xy = valid_true_boxes[:, 0:2] valid_true_box_wh = valid_true_boxes[:, 2:4]
pred_box_xy = pred_boxes[..., 0:2] pred_box_wh = pred_boxes[..., 2:4]
iou = self.broadcast_iou(valid_true_box_xy, valid_true_box_wh, pred_box_xy, pred_box_wh)
best_iou = tf.reduce_max(iou, axis=-1)
ignore_mask = tf.cast(best_iou < 0.5, tf.float32) ignore_mask = tf.expand_dims(ignore_mask, -1)
true_xy = y_true[..., 0:2] / ratio[::-1] - x_y_offset pred_xy = pred_box_xy / ratio[::-1] - x_y_offset
true_tw_th = y_true[..., 2:4] / anchors pred_tw_th = pred_box_wh / anchors true_tw_th = tf.where(condition=tf.equal(true_tw_th, 0), x=tf.ones_like(true_tw_th), y=true_tw_th) pred_tw_th = tf.where(condition=tf.equal(pred_tw_th, 0), x=tf.ones_like(pred_tw_th), y=pred_tw_th) true_tw_th = tf.log(tf.clip_by_value(true_tw_th, 1e-9, 1e9)) pred_tw_th = tf.log(tf.clip_by_value(pred_tw_th, 1e-9, 1e9))
box_loss_scale = 2. - (y_true[..., 2:3] / tf.cast(self.img_size[1], tf.float32)) * ( y_true[..., 3:4] / tf.cast(self.img_size[0], tf.float32))
mix_w = y_true[..., -1:] xy_loss = tf.reduce_sum(tf.square(true_xy - pred_xy) * object_mask * box_loss_scale * mix_w) / N wh_loss = tf.reduce_sum(tf.square(true_tw_th - pred_tw_th) * object_mask * box_loss_scale * mix_w) / N
conf_pos_mask = object_mask conf_neg_mask = (1 - object_mask) * ignore_mask conf_loss_pos = conf_pos_mask * tf.nn.sigmoid_cross_entropy_with_logits(labels=object_mask, logits=pred_conf_logits) conf_loss_neg = conf_neg_mask * tf.nn.sigmoid_cross_entropy_with_logits(labels=object_mask, logits=pred_conf_logits) conf_loss = conf_loss_pos + conf_loss_neg if self.use_focal_loss: alpha = 1.0 gamma = 2.0 focal_mask = alpha * tf.pow(tf.abs(object_mask - tf.sigmoid(pred_conf_logits)), gamma) conf_loss *= focal_mask conf_loss = tf.reduce_sum(conf_loss * mix_w) / N
if self.use_label_smooth: delta = 0.01 label_target = (1 - delta) * y_true[..., 5:-1] + delta * 1. / self.class_num else: label_target = y_true[..., 5:-1] class_loss = object_mask * tf.nn.sigmoid_cross_entropy_with_logits(labels=label_target, logits=pred_prob_logits) * mix_w class_loss = tf.reduce_sum(class_loss) / N return xy_loss, wh_loss, conf_loss, class_loss
def compute_loss(self, y_pred, y_true): ''' param: y_pred: returned feature_map list by `forward` function: [feature_map_1, feature_map_2, feature_map_3] y_true: input y_true by the tf.data pipeline '''
loss_xy, loss_wh, loss_conf, loss_class = 0., 0., 0., 0.
anchor_group = [self.anchors[6:9], self.anchors[3:6], self.anchors[0:3]]
for i in range(len(y_pred)): result = self.loss_layer(y_pred[i], y_true[i], anchor_group[i]) loss_xy += result[0] loss_wh += result[1] loss_conf += result[2] loss_class += result[3] total_loss = loss_xy + loss_wh + loss_conf + loss_class return [total_loss, loss_xy, loss_wh, loss_conf, loss_class]
def broadcast_iou(self, true_box_xy, true_box_wh, pred_box_xy, pred_box_wh): ''' maintain an efficient way to calculate the ios matrix between ground truth true boxes and the predicted boxes note: here we only care about the size match '''
pred_box_xy = tf.expand_dims(pred_box_xy, -2) pred_box_wh = tf.expand_dims(pred_box_wh, -2)
true_box_xy = tf.expand_dims(true_box_xy, 0) true_box_wh = tf.expand_dims(true_box_wh, 0)
intersect_mins = tf.maximum(pred_box_xy - pred_box_wh / 2., true_box_xy - true_box_wh / 2.) intersect_maxs = tf.minimum(pred_box_xy + pred_box_wh / 2., true_box_xy + true_box_wh / 2.) intersect_wh = tf.maximum(intersect_maxs - intersect_mins, 0.)
intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] pred_box_area = pred_box_wh[..., 0] * pred_box_wh[..., 1] true_box_area = true_box_wh[..., 0] * true_box_wh[..., 1]
iou = intersect_area / (pred_box_area + true_box_area - intersect_area + 1e-10)
return iou
|