detection.py 33.2 KB
Newer Older
1
#  Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserve.
2 3 4 5 6
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
7
#    http://www.apache.org/licenses/LICENSE-2.0
8 9 10 11 12 13 14 15 16 17
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
All layers just related to the detection neural network.
"""

18
from layer_function_generator import generate_layer_fn
19
from ..layer_helper import LayerHelper
20 21 22
import tensor
import ops
import nn
C
chengduoZH 已提交
23
import math
24

C
chengduoZH 已提交
25
__all__ = [
C
chengduoZH 已提交
26
    'prior_box',
C
chengduoZH 已提交
27
    'multi_box_head',
28 29 30 31
    'bipartite_match',
    'target_assign',
    'detection_output',
    'ssd_loss',
C
chengduoZH 已提交
32
]
33

34 35 36
__auto__ = [
    'iou_similarity',
    'box_coder',
C
chengduoZH 已提交
37
]
38

39 40 41 42 43
__all__ += __auto__

for _OP in set(__auto__):
    globals()[_OP] = generate_layer_fn(_OP)

44 45 46 47 48 49 50 51 52 53 54 55 56 57

def detection_output(scores,
                     loc,
                     prior_box,
                     prior_box_var,
                     background_label=0,
                     nms_threshold=0.3,
                     nms_top_k=400,
                     keep_top_k=200,
                     score_threshold=0.01,
                     nms_eta=1.0):
    """
    **Detection Output Layer**

C
chengduoZH 已提交
58
    This layer applies the NMS to the output of network and computes the
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
    predict bounding box location. The output's shape of this layer could
    be zero if there is no valid bounding box.

    Args:
        scores(Variable): A 3-D Tensor with shape [N, C, M] represents the
            predicted confidence predictions. N is the batch size, C is the
            class number, M is number of bounding boxes. For each category
            there are total M scores which corresponding M bounding boxes.
        loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the
            predicted locations of M bounding bboxes. N is the batch size,
            and each bounding box has four coordinate values and the layout
            is [xmin, ymin, xmax, ymax].
        prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,
            each box is represented as [xmin, ymin, xmax, ymax],
            [xmin, ymin] is the left top coordinate of the anchor box,
            if the input is image feature map, they are close to the origin
            of the coordinate system. [xmax, ymax] is the right bottom
            coordinate of the anchor box.
        prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group
            of variance.
        background_label(float): The index of background label,
            the background label will be ignored. If set to -1, then all
            categories will be considered.
        nms_threshold(float): The threshold to be used in NMS.
        nms_top_k(int): Maximum number of detections to be kept according
            to the confidences aftern the filtering detections based on
            score_threshold.
        keep_top_k(int): Number of total bboxes to be kept per image after
            NMS step. -1 means keeping all bboxes after NMS step.
        score_threshold(float): Threshold to filter out bounding boxes with
            low confidence score. If not provided, consider all boxes.
        nms_eta(float): The parameter for adaptive NMS.

    Returns:
        The detected bounding boxes which are a Tensor.

    Examples:
        .. code-block:: python

        pb = layers.data(name='prior_box', shape=[10, 4],
                         append_batch_size=False, dtype='float32')
        pbv = layers.data(name='prior_box_var', shape=[10, 4],
                          append_batch_size=False, dtype='float32')
        loc = layers.data(name='target_box', shape=[21, 4],
                          append_batch_size=False, dtype='float32')
        scores = layers.data(name='scores', shape=[2, 21, 10],
                          append_batch_size=False, dtype='float32')
        nmsed_outs = fluid.layers.detection_output(scores=scores,
                                       loc=loc,
                                       prior_box=pb,
                                       prior_box_var=pbv)
    """

    helper = LayerHelper("detection_output", **locals())
113 114 115 116 117
    decoded_box = box_coder(
        prior_box=prior_box,
        prior_box_var=prior_box_var,
        target_box=loc,
        code_type='decode_center_size')
118

119
    nmsed_outs = helper.create_tmp_variable(dtype=decoded_box.dtype)
120 121 122 123 124 125 126 127 128 129 130 131 132 133
    helper.append_op(
        type="multiclass_nms",
        inputs={'Scores': scores,
                'BBoxes': decoded_box},
        outputs={'Out': nmsed_outs},
        attrs={
            'background_label': 0,
            'nms_threshold': nms_threshold,
            'nms_top_k': nms_top_k,
            'keep_top_k': keep_top_k,
            'score_threshold': score_threshold,
            'nms_eta': 1.0
        })
    return nmsed_outs
C
chengduoZH 已提交
134 135


C
chengduoZH 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
def prior_box(inputs,
              image,
              min_ratio,
              max_ratio,
              aspect_ratios,
              base_size,
              steps=None,
              step_w=None,
              step_h=None,
              offset=0.5,
              variance=[0.1, 0.1, 0.1, 0.1],
              flip=False,
              clip=False,
              min_sizes=None,
              max_sizes=None,
              name=None):
C
chengduoZH 已提交
152 153 154
    """
    **Prior_boxes**

155 156 157 158
    Generate prior boxes for SSD(Single Shot MultiBox Detector)
    algorithm. The details of this algorithm, please refer the
    section 2.2 of SSD paper (SSD: Single Shot MultiBox Detector)
    <https://arxiv.org/abs/1512.02325>`_ .
C
chengduoZH 已提交
159

C
chengduoZH 已提交
160
    Args:
161
       inputs(list|tuple): The list of input Variables, the format
162 163 164
            of all Variables is NCHW.
       image(Variable): The input image data of PriorBoxOp,
            the layout is NCHW.
C
chengduoZH 已提交
165 166
       min_ratio(int): the min ratio of generated prior boxes.
       max_ratio(int): the max ratio of generated prior boxes.
167
       aspect_ratios(list|tuple): the aspect ratios of generated prior
168 169 170
            boxes. The length of input and aspect_ratios must be equal.
       base_size(int): the base_size is used to get min_size
            and max_size according to min_ratio and max_ratio.
171
       step_w(list|tuple|None): Prior boxes step
172 173
            across width. If step_w[i] == 0.0, the prior boxes step
            across width of the inputs[i] will be automatically calculated.
174
       step_h(list|tuple|None): Prior boxes step
175 176
            across height, If step_h[i] == 0.0, the prior boxes
            step across height of the inputs[i] will be automatically calculated.
C
chengduoZH 已提交
177
       offset(float, optional, default=0.5): Prior boxes center offset.
178
       variance(list|tuple|[0.1, 0.1, 0.1, 0.1]): the variances
C
chengduoZH 已提交
179
            to be encoded in prior boxes.
180
       flip(bool|False): Whether to flip
181 182 183
            aspect ratios.
       clip(bool, optional, default=False): Whether to clip
            out-of-boundary boxes.
184
       min_sizes(list|tuple|None): If `len(inputs) <=2`,
185 186
            min_sizes must be set up, and the length of min_sizes
            should equal to the length of inputs.
187
       max_sizes(list|tuple|None): If `len(inputs) <=2`,
188 189
            max_sizes must be set up, and the length of min_sizes
            should equal to the length of inputs.
190
       name(str|None): Name of the prior box layer.
C
chengduoZH 已提交
191

C
chengduoZH 已提交
192
    Returns:
193
        boxes(Variable): the output prior boxes of PriorBox.
194 195
             The layout is [num_priors, 4]. num_priors is the total
             box count of each position of inputs.
196
        Variances(Variable): the expanded variances of PriorBox.
197 198
             The layout is [num_priors, 4]. num_priors is the total
             box count of each position of inputs
C
chengduoZH 已提交
199

C
chengduoZH 已提交
200 201
    Examples:
        .. code-block:: python
C
chengduoZH 已提交
202

C
chengduoZH 已提交
203
          prior_box(
C
chengduoZH 已提交
204 205 206 207 208
             inputs = [conv1, conv2, conv3, conv4, conv5, conv6],
             image = data,
             min_ratio = 20, # 0.20
             max_ratio = 90, # 0.90
             offset = 0.5,
C
chengduoZH 已提交
209
             base_size = 300,
C
chengduoZH 已提交
210
             variance = [0.1,0.1,0.1,0.1],
C
chengduoZH 已提交
211
             aspect_ratios = [[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
C
chengduoZH 已提交
212 213 214
             flip=True,
             clip=True)
    """
C
chengduoZH 已提交
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

    def _prior_box_(input,
                    image,
                    min_sizes,
                    max_sizes,
                    aspect_ratios,
                    variance,
                    flip=False,
                    clip=False,
                    step_w=0.0,
                    step_h=0.0,
                    offset=0.5,
                    name=None):
        helper = LayerHelper("prior_box", **locals())
        dtype = helper.input_dtype()

        box = helper.create_tmp_variable(dtype)
        var = helper.create_tmp_variable(dtype)
        helper.append_op(
            type="prior_box",
            inputs={"Input": input,
                    "Image": image},
            outputs={"Boxes": box,
                     "Variances": var},
            attrs={
                'min_sizes': min_sizes,
                'max_sizes': max_sizes,
                'aspect_ratios': aspect_ratios,
                'variances': variance,
                'flip': flip,
                'clip': clip,
                'step_w': step_w,
                'step_h': step_h,
                'offset': offset
            })
        return box, var

    def _reshape_with_axis_(input, axis=1):
        if not (axis > 0 and axis < len(input.shape)):
254 255 256 257 258
            raise ValueError("The axis should be smaller than "
                             "the arity of input and bigger than 0.")
        new_shape = [
            -1, reduce(lambda x, y: x * y, input.shape[axis:len(input.shape)])
        ]
259
        out = ops.reshape(x=input, shape=new_shape)
C
chengduoZH 已提交
260 261
        return out

262 263 264 265 266 267 268 269 270 271
    def _is_list_or_tuple_(data):
        return (isinstance(data, list) or isinstance(data, tuple))

    def _is_list_or_tuple_and_equal(data, length, err_info):
        if not (_is_list_or_tuple_(data) and len(data) == length):
            raise ValueError(err_info)

    if not _is_list_or_tuple_(inputs):
        raise ValueError('inputs should be a list or tuple.')

C
chengduoZH 已提交
272 273
    num_layer = len(inputs)

C
chengduoZH 已提交
274 275 276 277 278 279
    if num_layer <= 2:
        assert min_sizes is not None and max_sizes is not None
        assert len(min_sizes) == num_layer and len(max_sizes) == num_layer
    else:
        min_sizes = []
        max_sizes = []
C
chengduoZH 已提交
280 281 282 283 284 285 286
        step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
        for ratio in xrange(min_ratio, max_ratio + 1, step):
            min_sizes.append(base_size * ratio / 100.)
            max_sizes.append(base_size * (ratio + step) / 100.)
        min_sizes = [base_size * .10] + min_sizes
        max_sizes = [base_size * .20] + max_sizes

C
chengduoZH 已提交
287
    if aspect_ratios:
288 289
        _is_list_or_tuple_and_equal(
            aspect_ratios, num_layer,
C
chengduoZH 已提交
290
            'aspect_ratios should be list or tuple, and the length of inputs '
291
            'and aspect_ratios should be the same.')
C
chengduoZH 已提交
292
    if step_h:
293 294
        _is_list_or_tuple_and_equal(
            step_h, num_layer,
C
chengduoZH 已提交
295
            'step_h should be list or tuple, and the length of inputs and '
296
            'step_h should be the same.')
C
chengduoZH 已提交
297
    if step_w:
298 299
        _is_list_or_tuple_and_equal(
            step_w, num_layer,
C
chengduoZH 已提交
300
            'step_w should be list or tuple, and the length of inputs and '
301
            'step_w should be the same.')
C
chengduoZH 已提交
302
    if steps:
303 304
        _is_list_or_tuple_and_equal(
            steps, num_layer,
C
chengduoZH 已提交
305
            'steps should be list or tuple, and the length of inputs and '
306
            'step_w should be the same.')
C
chengduoZH 已提交
307 308 309 310 311 312 313 314 315
        step_w = steps
        step_h = steps

    box_results = []
    var_results = []
    for i, input in enumerate(inputs):
        min_size = min_sizes[i]
        max_size = max_sizes[i]
        aspect_ratio = []
316
        if not _is_list_or_tuple_(min_size):
C
chengduoZH 已提交
317
            min_size = [min_size]
318
        if not _is_list_or_tuple_(max_size):
C
chengduoZH 已提交
319 320 321
            max_size = [max_size]
        if aspect_ratios:
            aspect_ratio = aspect_ratios[i]
322
            if not _is_list_or_tuple_(aspect_ratio):
C
chengduoZH 已提交
323 324
                aspect_ratio = [aspect_ratio]

C
chengduoZH 已提交
325 326 327 328
        box, var = _prior_box_(input, image, min_size, max_size, aspect_ratio,
                               variance, flip, clip, step_w[i]
                               if step_w else 0.0, step_h[i]
                               if step_w else 0.0, offset)
C
chengduoZH 已提交
329 330 331 332 333 334 335 336 337 338 339

        box_results.append(box)
        var_results.append(var)

    if len(box_results) == 1:
        box = box_results[0]
        var = var_results[0]
    else:
        reshaped_boxes = []
        reshaped_vars = []
        for i in range(len(box_results)):
C
chengduoZH 已提交
340 341
            reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3))
            reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3))
C
chengduoZH 已提交
342

343 344
        box = tensor.concat(reshaped_boxes)
        var = tensor.concat(reshaped_vars)
C
chengduoZH 已提交
345 346

    return box, var
C
chengduoZH 已提交
347 348


349 350 351 352 353 354 355 356 357 358 359
def bipartite_match(dist_matrix, name=None):
    """
    **Bipartite matchint operator**

    This operator is a greedy bipartite matching algorithm, which is used to
    obtain the matching with the maximum distance based on the input
    distance matrix. For input 2D matrix, the bipartite matching algorithm can
    find the matched column for each row, also can find the matched row for
    each column. And this operator only calculate matched indices from column
    to row. For each instance, the number of matched indices is the number of
    of columns of the input ditance matrix.
C
chengduoZH 已提交
360

361 362 363 364 365
    There are two outputs to save matched indices and distance.
    A simple description, this algothrim matched the best (maximum distance)
    row entity to the column entity and the matched indices are not duplicated
    in each row of ColToRowMatchIndices. If the column entity is not matched
    any row entity, set -1 in ColToRowMatchIndices.
C
chengduoZH 已提交
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
    Please note that the input DistMat can be LoDTensor (with LoD) or Tensor.
    If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.
    If Tensor, the height of ColToRowMatchIndices is 1.

    Args:
        dist_matrix(Variable): This input is a 2-D LoDTensor with shape
            [K, M]. It is pair-wise distance matrix between the entities
            represented by each row and each column. For example, assumed one
            entity is A with shape [K], another entity is B with shape [M]. The
            dist_matirx[i][j] is the distance between A[i] and B[j]. The bigger
            the distance is, the better macthing the pairs are. Please note,
            This tensor can contain LoD information to represent a batch of
            inputs. One instance of this batch can contain different numbers of
            entities.
    Returns:
        match_indices(Variable): A 2-D Tensor with shape [N, M] in int type.
            N is the batch size. If match_indices[i][j] is -1, it
            means B[j] does not match any entity in i-th instance.
            Otherwise, it means B[j] is matched to row
            match_indices[i][j] in i-th instance. The row number of
            i-th instance is saved in match_indices[i][j].
        match_distance(Variable): A 2-D Tensor with shape [N, M] in float type.
            N is batch size. If match_indices[i][j] is -1,
            match_distance[i][j] is also -1.0. Otherwise, assumed
            match_distance[i][j] = d, and the row offsets of each instance
            are called LoD. Then match_distance[i][j] = dist_matrix[d+LoD[i]][j].
    """
    helper = LayerHelper('bipartite_match', **locals())
    match_indices = helper.create_tmp_variable(dtype='int32')
    match_distance = helper.create_tmp_variable(dtype=dist_matrix.dtype)
    helper.append_op(
        type='bipartite_match',
        inputs={'DistMat': dist_matrix},
        outputs={
            'ColToRowMatchIndices': match_indices,
            'ColToRowMatchDist': match_distance
        })
    return match_indices, match_distance


def target_assign(input,
                  matched_indices,
                  negative_indices=None,
                  mismatch_value=None,
                  name=None):
    """
    **Target assigner operator**

    This operator can be, for given the target bounding boxes or labels,
    to assign classification and regression targets to each prediction as well as
    weights to prediction. The weights is used to specify which prediction would
    not contribute to training loss.
C
chengduoZH 已提交
419

420 421 422 423 424
    For each instance, the output `out` and`out_weight` are assigned based on
    `match_indices` and `negative_indices`.
    Assumed that the row offset for each instance in `input` is called lod,
    this operator assigns classification/regression targets by performing the
    following steps:
C
chengduoZH 已提交
425

426
    1. Assigning all outpts based on `match_indices`:
C
chengduoZH 已提交
427

428
    If id = match_indices[i][j] > 0,
C
chengduoZH 已提交
429

430 431
        out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]
        out_weight[i][j] = 1.
C
chengduoZH 已提交
432 433 434

    Otherwise,

435 436
        out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}
        out_weight[i][j] = 0.
C
chengduoZH 已提交
437

438
    2. Assigning out_weight based on `neg_indices` if `neg_indices` is provided:
C
chengduoZH 已提交
439

440 441
    Assumed that the row offset for each instance in `neg_indices` is called neg_lod,
    for i-th instance and each `id` of neg_indices in this instance:
C
chengduoZH 已提交
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 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
        out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
        out_weight[i][id] = 1.0

    Args:
       inputs (Variable): This input is a 3D LoDTensor with shape [M, P, K].
       matched_indices (Variable): Tensor<int>), The input matched indices
           is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,
           the j-th entity of column is not matched to any entity of row in
           i-th instance.
       negative_indices (Variable): The input negative example indices are
           an optional input with shape [Neg, 1] and int32 type, where Neg is
           the total number of negative example indices.
       mismatch_value (float32): Fill this value to the mismatched location.

    Returns:
       out (Variable): The output is a 3D Tensor with shape [N, P, K],
           N and P is the same as they are in `neg_indices`, K is the
           same as it in input of X. If `match_indices[i][j]`.
       out_weight (Variable): The weight for output with the shape of [N, P, 1].
    """
    helper = LayerHelper('target_assign', **locals())
    out = helper.create_tmp_variable(dtype=input.dtype)
    out_weight = helper.create_tmp_variable(dtype='float32')
    helper.append_op(
        type='target_assign',
        inputs={
            'X': input,
            'MatchIndices': matched_indices,
            'NegIndices': negative_indices
        },
        outputs={'Out': out,
                 'OutWeight': out_weight},
        attrs={'mismatch_value': mismatch_value})
    return out, out_weight


def ssd_loss(location,
             confidence,
             gt_box,
             gt_label,
             prior_box,
             prior_box_var=None,
             background_label=0,
             overlap_threshold=0.5,
             neg_pos_ratio=3.0,
             neg_overlap=0.5,
             loc_loss_weight=1.0,
             conf_loss_weight=1.0,
             match_type='per_prediction',
             mining_type='max_negative',
             sample_size=None):
    """
    **Multi-box loss layer for object dection algorithm of SSD**

    This layer is to compute dection loss for SSD given the location offset
    predictions, confidence predictions, prior boxes and ground-truth boudding
    boxes and labels, and the type of hard example mining. The returned loss
    is a weighted sum of the localization loss (or regression loss) and
    confidence loss (or classification loss) by performing the following steps:

    1. Find matched boundding box by bipartite matching algorithm.
      1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
      1.2 Compute matched boundding box by bipartite matching algorithm.
    2. Compute confidence for mining hard examples
      2.1. Get the target label based on matched indices.
      2.2. Compute confidence loss.
    3. Apply hard example mining to get the negative example indices and update
       the matched indices.
    4. Assign classification and regression targets
      4.1. Encoded bbox according to the prior boxes.
      4.2. Assign regression targets.
      4.3. Assign classification targets.
    5. Compute the overall objective loss.
      5.1 Compute confidence loss.
      5.1 Compute localization loss.
      5.3 Compute the overall weighted loss.

    Args:
        location (Variable): The location predictions are a 3D Tensor with
            shape [N, Np, 4], N is the batch size, Np is total number of
            predictions for each instance. 4 is the number of coordinate values,
            the layout is [xmin, ymin, xmax, ymax].
        confidence (Variable): The confidence predictions are a 3D Tensor
            with shape [N, Np, C], N and Np are the same as they are in
            `location`, C is the class number.
        gt_box (Variable): The ground-truth boudding boxes (bboxes) are a 2D
            LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
            bboxes of mini-batch input.
        gt_label (Variable): The ground-truth labels are a 2D LoDTensor
            with shape [Ng, 1].
        prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].
        prior_box_var (Variable): The variance of prior boxes are a 2D Tensor
            with shape [Np, 4].
        background_label (int): The index of background label, 0 by default.
        overlap_threshold (float): If match_type is 'per_prediction', use
            `overlap_threshold` to determine the extra matching bboxes when
             finding matched boxes. 0.5 by default.
        neg_pos_ratio (float): The ratio of the negative boxes to the positive
            boxes, used only when mining_type is max_negative, 3.0 by defalut.
        neg_overlap (float): The negative overlap upper bound for the unmatched
            predictions. Use only when mining_type is max_negative,
            0.5 by default.
        sample_size (int): The max sample size of negative box, used only when
            mining_type is hard_example.
        loc_loss_weight (float): Weight for localization loss, 1.0 by default.
        conf_loss_weight (float): Weight for confidence loss, 1.0 by default.
        match_type (str): The type of matching method during training, should
            be 'bipartite' or 'per_prediction'.
        mining_type (str): The hard example mining type, should be 'hard_example'
            or 'max_negative', now only support `max_negative`.

    Returns:
        Variable: The weighted sum of the localization loss and confidence loss,
            with shape [N * Np, 1], N and Np are the same as they are
            in `location`.

    Raises:
        ValueError: If mining_type is 'hard_example', now only support
            mining type of `max_negative`.

    Examples:
        .. code-block:: python

            pb = layers.data(
                name='prior_box',
                shape=[10, 4],
                append_batch_size=False,
                dtype='float32')
            pbv = layers.data(
                name='prior_box_var',
                shape=[10, 4],
                append_batch_size=False,
                dtype='float32')
            loc = layers.data(name='target_box', shape=[10, 4], dtype='float32')
            scores = layers.data(name='scores', shape=[10, 21], dtype='float32')
            gt_box = layers.data(
                name='gt_box', shape=[4], lod_level=1, dtype='float32')
            gt_label = layers.data(
                name='gt_label', shape=[1], lod_level=1, dtype='float32')
            loss = layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)
    """

    helper = LayerHelper('ssd_loss', **locals())
    if mining_type != 'max_negative':
        raise ValueError("Only support mining_type == max_negative now.")

    num, num_prior, num_class = confidence.shape

    def __reshape_to_2d(var):
        return ops.reshape(x=var, shape=[-1, var.shape[-1]])

    # 1. Find matched boundding box by prior box.
    #   1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
    iou = iou_similarity(x=gt_box, y=prior_box)
    #   1.2 Compute matched boundding box by bipartite matching algorithm.
    matched_indices, matched_dist = bipartite_match(iou)

    # 2. Compute confidence for mining hard examples
    # 2.1. Get the target label based on matched indices
    gt_label = ops.reshape(x=gt_label, shape=gt_label.shape + (1, ))
    target_label, _ = target_assign(
        gt_label, matched_indices, mismatch_value=background_label)
    # 2.2. Compute confidence loss.
    # Reshape confidence to 2D tensor.
    confidence = __reshape_to_2d(confidence)
    target_label = tensor.cast(x=target_label, dtype='int64')
    target_label = __reshape_to_2d(target_label)
    conf_loss = nn.softmax_with_cross_entropy(confidence, target_label)

    # 3. Mining hard examples
    conf_loss = ops.reshape(x=conf_loss, shape=(num, num_prior))
    neg_indices = helper.create_tmp_variable(dtype='int32')
    dtype = matched_indices.dtype
    updated_matched_indices = helper.create_tmp_variable(dtype=dtype)
    helper.append_op(
        type='mine_hard_examples',
        inputs={
            'ClsLoss': conf_loss,
            'LocLoss': None,
            'MatchIndices': matched_indices,
            'MatchDist': matched_dist,
        },
        outputs={
            'NegIndices': neg_indices,
            'UpdatedMatchIndices': updated_matched_indices
        },
        attrs={
            'neg_pos_ratio': neg_pos_ratio,
            'neg_dist_threshold': neg_pos_ratio,
            'mining_type': mining_type,
            'sample_size': sample_size,
        })

    # 4. Assign classification and regression targets
    # 4.1. Encoded bbox according to the prior boxes.
    encoded_bbox = box_coder(
        prior_box=prior_box,
        prior_box_var=prior_box_var,
        target_box=gt_box,
        code_type='encode_center_size')
    # 4.2. Assign regression targets
    target_bbox, target_loc_weight = target_assign(
        encoded_bbox, updated_matched_indices, mismatch_value=background_label)
    # 4.3. Assign classification targets
    target_label, target_conf_weight = target_assign(
        gt_label,
        updated_matched_indices,
        negative_indices=neg_indices,
        mismatch_value=background_label)

    # 5. Compute loss.
    # 5.1 Compute confidence loss.
    target_label = __reshape_to_2d(target_label)
    target_label = tensor.cast(x=target_label, dtype='int64')
    conf_loss = nn.softmax_with_cross_entropy(confidence, target_label)
    target_conf_weight = __reshape_to_2d(target_conf_weight)
    conf_loss = conf_loss * target_conf_weight

    # 5.2 Compute regression loss.
    location = __reshape_to_2d(location)
    target_bbox = __reshape_to_2d(target_bbox)

    loc_loss = nn.smooth_l1(location, target_bbox)
    target_loc_weight = __reshape_to_2d(target_loc_weight)
    loc_loss = loc_loss * target_loc_weight

    # 5.3 Compute overall weighted loss.
    loss = conf_loss_weight * conf_loss + loc_loss_weight * loc_loss
    return loss
C
chengduoZH 已提交
672 673


C
chengduoZH 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686
def multi_box_head(inputs,
                   num_classes,
                   min_sizes=None,
                   max_sizes=None,
                   min_ratio=None,
                   max_ratio=None,
                   aspect_ratios=None,
                   flip=False,
                   share_location=True,
                   kernel_size=1,
                   pad=1,
                   stride=1,
                   use_batchnorm=False,
687
                   base_size=None):
C
chengduoZH 已提交
688 689 690
    """
    **Multi Box Head**

691 692 693 694
    Generate prior boxes' location and confidence for SSD(Single
    Shot MultiBox Detector)algorithm. The details of this algorithm,
    please refer the section 2.1 of SSD paper (SSD: Single Shot
    MultiBox Detector)<https://arxiv.org/abs/1512.02325>`_ .
C
chengduoZH 已提交
695 696

    Args:
697
       inputs(list|tuple): The list of input Variables, the format
C
chengduoZH 已提交
698
            of all Variables is NCHW.
699 700 701
       num_classes(int): The number of classes.
       min_sizes(list|tuple|None): The number of
            min_sizes is used to compute the number of predicted box.
C
chengduoZH 已提交
702 703
            If the min_size is None, it will be computed according
            to min_ratio and max_ratio.
704 705 706
       max_sizes(list|tuple|None): The number of max_sizes
            is used to compute the the number of predicted box.
       min_ratio(int|None): If the min_sizes is None, min_ratio and max_ratio
C
chengduoZH 已提交
707
            will be used to compute the min_sizes and max_sizes.
708
       max_ratio(int|None): If the min_sizes is None, max_ratio and min_ratio
C
chengduoZH 已提交
709
            will be used to compute the min_sizes and max_sizes.
710
       aspect_ratios(list|tuple): The number of the aspect ratios is used to
C
chengduoZH 已提交
711 712 713
            compute the number of prior box.
       base_size(int): the base_size is used to get min_size
            and max_size according to min_ratio and max_ratio.
714
       flip(bool|False): Whether to flip
C
chengduoZH 已提交
715
            aspect ratios.
716
       name(str|None): Name of the prior box layer.
C
chengduoZH 已提交
717 718 719

    Returns:

720 721 722 723 724 725
        mbox_loc(list): The predicted boxes' location of the inputs.
             The layout of each element is [N, H, W, Priors]. Priors
             is the number of predicted boxof each position of each input.
        mbox_conf(list): The predicted boxes' confidence of the inputs.
             The layout of each element is [N, H, W, Priors]. Priors
             is the number of predicted box of each position of each input.
C
chengduoZH 已提交
726 727 728 729

    Examples:
        .. code-block:: python

C
chengduoZH 已提交
730 731 732 733 734 735 736 737
            mbox_locs, mbox_confs = detection.multi_box_head(
                inputs=[conv1, conv2, conv3, conv4, conv5, conv5],
                num_classes=21,
                min_ratio=20,
                max_ratio=90,
                aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],
                base_size=300,
                flip=True)
C
chengduoZH 已提交
738 739
    """

740 741 742
    def _is_equal_(len1, len2, err_info):
        if not (len1 == len2):
            raise ValueError(err_info)
743

744 745
    def _is_list_or_tuple_(data):
        return (isinstance(data, list) or isinstance(data, tuple))
746

747 748
    if not _is_list_or_tuple_(inputs):
        raise ValueError('inputs should be a list or tuple.')
C
chengduoZH 已提交
749 750

    if min_sizes is not None:
751 752 753 754
        _is_equal_(
            len(inputs),
            len(min_sizes), 'the length of min_sizes '
            'and inputs should be equal.')
C
chengduoZH 已提交
755 756

    if max_sizes is not None:
757 758 759 760
        _is_equal_(
            len(inputs),
            len(max_sizes), 'the length of max_sizes '
            'and inputs should be equal.')
C
chengduoZH 已提交
761 762

    if aspect_ratios is not None:
763 764 765 766
        _is_equal_(
            len(inputs),
            len(aspect_ratios), 'the length of aspect_ratios '
            'and inputs should be equal.')
C
chengduoZH 已提交
767 768

    if min_sizes is None:
C
chengduoZH 已提交
769 770 771 772 773 774
        # If min_sizes is None, min_sizes and max_sizes
        #  will be set according to max_ratio and min_ratio.
        num_layer = len(inputs)
        assert max_ratio is not None and min_ratio is not None,\
            'max_ratio and min_ratio must be not None.'
        assert num_layer >= 3, 'The length of the input data is at least three.'
C
chengduoZH 已提交
775 776 777 778 779 780 781 782 783 784 785 786 787
        min_sizes = []
        max_sizes = []
        step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))
        for ratio in xrange(min_ratio, max_ratio + 1, step):
            min_sizes.append(base_size * ratio / 100.)
            max_sizes.append(base_size * (ratio + step) / 100.)
        min_sizes = [base_size * .10] + min_sizes
        max_sizes = [base_size * .20] + max_sizes

    mbox_locs = []
    mbox_confs = []
    for i, input in enumerate(inputs):
        min_size = min_sizes[i]
788
        if not _is_list_or_tuple_(min_size):
C
chengduoZH 已提交
789 790 791 792 793
            min_size = [min_size]

        max_size = []
        if max_sizes is not None:
            max_size = max_sizes[i]
794
            if not _is_list_or_tuple_(max_size):
C
chengduoZH 已提交
795
                max_size = [max_size]
796 797 798 799
            _is_equal_(
                len(max_size),
                len(min_size),
                'the length of max_size and min_size should be equal.')
C
chengduoZH 已提交
800 801 802 803

        aspect_ratio = []
        if aspect_ratios is not None:
            aspect_ratio = aspect_ratios[i]
804
            if not _is_list_or_tuple_(aspect_ratio):
C
chengduoZH 已提交
805 806
                aspect_ratio = [aspect_ratio]

C
chengduoZH 已提交
807
        # get the number of prior box on each location
C
chengduoZH 已提交
808 809
        num_priors_per_location = 0
        if max_sizes is not None:
C
chengduoZH 已提交
810 811 812
            num_priors_per_location = len(min_size) + \
                                      len(aspect_ratio) * len(min_size) +\
                                      len(max_size)
C
chengduoZH 已提交
813
        else:
C
chengduoZH 已提交
814 815
            num_priors_per_location = len(min_size) +\
                                      len(aspect_ratio) * len(min_size)
C
chengduoZH 已提交
816 817 818
        if flip:
            num_priors_per_location += len(aspect_ratio) * len(min_size)

C
chengduoZH 已提交
819
        # get mbox_loc
C
chengduoZH 已提交
820 821 822 823
        num_loc_output = num_priors_per_location * 4
        if share_location:
            num_loc_output *= num_classes

824
        mbox_loc = nn.conv2d(
C
chengduoZH 已提交
825
            input=input,
826 827 828 829 830
            num_filters=num_loc_output,
            filter_size=kernel_size,
            padding=pad,
            stride=stride)

831
        mbox_loc = nn.transpose(mbox_loc, perm=[0, 2, 3, 1])
C
chengduoZH 已提交
832 833
        mbox_locs.append(mbox_loc)

C
chengduoZH 已提交
834
        # get conf_loc
C
chengduoZH 已提交
835
        num_conf_output = num_priors_per_location * num_classes
836
        conf_loc = nn.conv2d(
C
chengduoZH 已提交
837
            input=input,
838 839 840 841
            num_filters=num_conf_output,
            filter_size=kernel_size,
            padding=pad,
            stride=stride)
842
        conf_loc = nn.transpose(conf_loc, perm=[0, 2, 3, 1])
C
chengduoZH 已提交
843 844 845
        mbox_confs.append(conf_loc)

    return mbox_locs, mbox_confs