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', normalize=True, sample_size=None):
    "\n\t:alias_main: paddle.nn.functional.ssd_loss\n\t:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss\n\t:old_api: paddle.fluid.layers.ssd_loss\n\n    **Multi-box loss layer for object detection algorithm of SSD**\n\n    This layer is to compute detection loss for SSD given the location offset\n    predictions, confidence predictions, prior boxes and ground-truth bounding\n    boxes and labels, and the type of hard example mining. The returned loss\n    is a weighted sum of the localization loss (or regression loss) and\n    confidence loss (or classification loss) by performing the following steps:\n\n    1. Find matched bounding box by bipartite matching algorithm.\n\n      1.1 Compute IOU similarity between ground-truth boxes and prior boxes.\n\n      1.2 Compute matched bounding box by bipartite matching algorithm.\n\n    2. Compute confidence for mining hard examples\n\n      2.1. Get the target label based on matched indices.\n\n      2.2. Compute confidence loss.\n\n    3. Apply hard example mining to get the negative example indices and update\n       the matched indices.\n\n    4. Assign classification and regression targets\n\n      4.1. Encoded bbox according to the prior boxes.\n\n      4.2. Assign regression targets.\n\n      4.3. Assign classification targets.\n\n    5. Compute the overall objective loss.\n\n      5.1 Compute confidence loss.\n\n      5.2 Compute localization loss.\n\n      5.3 Compute the overall weighted loss.\n\n    Args:\n        location (Variable): The location predictions are a 3D Tensor with\n            shape [N, Np, 4], N is the batch size, Np is total number of\n            predictions for each instance. 4 is the number of coordinate values,\n            the layout is [xmin, ymin, xmax, ymax].The data type is float32 or\n            float64.\n        confidence (Variable): The confidence predictions are a 3D Tensor\n            with shape [N, Np, C], N and Np are the same as they are in\n            `location`, C is the class number.The data type is float32 or\n            float64.\n        gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D\n            LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth\n            bboxes of mini-batch input.The data type is float32 or float64.\n        gt_label (Variable): The ground-truth labels are a 2D LoDTensor\n            with shape [Ng, 1].Ng is the total number of ground-truth bboxes of\n            mini-batch input, 1 is the number of class. The data type is float32\n            or float64.\n        prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].\n            Np and 4 are the same as they are in `location`. The data type is\n            float32 or float64.\n        prior_box_var (Variable): The variance of prior boxes are a 2D Tensor\n            with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`\n        background_label (int): The index of background label, 0 by default.\n        overlap_threshold (float): If match_type is 'per_prediction', use\n            'overlap_threshold' to determine the extra matching bboxes when finding             matched boxes. 0.5 by default.\n        neg_pos_ratio (float): The ratio of the negative boxes to the positive\n            boxes, used only when mining_type is 'max_negative', 3.0 by default.\n        neg_overlap (float): The negative overlap upper bound for the unmatched\n            predictions. Use only when mining_type is 'max_negative',\n            0.5 by default.\n        loc_loss_weight (float): Weight for localization loss, 1.0 by default.\n        conf_loss_weight (float): Weight for confidence loss, 1.0 by default.\n        match_type (str): The type of matching method during training, should\n            be 'bipartite' or 'per_prediction', 'per_prediction' by default.\n        mining_type (str): The hard example mining type, should be 'hard_example'\n            or 'max_negative', now only support `max_negative`.\n        normalize (bool): Whether to normalize the SSD loss by the total number\n            of output locations, True by default.\n        sample_size (int): The max sample size of negative box, used only when\n            mining_type is 'hard_example'.\n\n    Returns:\n        Variable(Tensor):  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\n        `location`.The data type is float32 or float64.\n\n    Raises:\n        ValueError: If mining_type is 'hard_example', now only support mining         type of `max_negative`.\n\n    Examples:\n\n        .. code-block:: python\n\n            import paddle.fluid as fluid\n            pb = fluid.data(\n                           name='prior_box',\n                           shape=[10, 4],\n                           dtype='float32')\n            pbv = fluid.data(\n                           name='prior_box_var',\n                           shape=[10, 4],\n                           dtype='float32')\n            loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')\n            scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')\n            gt_box = fluid.data(\n                 name='gt_box', shape=[4], lod_level=1, dtype='float32')\n            gt_label = fluid.data(\n                 name='gt_label', shape=[1], lod_level=1, dtype='float32')\n            loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)\n    "
    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
    conf_shape = nn.shape(confidence)

    def __reshape_to_2d(var):
        return nn.flatten(x=var, axis=2)
    iou = iou_similarity(x=gt_box, y=prior_box)
    (matched_indices, matched_dist) = bipartite_match(iou, match_type, overlap_threshold)
    gt_label = nn.reshape(x=gt_label, shape=(((len(gt_label.shape) - 1) * (0,)) + ((- 1), 1)))
    gt_label.stop_gradient = True
    (target_label, _) = target_assign(gt_label, matched_indices, mismatch_value=background_label)
    confidence = __reshape_to_2d(confidence)
    target_label = tensor.cast(x=target_label, dtype='int64')
    target_label = __reshape_to_2d(target_label)
    target_label.stop_gradient = True
    conf_loss = softmax_with_cross_entropy(confidence, target_label)
    actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2])
    actual_shape.stop_gradient = True
    conf_loss = nn.reshape(x=conf_loss, shape=((- 1), 0), actual_shape=actual_shape)
    conf_loss.stop_gradient = True
    neg_indices = helper.create_variable_for_type_inference(dtype='int32')
    dtype = matched_indices.dtype
    updated_matched_indices = helper.create_variable_for_type_inference(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_overlap, 'mining_type': mining_type, 'sample_size': sample_size})
    encoded_bbox = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=gt_box, code_type='encode_center_size')
    (target_bbox, target_loc_weight) = target_assign(encoded_bbox, updated_matched_indices, mismatch_value=background_label)
    (target_label, target_conf_weight) = target_assign(gt_label, updated_matched_indices, negative_indices=neg_indices, mismatch_value=background_label)
    target_label = __reshape_to_2d(target_label)
    target_label = tensor.cast(x=target_label, dtype='int64')
    conf_loss = softmax_with_cross_entropy(confidence, target_label)
    target_conf_weight = __reshape_to_2d(target_conf_weight)
    conf_loss = (conf_loss * target_conf_weight)
    target_label.stop_gradient = True
    target_conf_weight.stop_gradient = True
    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)
    target_bbox.stop_gradient = True
    target_loc_weight.stop_gradient = True
    loss = ((conf_loss_weight * conf_loss) + (loc_loss_weight * loc_loss))
    loss = nn.reshape(x=loss, shape=((- 1), 0), actual_shape=actual_shape)
    loss = nn.reduce_sum(loss, dim=1, keep_dim=True)
    if normalize:
        normalizer = nn.reduce_sum(target_loc_weight)
        loss = (loss / normalizer)
    return loss
:alias_main: paddle.nn.functional.ssd_loss
    :alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss
    :old_api: paddle.fluid.layers.ssd_loss

**Multi-box loss layer for object detection algorithm of SSD**

This layer is to compute detection loss for SSD given the location offset
predictions, confidence predictions, prior boxes and ground-truth bounding
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 bounding box by bipartite matching algorithm.

  1.1 Compute IOU similarity between ground-truth boxes and prior boxes.

  1.2 Compute matched bounding 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.2 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].The data type is float32 or
        float64.
    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.The data type is float32 or
        float64.
    gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D
        LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
        bboxes of mini-batch input.The data type is float32 or float64.
    gt_label (Variable): The ground-truth labels are a 2D LoDTensor
        with shape [Ng, 1].Ng is the total number of ground-truth bboxes of
        mini-batch input, 1 is the number of class. The data type is float32
        or float64.
    prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].
        Np and 4 are the same as they are in `location`. The data type is
        float32 or float64.
    prior_box_var (Variable): The variance of prior boxes are a 2D Tensor
        with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`
    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 default.
    neg_overlap (float): The negative overlap upper bound for the unmatched
        predictions. Use only when mining_type is 'max_negative',
        0.5 by default.
    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', 'per_prediction' by default.
    mining_type (str): The hard example mining type, should be 'hard_example'
        or 'max_negative', now only support `max_negative`.
    normalize (bool): Whether to normalize the SSD loss by the total number
        of output locations, True by default.
    sample_size (int): The max sample size of negative box, used only when
        mining_type is 'hard_example'.

Returns:
    Variable(Tensor):  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`.The data type is float32 or float64.

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

Examples:

    .. code-block:: python

        import paddle.fluid as fluid
        pb = fluid.data(
                       name='prior_box',
                       shape=[10, 4],
                       dtype='float32')
        pbv = fluid.data(
                       name='prior_box_var',
                       shape=[10, 4],
                       dtype='float32')
        loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')
        scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')
        gt_box = fluid.data(
             name='gt_box', shape=[4], lod_level=1, dtype='float32')
        gt_label = fluid.data(
             name='gt_label', shape=[1], lod_level=1, dtype='float32')
        loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)
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', normalize=True, sample_size=None):
    "\n\t:alias_main: paddle.nn.functional.ssd_loss\n\t:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss\n\t:old_api: paddle.fluid.layers.ssd_loss\n\n    **Multi-box loss layer for object detection algorithm of SSD**\n\n    This layer is to compute detection loss for SSD given the location offset\n    predictions, confidence predictions, prior boxes and ground-truth bounding\n    boxes and labels, and the type of hard example mining. The returned loss\n    is a weighted sum of the localization loss (or regression loss) and\n    confidence loss (or classification loss) by performing the following steps:\n\n    1. Find matched bounding box by bipartite matching algorithm.\n\n      1.1 Compute IOU similarity between ground-truth boxes and prior boxes.\n\n      1.2 Compute matched bounding box by bipartite matching algorithm.\n\n    2. Compute confidence for mining hard examples\n\n      2.1. Get the target label based on matched indices.\n\n      2.2. Compute confidence loss.\n\n    3. Apply hard example mining to get the negative example indices and update\n       the matched indices.\n\n    4. Assign classification and regression targets\n\n      4.1. Encoded bbox according to the prior boxes.\n\n      4.2. Assign regression targets.\n\n      4.3. Assign classification targets.\n\n    5. Compute the overall objective loss.\n\n      5.1 Compute confidence loss.\n\n      5.2 Compute localization loss.\n\n      5.3 Compute the overall weighted loss.\n\n    Args:\n        location (Variable): The location predictions are a 3D Tensor with\n            shape [N, Np, 4], N is the batch size, Np is total number of\n            predictions for each instance. 4 is the number of coordinate values,\n            the layout is [xmin, ymin, xmax, ymax].The data type is float32 or\n            float64.\n        confidence (Variable): The confidence predictions are a 3D Tensor\n            with shape [N, Np, C], N and Np are the same as they are in\n            `location`, C is the class number.The data type is float32 or\n            float64.\n        gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D\n            LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth\n            bboxes of mini-batch input.The data type is float32 or float64.\n        gt_label (Variable): The ground-truth labels are a 2D LoDTensor\n            with shape [Ng, 1].Ng is the total number of ground-truth bboxes of\n            mini-batch input, 1 is the number of class. The data type is float32\n            or float64.\n        prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].\n            Np and 4 are the same as they are in `location`. The data type is\n            float32 or float64.\n        prior_box_var (Variable): The variance of prior boxes are a 2D Tensor\n            with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`\n        background_label (int): The index of background label, 0 by default.\n        overlap_threshold (float): If match_type is 'per_prediction', use\n            'overlap_threshold' to determine the extra matching bboxes when finding             matched boxes. 0.5 by default.\n        neg_pos_ratio (float): The ratio of the negative boxes to the positive\n            boxes, used only when mining_type is 'max_negative', 3.0 by default.\n        neg_overlap (float): The negative overlap upper bound for the unmatched\n            predictions. Use only when mining_type is 'max_negative',\n            0.5 by default.\n        loc_loss_weight (float): Weight for localization loss, 1.0 by default.\n        conf_loss_weight (float): Weight for confidence loss, 1.0 by default.\n        match_type (str): The type of matching method during training, should\n            be 'bipartite' or 'per_prediction', 'per_prediction' by default.\n        mining_type (str): The hard example mining type, should be 'hard_example'\n            or 'max_negative', now only support `max_negative`.\n        normalize (bool): Whether to normalize the SSD loss by the total number\n            of output locations, True by default.\n        sample_size (int): The max sample size of negative box, used only when\n            mining_type is 'hard_example'.\n\n    Returns:\n        Variable(Tensor):  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\n        `location`.The data type is float32 or float64.\n\n    Raises:\n        ValueError: If mining_type is 'hard_example', now only support mining         type of `max_negative`.\n\n    Examples:\n\n        .. code-block:: python\n\n            import paddle.fluid as fluid\n            pb = fluid.data(\n                           name='prior_box',\n                           shape=[10, 4],\n                           dtype='float32')\n            pbv = fluid.data(\n                           name='prior_box_var',\n                           shape=[10, 4],\n                           dtype='float32')\n            loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')\n            scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')\n            gt_box = fluid.data(\n                 name='gt_box', shape=[4], lod_level=1, dtype='float32')\n            gt_label = fluid.data(\n                 name='gt_label', shape=[1], lod_level=1, dtype='float32')\n            loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)\n    "
    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
    conf_shape = nn.shape(confidence)

    def __reshape_to_2d(var):
        return nn.flatten(x=var, axis=2)
    iou = iou_similarity(x=gt_box, y=prior_box)
    (matched_indices, matched_dist) = bipartite_match(iou, match_type, overlap_threshold)
    gt_label = nn.reshape(x=gt_label, shape=(((len(gt_label.shape) - 1) * (0,)) + ((- 1), 1)))
    gt_label.stop_gradient = True
    (target_label, _) = target_assign(gt_label, matched_indices, mismatch_value=background_label)
    confidence = __reshape_to_2d(confidence)
    target_label = tensor.cast(x=target_label, dtype='int64')
    target_label = __reshape_to_2d(target_label)
    target_label.stop_gradient = True
    conf_loss = softmax_with_cross_entropy(confidence, target_label)
    actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2])
    actual_shape.stop_gradient = True
    conf_loss = nn.reshape(x=conf_loss, shape=((- 1), 0), actual_shape=actual_shape)
    conf_loss.stop_gradient = True
    neg_indices = helper.create_variable_for_type_inference(dtype='int32')
    dtype = matched_indices.dtype
    updated_matched_indices = helper.create_variable_for_type_inference(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_overlap, 'mining_type': mining_type, 'sample_size': sample_size})
    encoded_bbox = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=gt_box, code_type='encode_center_size')
    (target_bbox, target_loc_weight) = target_assign(encoded_bbox, updated_matched_indices, mismatch_value=background_label)
    (target_label, target_conf_weight) = target_assign(gt_label, updated_matched_indices, negative_indices=neg_indices, mismatch_value=background_label)
    target_label = __reshape_to_2d(target_label)
    target_label = tensor.cast(x=target_label, dtype='int64')
    conf_loss = softmax_with_cross_entropy(confidence, target_label)
    target_conf_weight = __reshape_to_2d(target_conf_weight)
    conf_loss = (conf_loss * target_conf_weight)
    target_label.stop_gradient = True
    target_conf_weight.stop_gradient = True
    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)
    target_bbox.stop_gradient = True
    target_loc_weight.stop_gradient = True
    loss = ((conf_loss_weight * conf_loss) + (loc_loss_weight * loc_loss))
    loss = nn.reshape(x=loss, shape=((- 1), 0), actual_shape=actual_shape)
    loss = nn.reduce_sum(loss, dim=1, keep_dim=True)
    if normalize:
        normalizer = nn.reduce_sum(target_loc_weight)
        loss = (loss / normalizer)
    return loss