detection¶
anchor_generator¶

paddle.fluid.layers.
anchor_generator
(input, anchor_sizes=None, aspect_ratios=None, variance=[0.1, 0.1, 0.2, 0.2], stride=None, offset=0.5, name=None)[source] Anchor generator operator
Generate anchors for Faster RCNN algorithm. Each position of the input produce N anchors, N = size(anchor_sizes) * size(aspect_ratios). The order of generated anchors is firstly aspect_ratios loop then anchor_sizes loop.
 Parameters
input (Variable) – 4D Tensor with shape [N,C,H,W]. The input feature map.
anchor_sizes (float32listtuple, optional) – The anchor sizes of generated anchors, given in absolute pixels e.g. [64., 128., 256., 512.]. For instance, the anchor size of 64 means the area of this anchor equals to 64**2. None by default.
aspect_ratios (float32listtuple, optional) – The height / width ratios of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.
variance (listtuple, optional) – The variances to be used in box regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by default.
stride (listtuple, optional) – The anchors stride across width and height. The data type is float32. e.g. [16.0, 16.0]. None by default.
offset (float32, optional) – Prior boxes center offset. 0.5 by default.
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4]. H is the height of input, W is the width of input, num_anchors is the box count of each position. Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.
Variances(Variable): The expanded variances of anchors with a layout of [H, W, num_priors, 4]. H is the height of input, W is the width of input num_anchors is the box count of each position. Each variance is in (xcenter, ycenter, w, h) format.
 Return type
Tuple
Examples
import paddle.fluid as fluid conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32') anchor, var = fluid.layers.anchor_generator( input=conv1, anchor_sizes=[64, 128, 256, 512], aspect_ratios=[0.5, 1.0, 2.0], variance=[0.1, 0.1, 0.2, 0.2], stride=[16.0, 16.0], offset=0.5)
bipartite_match¶

paddle.fluid.layers.
bipartite_match
(dist_matrix, match_type=None, dist_threshold=None, name=None)[source] This operator implements 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 (matched means the largest distance), 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 column number of the input distance matrix. The OP only supports CPU.
There are two outputs, matched indices and distance. A simple description, this algorithm 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.
NOTE: 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.
NOTE: This API is a very low level API. It is used by
ssd_loss
layer. Please consider to usessd_loss
instead. Parameters
dist_matrix (Variable) – This input is a 2D LoDTensor with shape [K, M]. The data type is float32 or float64. It is pairwise 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_matrix[i][j] is the distance between A[i] and B[j]. The bigger the distance is, the better matching the pairs are. NOTE: This tensor can contain LoD information to represent a batch of inputs. One instance of this batch can contain different numbers of entities.
match_type (str, optional) – The type of matching method, should be ‘bipartite’ or ‘per_prediction’. None (‘bipartite’) by default.
dist_threshold (float32, optional) – If match_type is ‘per_prediction’, this threshold is to determine the extra matching bboxes based on the maximum distance, 0.5 by default.
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
matched_indices(Variable): A 2D Tensor with shape [N, M]. The data type is int32. N is the batch size. If match_indices[i][j] is 1, it means B[j] does not match any entity in ith instance. Otherwise, it means B[j] is matched to row match_indices[i][j] in ith instance. The row number of ith instance is saved in match_indices[i][j].
matched_distance(Variable): A 2D Tensor with shape [N, M]. The data type is float32. 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].
 Return type
Tuple
Examples
>>> import paddle.fluid as fluid >>> x = fluid.data(name='x', shape=[None, 4], dtype='float32') >>> y = fluid.data(name='y', shape=[None, 4], dtype='float32') >>> iou = fluid.layers.iou_similarity(x=x, y=y) >>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou)
box_clip¶

paddle.fluid.layers.
box_clip
(input, im_info, name=None)[source] Clip the box into the size given by im_info For each input box, The formula is given as follows:
xmin = max(min(xmin, im_w  1), 0) ymin = max(min(ymin, im_h  1), 0) xmax = max(min(xmax, im_w  1), 0) ymax = max(min(ymax, im_h  1), 0)
where im_w and im_h are computed from im_info:
im_h = round(height / scale) im_w = round(weight / scale)
 Parameters
input (Variable) – The input Tensor with shape \([N_1, N_2, ..., N_k, 4]\), the last dimension is 4 and data type is float32 or float64.
im_info (Variable) – The 2D Tensor with shape [N, 3] with layout (height, width, scale) represeting the information of image. height and width is the input size and scale is the ratio of input size and original size. The data type is float32 or float64.
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
output(Variable): The cliped tensor with data type float32 or float64. The shape is same as input.
 Return type
Variable
Examples
import paddle.fluid as fluid boxes = fluid.data( name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1) im_info = fluid.data(name='im_info', shape=[1 ,3]) out = fluid.layers.box_clip( input=boxes, im_info=im_info)
box_coder¶

paddle.fluid.layers.
box_coder
(prior_box, prior_box_var, target_box, code_type='encode_center_size', box_normalized=True, name=None, axis=0)[source] Box Coder Layer
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
\[ \begin{align}\begin{aligned}ox = (tx  px) / pw / pxv\\oy = (ty  py) / ph / pyv\\ow = \log(bs(tw / pw)) / pwv\\oh = \log(bs(th / ph)) / phv\end{aligned}\end{align} \]The Decoding schema described below:
\[ \begin{align}\begin{aligned}ox = (pw * pxv * tx * + px)  tw / 2\\oy = (ph * pyv * ty * + py)  th / 2\\ow = \exp(pwv * tw) * pw + tw / 2\\oh = \exp(phv * th) * ph + th / 2\end{aligned}\end{align} \]where tx, ty, tw, th denote the target box’s center coordinates, width and height respectively. Similarly, px, py, pw, ph denote the priorbox’s (anchor) center coordinates, width and height. pxv, pyv, pwv, phv denote the variance of the priorbox and ox, oy, ow, oh denote the encoded/decoded coordinates, width and height.
During Box Decoding, two modes for broadcast are supported. Say target box has shape [N, M, 4], and the shape of prior box can be [N, 4] or [M, 4]. Then prior box will broadcast to target box along the assigned axis.
 Parameters
prior_box (Variable) – Box list prior_box is a 2D Tensor with shape [M, 4] holds M boxes and data type is float32 or float64. 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 (ListVariableNone) – prior_box_var supports three types of input. One is variable with shape [M, 4] which holds M group and data type is float32 or float64. The second is list consist of 4 elements shared by all boxes and data type is float32 or float64. Other is None and not involved in calculation.
target_box (Variable) – This input can be a 2D LoDTensor with shape [N, 4] when code_type is ‘encode_center_size’. This input also can be a 3D Tensor with shape [N, M, 4] when code_type is ‘decode_center_size’. Each box is represented as [xmin, ymin, xmax, ymax]. The data type is float32 or float64. This tensor can contain LoD information to represent a batch of inputs.
code_type (str) – The code type used with the target box. It can be encode_center_size or decode_center_size. encode_center_size by default.
box_normalized (bool) – Whether treat the priorbox as a noramlized box. Set true by default.
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
axis (int) – Which axis in PriorBox to broadcast for box decode, for example, if axis is 0 and TargetBox has shape [N, M, 4] and PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4] for decoding. It is only valid when code type is decode_center_size. Set 0 by default.
 Returns
output_box(Variable): When code_type is ‘encode_center_size’, the output tensor of box_coder_op with shape [N, M, 4] representing the result of N target boxes encoded with M Prior boxes and variances. When code_type is ‘decode_center_size’, N represents the batch size and M represents the number of deocded boxes.
 Return type
Variable
Examples
import paddle.fluid as fluid # For encode prior_box_encode = fluid.data(name='prior_box_encode', shape=[512, 4], dtype='float32') target_box_encode = fluid.data(name='target_box_encode', shape=[81, 4], dtype='float32') output_encode = fluid.layers.box_coder(prior_box=prior_box_encode, prior_box_var=[0.1,0.1,0.2,0.2], target_box=target_box_encode, code_type="encode_center_size") # For decode prior_box_decode = fluid.data(name='prior_box_decode', shape=[512, 4], dtype='float32') target_box_decode = fluid.data(name='target_box_decode', shape=[512, 81, 4], dtype='float32') output_decode = fluid.layers.box_coder(prior_box=prior_box_decode, prior_box_var=[0.1,0.1,0.2,0.2], target_box=target_box_decode, code_type="decode_center_size", box_normalized=False, axis=1)
box_decoder_and_assign¶

paddle.fluid.layers.
box_decoder_and_assign
(prior_box, prior_box_var, target_box, box_score, box_clip, name=None)[source] Bounding Box Coder.
Decode the target bounding box with the prior_box information.
The Decoding schema is described below:
$$ ox = (pw \times pxv \times tx + px)  \frac{tw}{2} $$ $$ oy = (ph \times pyv \times ty + py)  \frac{th}{2} $$ $$ ow = \exp (pwv \times tw) \times pw + \frac{tw}{2} $$ $$ oh = \exp (phv \times th) \times ph + \frac{th}{2} $$
where tx, ty, tw, th denote the target box’s center coordinates, width and height respectively. Similarly, px, py, pw, ph denote the prior_box’s (anchor) center coordinates, width and height. pxv, pyv, pwv, phv denote the variance of the prior_box and ox, oy, ow, oh denote the decoded coordinates, width and height in decode_box.
decode_box is obtained after box decode, then assigning schema is described below:
For each prior_box, use the best nonbackground class’s decoded values to update the prior_box locations and get output_assign_box. So, the shape of output_assign_box is the same as PriorBox.
 Parameters
prior_box (Variable) – (Tensor, default Tensor<float>) Box list PriorBox is a 2D Tensor with shape [N, 4] which holds N boxes and 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) – (Tensor, default Tensor<float>, optional) PriorBoxVar is a 2D Tensor with shape [N, 4] which holds N group of variance. PriorBoxVar will set all elements to 1 by default
target_box (Variable) – (LoDTensor or Tensor) This input can be a 2D LoDTensor with shape [N, classnum*4]. It holds N targets for N boxes
box_score (Variable) – (LoDTensor or Tensor) This input can be a 2D LoDTensor with shape [N, classnum], each box is represented as [classnum] which is the classification probabilities
box_clip (FLOAT) – (float, default 4.135, np.log(1000. / 16.)) clip box to prevent overflowing
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
decode_box(Variable): (LoDTensor or Tensor) the output tensor of op with shape [N, classnum * 4] representing the result of N target boxes decoded with M Prior boxes and variances for each class
output_assign_box(Variable): (LoDTensor or Tensor) the output tensor of op with shape [N, 4] representing the result of N target boxes decoded with M Prior boxes and variances with the best nonbackground class by BoxScore
 Return type
Tuple
Examples
import paddle.fluid as fluid pb = fluid.data( name='prior_box', shape=[None, 4], dtype='float32') pbv = fluid.data( name='prior_box_var', shape=[4], dtype='float32') loc = fluid.data( name='target_box', shape=[None, 4*81], dtype='float32') scores = fluid.data( name='scores', shape=[None, 81], dtype='float32') decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign( pb, pbv, loc, scores, 4.135)
collect_fpn_proposals¶

paddle.fluid.layers.
collect_fpn_proposals
(multi_rois, multi_scores, min_level, max_level, post_nms_top_n, name=None)[source] This OP only supports LoDTensor as input. Concat multilevel RoIs (Region of Interest) and select N RoIs with respect to multi_scores. This operation performs the following steps:
Choose num_level RoIs and scores as input: num_level = max_level  min_level
Concat multilevel RoIs and scores
Sort scores and select post_nms_top_n scores
Gather RoIs by selected indices from scores
Resort RoIs by corresponding batch_id
 Parameters
multi_rois (list) – List of RoIs to collect. Element in list is 2D LoDTensor with shape [N, 4] and data type is float32 or float64, N is the number of RoIs.
multi_scores (list) – List of scores of RoIs to collect. Element in list is 2D LoDTensor with shape [N, 1] and data type is float32 or float64, N is the number of RoIs.
min_level (int) – The lowest level of FPN layer to collect
max_level (int) – The highest level of FPN layer to collect
post_nms_top_n (int) – The number of selected RoIs
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
fpn_rois(Variable): 2D LoDTensor with shape [N, 4] and data type is float32 or float64. Selected RoIs.
 Return type
Variable
Examples
import paddle.fluid as fluid multi_rois = [] multi_scores = [] for i in range(4): multi_rois.append(fluid.data( name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1)) for i in range(4): multi_scores.append(fluid.data( name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1)) fpn_rois = fluid.layers.collect_fpn_proposals( multi_rois=multi_rois, multi_scores=multi_scores, min_level=2, max_level=5, post_nms_top_n=2000)
density_prior_box¶

paddle.fluid.layers.
density_prior_box
(input, image, densities=None, fixed_sizes=None, fixed_ratios=None, variance=[0.1, 0.1, 0.2, 0.2], clip=False, steps=[0.0, 0.0], offset=0.5, flatten_to_2d=False, name=None)[source] This op generates density prior boxes for SSD(Single Shot MultiBox Detector) algorithm. Each position of the input produce N prior boxes, N is determined by the count of densities, fixed_sizes and fixed_ratios. Boxes center at grid points around each input position is generated by this operator, and the grid points is determined by densities and the count of density prior box is determined by fixed_sizes and fixed_ratios. Obviously, the number of fixed_sizes is equal to the number of densities.
For densities_i in densities:
\[N\_density_prior\_box = SUM(N\_fixed\_ratios * densities\_i^2)\]N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.
 Parameters
input (Variable) – 4D tensor(NCHW), the data type should be float32 of float64.
image (Variable) – 4D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64. the layout is NCHW.
densities (listtupleNone) – The densities of generated density prior boxes, this attribute should be a list or tuple of integers. Default: None.
fixed_sizes (listtupleNone) – The fixed sizes of generated density prior boxes, this attribute should a list or tuple of same length with
densities
. Default: None.fixed_ratios (listtupleNone) – The fixed ratios of generated density prior boxes, if this attribute is not set and
densities
andfix_sizes
is set,aspect_ratios
will be used to generate density prior boxes.variance (listtuple) – The variances to be encoded in density prior boxes. Default:[0.1, 0.1, 0.2, 0.2].
clip (bool) – Whether to clip out of boundary boxes. Default: False.
step (listtuple) – Prior boxes step across width and height, If step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across height or weight of the input will be automatically calculated. Default: [0., 0.]
offset (float) – Prior boxes center offset. Default: 0.5
flatten_to_2d (bool) – Whether to flatten output prior boxes and variance to 2D shape, the second dim is 4. Default: False.
name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name
 Returns
A tuple with two Variable (boxes, variances)
boxes: the output density prior boxes of PriorBox. 4D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False. 2D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True. H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
variances: the expanded variances of PriorBox. 4D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False. 2D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True. H is the height of input, W is the width of input, and num_priors is the total box count of each position of input.
 Return type
Tuple
Examples
#declarative mode import paddle.fluid as fluid import numpy as np input = fluid.data(name="input", shape=[None,3,6,9]) image = fluid.data(name="image", shape=[None,3,9,12]) box, var = fluid.layers.density_prior_box( input=input, image=image, densities=[4, 2, 1], fixed_sizes=[32.0, 64.0, 128.0], fixed_ratios=[1.], clip=True, flatten_to_2d=True) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) # prepare a batch of data input_data = np.random.rand(1,3,6,9).astype("float32") image_data = np.random.rand(1,3,9,12).astype("float32") box_out, var_out = exe.run( fluid.default_main_program(), feed={"input":input_data, "image":image_data}, fetch_list=[box,var], return_numpy=True) print(mask_out.shape) # (1134, 4) print(z_out.shape) # (1134, 4) #imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) image = dg.to_variable(image_data) box, var = fluid.layers.density_prior_box( input=input, image=image, densities=[4, 2, 1], fixed_sizes=[32.0, 64.0, 128.0], fixed_ratios=[1.], clip=True) print(box.shape) # [6L, 9L, 21L, 4L] print(var.shape) # [6L, 9L, 21L, 4L]
detection_map¶
detection_output¶

paddle.fluid.layers.
detection_output
(loc, scores, 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, return_index=False)[source] Given the regression locations, classification confidences and prior boxes, calculate the detection outputs by performing following steps:
Decode input bounding box predictions according to the prior boxes and regression locations.
Get the final detection results by applying multiclass non maximum suppression (NMS).
Please note, this operation doesn’t clip the final output bounding boxes to the image window.
 Parameters
loc (Variable) – A 3D Tensor with shape [N, M, 4] represents the predicted locations of M bounding bboxes. Data type should be float32 or float64. N is the batch size, and each bounding box has four coordinate values and the layout is [xmin, ymin, xmax, ymax].
scores (Variable) – A 3D Tensor with shape [N, M, C] represents the predicted confidence predictions. Data type should be float32 or float64. N is the batch size, C is the class number, M is number of bounding boxes.
prior_box (Variable) – A 2D Tensor with shape [M, 4] holds M boxes, each box is represented as [xmin, ymin, xmax, ymax]. Data type should be float32 or float64.
prior_box_var (Variable) – A 2D Tensor with shape [M, 4] holds M group of variance. Data type should be float32 or float64.
background_label (int) – The index of background label, the background label will be ignored. If set to 1, then all categories will be considered. Default: 0.
nms_threshold (float) – The threshold to be used in NMS. Default: 0.3.
nms_top_k (int) – Maximum number of detections to be kept according to the confidences aftern filtering detections based on score_threshold and before NMS. Default: 400.
keep_top_k (int) – Number of total bboxes to be kept per image after NMS step. 1 means keeping all bboxes after NMS step. Default: 200.
score_threshold (float) – Threshold to filter out bounding boxes with low confidence score. If not provided, consider all boxes. Default: 0.01.
nms_eta (float) – The parameter for adaptive NMS. It works only when the value is less than 1.0. Default: 1.0.
return_index (bool) – Whether return selected index. Default: False
 Returns
(Out, Index) if return_index is True, otherwise, a tuple with one Variable(Out) is returned.
Out (Variable): The detection outputs is a LoDTensor with shape [No, 6]. Data type is the same as input (loc). Each row has six values: [label, confidence, xmin, ymin, xmax, ymax]. No is the total number of detections in this minibatch. For each instance, the offsets in first dimension are called LoD, the offset number is N + 1, N is the batch size. The ith image has LoD[i + 1]  LoD[i] detected results, if it is 0, the ith image has no detected results.
Index (Variable): Only return when return_index is True. A 2D LoDTensor with shape [No, 1] represents the selected index which type is Integer. The index is the absolute value cross batches. No is the same number as Out. If the index is used to gather other attribute such as age, one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where N is the batch size and M is the number of boxes.
 Return type
A tuple with two Variables
Examples
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=[2, 21, 4], dtype='float32') scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32') nmsed_outs, index = fluid.layers.detection_output(scores=scores, loc=loc, prior_box=pb, prior_box_var=pbv, return_index=True)
distribute_fpn_proposals¶

paddle.fluid.layers.
distribute_fpn_proposals
(fpn_rois, min_level, max_level, refer_level, refer_scale, name=None)[source] This op only takes LoDTensor as input. In Feature Pyramid Networks (FPN) models, it is needed to distribute all proposals into different FPN level, with respect to scale of the proposals, the referring scale and the referring level. Besides, to restore the order of proposals, we return an array which indicates the original index of rois in current proposals. To compute FPN level for each roi, the formula is given as follows:
\[ \begin{align}\begin{aligned}roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}\\level = floor(&\log(\frac{roi\_scale}{refer\_scale}) + refer\_level)\end{aligned}\end{align} \]where BBoxArea is a function to compute the area of each roi.
 Parameters
fpn_rois (Variable) – 2D Tensor with shape [N, 4] and data type is float32 or float64. The input fpn_rois.
min_level (int32) – The lowest level of FPN layer where the proposals come from.
max_level (int32) – The highest level of FPN layer where the proposals come from.
refer_level (int32) – The referring level of FPN layer with specified scale.
refer_scale (int32) – The referring scale of FPN layer with specified level.
name (str, optional) – For detailed information, please refer to api_guide_Name. Usually name is no need to set and None by default.
 Returns
multi_rois(List) : A list of 2D LoDTensor with shape [M, 4] and data type of float32 and float64. The length is max_levelmin_level+1. The proposals in each FPN level.
restore_ind(Variable): A 2D Tensor with shape [N, 1], N is the number of total rois. The data type is int32. It is used to restore the order of fpn_rois.
 Return type
Tuple
Examples
import paddle.fluid as fluid fpn_rois = fluid.data( name='data', shape=[None, 4], dtype='float32', lod_level=1) multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals( fpn_rois=fpn_rois, min_level=2, max_level=5, refer_level=4, refer_scale=224)
generate_mask_labels¶

paddle.fluid.layers.
generate_mask_labels
(im_info, gt_classes, is_crowd, gt_segms, rois, labels_int32, num_classes, resolution)[source] Generate Mask Labels for MaskRCNN
This operator can be, for given the RoIs and corresponding labels, to sample foreground RoIs. This mask branch also has a :math: K times M^{2} dimensional output targets for each foreground RoI, which encodes K binary masks of resolution M x M, one for each of the K classes. This mask targets are used to compute loss of mask branch.
Please note, the data format of groudtruth segmentation, assumed the segmentations are as follows. The first instance has two gt objects. The second instance has one gt object, this object has two gt segmentations.
#[ # [[[229.14, 370.9, 229.14, 370.9, ...]], # [[343.7, 139.85, 349.01, 138.46, ...]]], # 0th instance # [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1th instance #] batch_masks = [] for semgs in batch_semgs: gt_masks = [] for semg in semgs: gt_segm = [] for polys in semg: gt_segm.append(np.array(polys).reshape(1, 2)) gt_masks.append(gt_segm) batch_masks.append(gt_masks) place = fluid.CPUPlace() feeder = fluid.DataFeeder(place=place, feed_list=feeds) feeder.feed(batch_masks)
 Parameters
im_info (Variable) – A 2D Tensor with shape [N, 3] and float32 data type. N is the batch size, each element is [height, width, scale] of image. Image scale is target_size / original_size, target_size is the size after resize, original_size is the original image size.
gt_classes (Variable) – A 2D LoDTensor with shape [M, 1]. Data type shoule be int. M is the total number of groundtruth, each element is a class label.
is_crowd (Variable) – A 2D LoDTensor with same shape and same data type as gt_classes, each element is a flag indicating whether a groundtruth is crowd.
gt_segms (Variable) – This input is a 2D LoDTensor with shape [S, 2] and float32 data type, it’s LoD level is 3. Usually users do not needs to understand LoD, The users should return correct data format in reader. The LoD[0] represents the groundtruth objects number of each instance. LoD[1] represents the segmentation counts of each objects. LoD[2] represents the polygons number of each segmentation. S the total number of polygons coordinate points. Each element is (x, y) coordinate points.
rois (Variable) – A 2D LoDTensor with shape [R, 4] and float32 data type float32. R is the total number of RoIs, each element is a bounding box with (xmin, ymin, xmax, ymax) format in the range of original image.
labels_int32 (Variable) – A 2D LoDTensor in shape of [R, 1] with type of int32. R is the same as it in rois. Each element repersents a class label of a RoI.
num_classes (int) – Class number.
resolution (int) – Resolution of mask predictions.
 Returns
A 2D LoDTensor with shape [P, 4] and same data type as rois. P is the total number of sampled RoIs. Each element is a bounding box with [xmin, ymin, xmax, ymax] format in range of orignal image size.
mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1] and int data type, each element repersents the output mask RoI index with regard to input RoIs.
mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int data type, K is the classes number and M is the resolution of mask predictions. Each element repersents the binary mask targets.
 Return type
mask_rois (Variable)
Examples
import paddle.fluid as fluid im_info = fluid.data(name="im_info", shape=[None, 3], dtype="float32") gt_classes = fluid.data(name="gt_classes", shape=[None, 1], dtype="float32", lod_level=1) is_crowd = fluid.data(name="is_crowd", shape=[None, 1], dtype="float32", lod_level=1) gt_masks = fluid.data(name="gt_masks", shape=[None, 2], dtype="float32", lod_level=3) # rois, roi_labels can be the output of # fluid.layers.generate_proposal_labels. rois = fluid.data(name="rois", shape=[None, 4], dtype="float32", lod_level=1) roi_labels = fluid.data(name="roi_labels", shape=[None, 1], dtype="int32", lod_level=1) mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels( im_info=im_info, gt_classes=gt_classes, is_crowd=is_crowd, gt_segms=gt_masks, rois=rois, labels_int32=roi_labels, num_classes=81, resolution=14)
generate_proposal_labels¶

paddle.fluid.layers.
generate_proposal_labels
(rpn_rois, gt_classes, is_crowd, gt_boxes, im_info, batch_size_per_im=256, fg_fraction=0.25, fg_thresh=0.25, bg_thresh_hi=0.5, bg_thresh_lo=0.0, bbox_reg_weights=[0.1, 0.1, 0.2, 0.2], class_nums=None, use_random=True, is_cls_agnostic=False, is_cascade_rcnn=False)[source] Generate Proposal Labels of FasterRCNN
This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth, to sample foreground boxes and background boxes, and compute loss target.
RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction, If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample. If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi, then it was considered as a background sample. After all foreground and background boxes are chosen (so called Rois), then we apply random sampling to make sure the number of foreground boxes is no more than batch_size_per_im * fg_fraction.
For each box in Rois, we assign the classification (class label) and regression targets (box label) to it. Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.
 Parameters
rpn_rois (Variable) – A 2D LoDTensor with shape [N, 4]. N is the number of the GenerateProposalOp’s output, each element is a bounding box with [xmin, ymin, xmax, ymax] format. The data type can be float32 or float64.
gt_classes (Variable) – A 2D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a class label of groundtruth. The data type must be int32.
is_crowd (Variable) – A 2D LoDTensor with shape [M, 1]. M is the number of groundtruth, each element is a flag indicates whether a groundtruth is crowd. The data type must be int32.
gt_boxes (Variable) – A 2D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.
im_info (Variable) – A 2D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.
batch_size_per_im (int) – Batch size of rois per images. The data type must be int32.
fg_fraction (float) – Foreground fraction in total batch_size_per_im. The data type must be float32.
fg_thresh (float) – Overlap threshold which is used to chose foreground sample. The data type must be float32.
bg_thresh_hi (float) – Overlap threshold upper bound which is used to chose background sample. The data type must be float32.
bg_thresh_lo (float) – Overlap threshold lower bound which is used to chose background sample. The data type must be float32.
bbox_reg_weights (listtuple) – Box regression weights. The data type must be float32.
class_nums (int) – Class number. The data type must be int32.
use_random (bool) – Use random sampling to choose foreground and background boxes.
is_cls_agnostic (bool) – bbox regression use class agnostic simply which only represent fg and bg boxes.
is_cascade_rcnn (bool) – it will filter some bbox crossing the image’s boundary when setting True.
 Returns
A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.
rois: 2D LoDTensor with shape
[batch_size_per_im * batch_size, 4]
. The data type is the same asrpn_rois
.labels_int32: 2D LoDTensor with shape
[batch_size_per_im * batch_size, 1]
. The data type must be int32.bbox_targets: 2D LoDTensor with shape
[batch_size_per_im * batch_size, 4 * class_num]
. The regression targets of all RoIs. The data type is the same asrpn_rois
.bbox_inside_weights: 2D LoDTensor with shape
[batch_size_per_im * batch_size, 4 * class_num]
. The weights of foreground boxes’ regression loss. The data type is the same asrpn_rois
.bbox_outside_weights: 2D LoDTensor with shape
[batch_size_per_im * batch_size, 4 * class_num]
. The weights of regression loss. The data type is the same asrpn_rois
.
 Return type
tuple
Examples
import paddle.fluid as fluid rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32') gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='float32') is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='float32') gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32') im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32') rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels( rpn_rois, gt_classes, is_crowd, gt_boxes, im_info, class_nums=10)
generate_proposals¶

paddle.fluid.layers.
generate_proposals
(scores, bbox_deltas, im_info, anchors, variances, pre_nms_top_n=6000, post_nms_top_n=1000, nms_thresh=0.5, min_size=0.1, eta=1.0, name=None)[source] Generate proposal FasterRCNN
This operation proposes RoIs according to each box with their probability to be a foreground object and the box can be calculated by anchors. Bbox_deltais and scores to be an object are the output of RPN. Final proposals could be used to train detection net.
For generating proposals, this operation performs following steps:
Transposes and resizes scores and bbox_deltas in size of (H*W*A, 1) and (H*W*A, 4)
Calculate box locations as proposals candidates.
Clip boxes to image
Remove predicted boxes with small area.
Apply NMS to get final proposals as output.
 Parameters
scores (Variable) – A 4D Tensor with shape [N, A, H, W] represents the probability for each box to be an object. N is batch size, A is number of anchors, H and W are height and width of the feature map. The data type must be float32.
bbox_deltas (Variable) – A 4D Tensor with shape [N, 4*A, H, W] represents the differece between predicted box locatoin and anchor location. The data type must be float32.
im_info (Variable) – A 2D Tensor with shape [N, 3] represents origin image information for N batch. Info contains height, width and scale between origin image size and the size of feature map. The data type must be int32.
anchors (Variable) – A 4D Tensor represents the anchors with a layout of [H, W, A, 4]. H and W are height and width of the feature map, num_anchors is the box count of each position. Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.
variances (Variable) – A 4D Tensor. The expanded variances of anchors with a layout of [H, W, num_priors, 4]. Each variance is in (xcenter, ycenter, w, h) format. The data type must be float32.
pre_nms_top_n (float) – Number of total bboxes to be kept per image before NMS. The data type must be float32. 6000 by default.
post_nms_top_n (float) – Number of total bboxes to be kept per image after NMS. The data type must be float32. 1000 by default.
nms_thresh (float) – Threshold in NMS. The data type must be float32. 0.5 by default.
min_size (float) – Remove predicted boxes with either height or width < min_size. The data type must be float32. 0.1 by default.
eta (float) – Apply in adaptive NMS, if adaptive threshold > 0.5, adaptive_threshold = adaptive_threshold * eta in each iteration.
 Returns
A tuple with format
(rpn_rois, rpn_roi_probs)
.rpn_rois: The generated RoIs. 2D Tensor with shape
[N, 4]
whileN
is the number of RoIs. The data type is the same asscores
.rpn_roi_probs: The scores of generated RoIs. 2D Tensor with shape
[N, 1]
whileN
is the number of RoIs. The data type is the same asscores
.
 Return type
tuple
Examples
import paddle.fluid as fluid scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32') bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32') im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32') anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32') variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32') rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas, im_info, anchors, variances)
iou_similarity¶

paddle.fluid.layers.
iou_similarity
(x, y, name=None)[source] IOU Similarity Operator
Computes intersectionoverunion (IOU) between two box lists. Box list ‘X’ should be a LoDTensor and ‘Y’ is a common Tensor, boxes in ‘Y’ are shared by all instance of the batched inputs of X. Given two boxes A and B, the calculation of IOU is as follows:
$$ IOU(A, B) = \frac{area(A\cap B)}{area(A)+area(B)area(A\cap B)} $$
 Parameters
x (Variable) – (LoDTensor, default LoDTensor<float>) Box list X is a 2D LoDTensor with shape [N, 4] holds N boxes, each box is represented as [xmin, ymin, xmax, ymax], the shape of X is [N, 4]. [xmin, ymin] is the left top coordinate of the 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 box. This tensor can contain LoD information to represent a batch of inputs. One instance of this batch can contain different numbers of entities.The data type is float32 or float64.
y (Variable) – (Tensor, default Tensor<float>) Box list Y holds M boxes, each box is represented as [xmin, ymin, xmax, ymax], the shape of X is [N, 4]. [xmin, ymin] is the left top coordinate of the box if the input is image feature map, and [xmax, ymax] is the right bottom coordinate of the box.The data type is float32 or float64.
 Returns
(LoDTensor, the lod is same as input X) The output of iou_similarity op, a tensor with shape [N, M] representing pairwise iou scores.The data type is same with x.
 Return type
Variable
Examples
import numpy as np import paddle.fluid as fluid use_gpu = False place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace() exe = fluid.Executor(place) x = fluid.data(name='x', shape=[None, 4], dtype='float32') y = fluid.data(name='y', shape=[None, 4], dtype='float32') iou = fluid.layers.iou_similarity(x=x, y=y) exe.run(fluid.default_startup_program()) test_program = fluid.default_main_program().clone(for_test=True) [out_iou] = exe.run(test_program, fetch_list=iou, feed={'x': np.array([[0.5, 0.5, 2.0, 2.0], [0., 0., 1.0, 1.0]]).astype('float32'), 'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')}) # out_iou is [[0.2857143], # [0. ]] with shape: [2, 1]
multi_box_head¶

paddle.fluid.layers.
multi_box_head
(inputs, image, base_size, num_classes, aspect_ratios, min_ratio=None, max_ratio=None, min_sizes=None, max_sizes=None, steps=None, step_w=None, step_h=None, offset=0.5, variance=[0.1, 0.1, 0.2, 0.2], flip=True, clip=False, kernel_size=1, pad=0, stride=1, name=None, min_max_aspect_ratios_order=False)[source] Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes, regression location and classification confidence on multiple input feature maps, then output the concatenate results. The details of this algorithm, please refer the section 2.2 of SSD paper SSD: Single Shot MultiBox Detector .
 Parameters
inputs (list(Variable)tuple(Variable)) – The list of input variables, the format of all Variables are 4D Tensor, layout is NCHW. Data type should be float32 or float64.
image (Variable) – The input image, layout is NCHW. Data type should be the same as inputs.
base_size (int) –
the base_size is input image size. When len(inputs) > 2 and min_size and max_size are None, the min_size and max_size are calculated by baze_size, ‘min_ratio’ and max_ratio. The formula is as follows:
min_sizes = [] max_sizes = [] step = int(math.floor(((max_ratio  min_ratio)) / (num_layer  2))) for ratio in six.moves.range(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
num_classes (int) – The number of classes.
aspect_ratios (list(float)  tuple(float)) – the aspect ratios of generated prior boxes. The length of input and aspect_ratios must be equal.
min_ratio (int) – the min ratio of generated prior boxes.
max_ratio (int) – the max ratio of generated prior boxes.
min_sizes (listtupleNone) – If len(inputs) <=2, min_sizes must be set up, and the length of min_sizes should equal to the length of inputs. Default: None.
max_sizes (listtupleNone) – If len(inputs) <=2, max_sizes must be set up, and the length of min_sizes should equal to the length of inputs. Default: None.
steps (listtuple) – If step_w and step_h are the same, step_w and step_h can be replaced by steps.
step_w (listtuple) – Prior boxes step across width. If step_w[i] == 0.0, the prior boxes step across width of the inputs[i] will be automatically calculated. Default: None.
step_h (listtuple) – Prior boxes step across height, If step_h[i] == 0.0, the prior boxes step across height of the inputs[i] will be automatically calculated. Default: None.
offset (float) – Prior boxes center offset. Default: 0.5
variance (listtuple) – the variances to be encoded in prior boxes. Default:[0.1, 0.1, 0.2, 0.2].
flip (bool) – Whether to flip aspect ratios. Default:False.
clip (bool) – Whether to clip outofboundary boxes. Default: False.
kernel_size (int) – The kernel size of conv2d. Default: 1.
pad (intlisttuple) – The padding of conv2d. Default:0.
stride (intlisttuple) – The stride of conv2d. Default:1,
name (str) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name.
min_max_aspect_ratios_order (bool) – If set True, the output prior box is in order of [min, max, aspect_ratios], which is consistent with Caffe. Please note, this order affects the weights order of convolution layer followed by and does not affect the fininal detection results. Default: False.
 Returns
A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)
mbox_loc (Variable): The predicted boxes’ location of the inputs. The layout is [N, num_priors, 4], where N is batch size,
num_priors
is the number of prior boxes. Data type is the same as input.mbox_conf (Variable): The predicted boxes’ confidence of the inputs. The layout is [N, num_priors, C], where
N
andnum_priors
has the same meaning as above. C is the number of Classes. Data type is the same as input.boxes (Variable): the output prior boxes. The layout is [num_priors, 4]. The meaning of num_priors is the same as above. Data type is the same as input.
variances (Variable): the expanded variances for prior boxes. The layout is [num_priors, 4]. Data type is the same as input.
 Return type
tuple
 Examples 1: set min_ratio and max_ratio:
import paddle.fluid as fluid images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32') conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32') conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32') conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32') conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32') conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32') conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32') mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head( inputs=[conv1, conv2, conv3, conv4, conv5, conv6], image=images, num_classes=21, min_ratio=20, max_ratio=90, aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]], base_size=300, offset=0.5, flip=True, clip=True)
 Examples 2: set min_sizes and max_sizes:
import paddle.fluid as fluid images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32') conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32') conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32') conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32') conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32') conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32') conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32') mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head( inputs=[conv1, conv2, conv3, conv4, conv5, conv6], image=images, num_classes=21, min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0], max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0], aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]], base_size=300, offset=0.5, flip=True, clip=True)
multiclass_nms¶

paddle.fluid.layers.
multiclass_nms
(bboxes, scores, score_threshold, nms_top_k, keep_top_k, nms_threshold=0.3, normalized=True, nms_eta=1.0, background_label=0, name=None)[source] Multiclass NMS
This operator is to do multiclass non maximum suppression (NMS) on boxes and scores.
In the NMS step, this operator greedily selects a subset of detection bounding boxes that have high scores larger than score_threshold, if providing this threshold, then selects the largest nms_top_k confidences scores if nms_top_k is larger than 1. Then this operator pruns away boxes that have high IOU (intersection over union) overlap with already selected boxes by adaptive threshold NMS based on parameters of nms_threshold and nms_eta. Aftern NMS step, at most keep_top_k number of total bboxes are to be kept per image if keep_top_k is larger than 1.
See below for an example:
if: box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax) box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4) box2.data = (3.0, 4.0, 8.0, 5.0) box2.score = (0.3, 0.3, 0.1) nms_threshold = 0.3 background_label = 0 score_threshold = 0 Then: iou = 4/11 > 0.3 out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0], [2, 0.4, 2.0, 3.0, 7.0, 5.0]] Out format is (label, confidence, xmin, ymin, xmax, ymax)
 Parameters
bboxes (Variable) – Two types of bboxes are supported: 1. (Tensor) A 3D Tensor with shape [N, M, 4 or 8 16 24 32] represents the predicted locations of M bounding bboxes, N is the batch size. Each bounding box has four coordinate values and the layout is [xmin, ymin, xmax, ymax], when box size equals to 4. The data type is float32 or float64. 2. (LoDTensor) A 3D Tensor with shape [M, C, 4] M is the number of bounding boxes, C is the class number. The data type is float32 or float64.
scores (Variable) – Two types of scores are supported: 1. (Tensor) A 3D 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. Please note, M is equal to the 2nd dimension of BBoxes.The data type is float32 or float64. 2. (LoDTensor) A 2D LoDTensor with shape [M, C]. M is the number of bbox, C is the class number. In this case, input BBoxes should be the second case with shape [M, C, 4].The data type is float32 or float64.
background_label (int) – The index of background label, the background label will be ignored. If set to 1, then all categories will be considered. Default: 0
score_threshold (float) – Threshold to filter out bounding boxes with low confidence score. If not provided, consider all boxes.
nms_top_k (int) – Maximum number of detections to be kept according to the confidences aftern the filtering detections based on score_threshold.
nms_threshold (float) – The threshold to be used in NMS. Default: 0.3
nms_eta (float) – The threshold to be used in NMS. Default: 1.0
keep_top_k (int) – Number of total bboxes to be kept per image after NMS step. 1 means keeping all bboxes after NMS step.
normalized (bool) – Whether detections are normalized. Default: True
name (str) – Name of the multiclass nms op. Default: None.
 Returns
 A 2D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax] or A 2D LoDTensor with shape [No, 10] represents the detections. Each row has 10 values: [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the total number of detections. If there is no detected boxes for all images, lod will be set to {1} and Out only contains one value which is 1. (After version 1.3, when no boxes detected, the lod is changed from {0} to {1})
 Return type
Variable
Examples
import paddle.fluid as fluid boxes = fluid.data(name='bboxes', shape=[None,81, 4], dtype='float32', lod_level=1) scores = fluid.data(name='scores', shape=[None,81], dtype='float32', lod_level=1) out = fluid.layers.multiclass_nms(bboxes=boxes, scores=scores, background_label=0, score_threshold=0.5, nms_top_k=400, nms_threshold=0.3, keep_top_k=200, normalized=False)
polygon_box_transform¶

paddle.fluid.layers.
polygon_box_transform
(input, name=None)[source] PolygonBoxTransform Operator.
PolygonBoxTransform Operator is used to transform the coordinate shift to the real coordinate.
The input is the final geometry output in detection network. We use 2*n numbers to denote the coordinate shift from n corner vertices of the polygon_box to the pixel location. As each distance offset contains two numbers (xi, yi), the geometry output contains 2*n channels.
 Parameters
input (Variable) – The input with shape [batch_size, geometry_channels, height, width]. A Tensor with type float32, float64.
name (str, Optional) – For details, please refer to api_guide_Name. Generally, no setting is required. Default: None.
 Returns
The output with the same shape as input. A Tensor with type float32, float64.
 Return type
Variable
Examples
import paddle.fluid as fluid input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32') out = fluid.layers.polygon_box_transform(input)
prior_box¶

paddle.fluid.layers.
prior_box
(input, image, min_sizes, max_sizes=None, aspect_ratios=[1.0], variance=[0.1, 0.1, 0.2, 0.2], flip=False, clip=False, steps=[0.0, 0.0], offset=0.5, name=None, min_max_aspect_ratios_order=False)[source] This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm. Each position of the input produce N prior boxes, N is determined by the count of min_sizes, max_sizes and aspect_ratios, The size of the box is in range(min_size, max_size) interval, which is generated in sequence according to the aspect_ratios.
 Parameters
input (Variable) – 4D tenosr(NCHW), the data type should be float32 or float64.
image (Variable) – 4D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.
min_sizes (listtuplefloat) – the min sizes of generated prior boxes.
max_sizes (listtupleNone) – the max sizes of generated prior boxes. Default: None.
aspect_ratios (listtuplefloat) – the aspect ratios of generated prior boxes. Default: [1.].
variance (listtuple) – the variances to be encoded in prior boxes. Default:[0.1, 0.1, 0.2, 0.2].
flip (bool) – Whether to flip aspect ratios. Default:False.
clip (bool) – Whether to clip outofboundary boxes. Default: False.
step (listtuple) – Prior boxes step across width and height, If step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across height or weight of the input will be automatically calculated. Default: [0., 0.]
offset (float) – Prior boxes center offset. Default: 0.5
min_max_aspect_ratios_order (bool) – If set True, the output prior box is in order of [min, max, aspect_ratios], which is consistent with Caffe. Please note, this order affects the weights order of convolution layer followed by and does not affect the final detection results. Default: False.
name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name
 Returns
A tuple with two Variable (boxes, variances)
boxes(Variable): the output prior boxes of PriorBox. 4D tensor, the layout is [H, W, num_priors, 4]. H is the height of input, W is the width of input, num_priors is the total box count of each position of input.
variances(Variable): the expanded variances of PriorBox. 4D tensor, the layput is [H, W, num_priors, 4]. H is the height of input, W is the width of input num_priors is the total box count of each position of input
 Return type
Tuple
Examples
#declarative mode import paddle.fluid as fluid import numpy as np input = fluid.data(name="input", shape=[None,3,6,9]) image = fluid.data(name="image", shape=[None,3,9,12]) box, var = fluid.layers.prior_box( input=input, image=image, min_sizes=[100.], clip=True, flip=True) place = fluid.CPUPlace() exe = fluid.Executor(place) exe.run(fluid.default_startup_program()) # prepare a batch of data input_data = np.random.rand(1,3,6,9).astype("float32") image_data = np.random.rand(1,3,9,12).astype("float32") box_out, var_out = exe.run(fluid.default_main_program(), feed={"input":input_data,"image":image_data}, fetch_list=[box,var], return_numpy=True) # print(box_out.shape) # (6, 9, 1, 4) # print(var_out.shape) # (6, 9, 1, 4) # imperative mode import paddle.fluid.dygraph as dg with dg.guard(place) as g: input = dg.to_variable(input_data) image = dg.to_variable(image_data) box, var = fluid.layers.prior_box( input=input, image=image, min_sizes=[100.], clip=True, flip=True) # print(box.shape) # [6L, 9L, 1L, 4L] # print(var.shape) # [6L, 9L, 1L, 4L]
retinanet_detection_output¶

paddle.fluid.layers.
retinanet_detection_output
(bboxes, scores, anchors, im_info, score_threshold=0.05, nms_top_k=1000, keep_top_k=100, nms_threshold=0.3, nms_eta=1.0)[source] Detection Output Layer for the detector RetinaNet.
In the detector RetinaNet , many FPN levels output the category and location predictions, this OP is to get the detection results by performing following steps:
For each FPN level, decode box predictions according to the anchor boxes from at most
nms_top_k
topscoring predictions after thresholding detector confidence atscore_threshold
.Merge top predictions from all levels and apply multiclass non maximum suppression (NMS) on them to get the final detections.
 Parameters
bboxes (List) – A list of Tensors from multiple FPN levels represents the location prediction for all anchor boxes. Each element is a 3D Tensor with shape \([N, Mi, 4]\), \(N\) is the batch size, \(Mi\) is the number of bounding boxes from \(i\)th FPN level and each bounding box has four coordinate values and the layout is [xmin, ymin, xmax, ymax]. The data type of each element is float32 or float64.
scores (List) – A list of Tensors from multiple FPN levels represents the category prediction for all anchor boxes. Each element is a 3D Tensor with shape \([N, Mi, C]\), \(N\) is the batch size, \(C\) is the class number (excluding background), \(Mi\) is the number of bounding boxes from \(i\)th FPN level. The data type of each element is float32 or float64.
anchors (List) – A list of Tensors from multiple FPN levels represents the locations of all anchor boxes. Each element is a 2D Tensor with shape \([Mi, 4]\), \(Mi\) is the number of bounding boxes from \(i\)th FPN level, and each bounding box has four coordinate values and the layout is [xmin, ymin, xmax, ymax]. The data type of each element is float32 or float64.
im_info (Variable) – A 2D Tensor with shape \([N, 3]\) represents the size information of input images. \(N\) is the batch size, the size informarion of each image is a 3vector which are the height and width of the network input along with the factor scaling the origin image to the network input. The data type of
im_info
is float32.score_threshold (float) – Threshold to filter out bounding boxes with a confidence score before NMS, default value is set to 0.05.
nms_top_k (int) – Maximum number of detections per FPN layer to be kept according to the confidences before NMS, default value is set to 1000.
keep_top_k (int) – Number of total bounding boxes to be kept per image after NMS step. Default value is set to 100, 1 means keeping all bounding boxes after NMS step.
nms_threshold (float) – The IntersectionoverUnion(IoU) threshold used to filter out boxes in NMS.
nms_eta (float) – The parameter for adjusting
nms_threshold
in NMS. Default value is set to 1., which represents the value ofnms_threshold
keep the same in NMS. Ifnms_eta
is set to be lower than 1. and the value ofnms_threshold
is set to be higher than 0.5, everytime a bounding box is filtered out, the adjustment fornms_threshold
likenms_threshold
=nms_threshold
*nms_eta
will not be stopped until the actual value ofnms_threshold
is lower than or equal to 0.5.
Notice: In some cases where the image sizes are very small, it’s possible that there is no detection if
score_threshold
are used at all levels. Hence, this OP do not filter out anchors from the highest FPN level before NMS. And the last element inbboxes
:,scores
andanchors
is required to be from the hightest FPN level. Returns
The detection output is a 1level LoDTensor with shape \([No, 6]\). Each row has six values: [label, confidence, xmin, ymin, xmax, ymax]. \(No\) is the total number of detections in this minibatch. The \(i\)th image has LoD[i + 1]  LoD[i] detected results, if LoD[i + 1]  LoD[i] is 0, the \(i\)th image has no detected results. If all images have no detected results, LoD will be set to 0, and the output tensor is empty (None).
 Return type
Variable(The data type is float32 or float64)
Examples
import paddle.fluid as fluid bboxes_low = fluid.data( name='bboxes_low', shape=[1, 44, 4], dtype='float32') bboxes_high = fluid.data( name='bboxes_high', shape=[1, 11, 4], dtype='float32') scores_low = fluid.data( name='scores_low', shape=[1, 44, 10], dtype='float32') scores_high = fluid.data( name='scores_high', shape=[1, 11, 10], dtype='float32') anchors_low = fluid.data( name='anchors_low', shape=[44, 4], dtype='float32') anchors_high = fluid.data( name='anchors_high', shape=[11, 4], dtype='float32') im_info = fluid.data( name="im_info", shape=[1, 3], dtype='float32') nmsed_outs = fluid.layers.retinanet_detection_output( bboxes=[bboxes_low, bboxes_high], scores=[scores_low, scores_high], anchors=[anchors_low, anchors_high], im_info=im_info, score_threshold=0.05, nms_top_k=1000, keep_top_k=100, nms_threshold=0.45, nms_eta=1.)
retinanet_target_assign¶

paddle.fluid.layers.
retinanet_target_assign
(bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, gt_labels, is_crowd, im_info, num_classes=1, positive_overlap=0.5, negative_overlap=0.4)[source] Target Assign Layer for the detector RetinaNet.
This OP finds out positive and negative samples from all anchors for training the detector RetinaNet , and assigns target labels for classification along with target locations for regression to each sample, then takes out the part belonging to positive and negative samples from category prediction(
cls_logits
) and location prediction(bbox_pred
) which belong to all anchors.The searching principles for positive and negative samples are as followed:
1. Anchors are assigned to groundtruth boxes when it has the highest IoU overlap with a groundtruth box.
2. Anchors are assigned to groundtruth boxes when it has an IoU overlap higher than
positive_overlap
with any groundtruth box.3. Anchors are assigned to background when its IoU overlap is lower than
negative_overlap
for all groundtruth boxes.4. Anchors which do not meet the above conditions do not participate in the training process.
Retinanet predicts a \(C\)vector for classification and a 4vector for box regresion for each anchor, hence the target label for each positive(or negative) sample is a \(C\)vector and the target locations for each positive sample is a 4vector. As for a positive sample, if the category of its assigned groundtruth box is class \(i\), the corresponding entry in its length \(C\) label vector is set to 1 and all other entries is set to 0, its box regression targets are computed as the offset between itself and its assigned groundtruth box. As for a negative sample, all entries in its length \(C\) label vector are set to 0 and box regression targets are omitted because negative samples do not participate in the training process of location regression.
After the assignment, the part belonging to positive and negative samples is taken out from category prediction(
cls_logits
), and the part belonging to positive samples is taken out from location prediction(bbox_pred
). Parameters
bbox_pred (Variable) – A 3D Tensor with shape \([N, M, 4]\) represents the predicted locations of all anchors. \(N\) is the batch size( the number of images in a minibatch), \(M\) is the number of all anchors of one image, and each anchor has 4 coordinate values. The data type of
bbox_pred
is float32 or float64.cls_logits (Variable) – A 3D Tensor with shape \([N, M, C]\) represents the predicted categories of all anchors. \(N\) is the batch size, \(M\) is the number of all anchors of one image, and \(C\) is the number of categories (Notice: excluding background). The data type of
cls_logits
is float32 or float64.anchor_box (Variable) – A 2D Tensor with shape \([M, 4]\) represents the locations of all anchors. \(M\) is the number of all anchors of one image, each anchor is represented as \([xmin, ymin, xmax, ymax]\), \([xmin, ymin]\) is the left top coordinate of the anchor box, \([xmax, ymax]\) is the right bottom coordinate of the anchor box. The data type of
anchor_box
is float32 or float64. Please refer to the OP anchor_generator for the generation ofanchor_box
.anchor_var (Variable) – A 2D Tensor with shape \([M,4]\) represents the expanded factors of anchor locations used in loss function. \(M\) is number of all anchors of one image, each anchor possesses a 4vector expanded factor. The data type of
anchor_var
is float32 or float64. Please refer to the OP anchor_generator for the generation ofanchor_var
.gt_boxes (Variable) – A 1level 2D LoDTensor with shape \([G, 4]\) represents locations of all groundtruth boxes. \(G\) is the total number of all groundtruth boxes in a minibatch, and each groundtruth box has 4 coordinate values. The data type of
gt_boxes
is float32 or float64.gt_labels (variable) – A 1level 2D LoDTensor with shape \([G, 1]\) represents categories of all groundtruth boxes, and the values are in the range of \([1, C]\). \(G\) is the total number of all groundtruth boxes in a minibatch, and each groundtruth box has one category. The data type of
gt_labels
is int32.is_crowd (Variable) – A 1level 1D LoDTensor with shape \([G]\) which indicates whether a groundtruth box is a crowd. If the value is 1, the corresponding box is a crowd, it is ignored during training. \(G\) is the total number of all groundtruth boxes in a minibatch. The data type of
is_crowd
is int32.im_info (Variable) – A 2D Tensor with shape [N, 3] represents the size information of input images. \(N\) is the batch size, the size informarion of each image is a 3vector which are the height and width of the network input along with the factor scaling the origin image to the network input. The data type of
im_info
is float32.num_classes (int32) – The number of categories for classification, the default value is 1.
positive_overlap (float32) – Minimum overlap required between an anchor and groundtruth box for the anchor to be a positive sample, the default value is 0.5.
negative_overlap (float32) – Maximum overlap allowed between an anchor and groundtruth box for the anchor to be a negative sample, the default value is 0.4.
negative_overlap
should be less than or equal topositive_overlap
, if not, the actual value ofpositive_overlap
isnegative_overlap
.
 Returns
predict_scores (Variable): A 2D Tensor with shape \([F+B, C]\) represents category prediction belonging to positive and negative samples. \(F\) is the number of positive samples in a minibatch, \(B\) is the number of negative samples, and \(C\) is the number of categories (Notice: excluding background). The data type of
predict_scores
is float32 or float64.predict_location (Variable): A 2D Tensor with shape \([F, 4]\) represents location prediction belonging to positive samples. \(F\) is the number of positive samples. \(F\) is the number of positive samples, and each sample has 4 coordinate values. The data type of
predict_location
is float32 or float64.target_label (Variable): A 2D Tensor with shape \([F+B, 1]\) represents target labels for classification belonging to positive and negative samples. \(F\) is the number of positive samples, \(B\) is the number of negative, and each sample has one target category. The data type of
target_label
is int32.target_bbox (Variable): A 2D Tensor with shape \([F, 4]\) represents target locations for box regression belonging to positive samples. \(F\) is the number of positive samples, and each sample has 4 coordinate values. The data type of
target_bbox
is float32 or float64.bbox_inside_weight (Variable): A 2D Tensor with shape \([F, 4]\) represents whether a positive sample is fake positive, if a positive sample is false positive, the corresponding entries in
bbox_inside_weight
are set 0, otherwise 1. \(F\) is the number of total positive samples in a minibatch, and each sample has 4 coordinate values. The data type ofbbox_inside_weight
is float32 or float64.fg_num (Variable): A 2D Tensor with shape \([N, 1]\) represents the number of positive samples. \(N\) is the batch size. Notice: The number of positive samples is used as the denominator of later loss function, to avoid the condition that the denominator is zero, this OP has added 1 to the actual number of positive samples of each image. The data type of
fg_num
is int32. Return type
A tuple with 6 Variables
Examples
import paddle.fluid as fluid bbox_pred = fluid.data(name='bbox_pred', shape=[1, 100, 4], dtype='float32') cls_logits = fluid.data(name='cls_logits', shape=[1, 100, 10], dtype='float32') anchor_box = fluid.data(name='anchor_box', shape=[100, 4], dtype='float32') anchor_var = fluid.data(name='anchor_var', shape=[100, 4], dtype='float32') gt_boxes = fluid.data(name='gt_boxes', shape=[10, 4], dtype='float32') gt_labels = fluid.data(name='gt_labels', shape=[10, 1], dtype='float32') is_crowd = fluid.data(name='is_crowd', shape=[1], dtype='float32') im_info = fluid.data(name='im_infoss', shape=[1, 3], dtype='float32') score_pred, loc_pred, score_target, loc_target, bbox_inside_weight, fg_num = fluid.layers.retinanet_target_assign(bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, gt_labels, is_crowd, im_info, 10)
roi_perspective_transform¶

paddle.fluid.layers.
roi_perspective_transform
(input, rois, transformed_height, transformed_width, spatial_scale=1.0, name=None)[source] The rois of this op should be a LoDTensor.
ROI perspective transform op applies perspective transform to map each roi into an rectangular region. Perspective transform is a type of transformation in linear algebra.
 Parameters
input (Variable) – 4D Tensor, input of ROIPerspectiveTransformOp. The format of input tensor is NCHW. Where N is batch size, C is the number of input channels, H is the height of the feature, and W is the width of the feature. The data type is float32.
rois (Variable) – 2D LoDTensor, ROIs (Regions of Interest) to be transformed. It should be a 2D LoDTensor of shape (num_rois, 8). Given as [[x1, y1, x2, y2, x3, y3, x4, y4], …], (x1, y1) is the top left coordinates, and (x2, y2) is the top right coordinates, and (x3, y3) is the bottom right coordinates, and (x4, y4) is the bottom left coordinates. The data type is the same as input
transformed_height (int) – The height of transformed output.
transformed_width (int) – The width of transformed output.
spatial_scale (float) – Spatial scale factor to scale ROI coords. Default: 1.0
name (str, optional) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name
 Returns
A tuple with three Variables. (out, mask, transform_matrix)
out: The output of ROIPerspectiveTransformOp which is a 4D tensor with shape (num_rois, channels, transformed_h, transformed_w). The data type is the same as input
mask: The mask of ROIPerspectiveTransformOp which is a 4D tensor with shape (num_rois, 1, transformed_h, transformed_w). The data type is int32
transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is a 2D tensor with shape (num_rois, 9). The data type is the same as input
 Return Type:
tuple
Examples
import paddle.fluid as fluid x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32') rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32') out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)
rpn_target_assign¶

paddle.fluid.layers.
rpn_target_assign
(bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, is_crowd, im_info, rpn_batch_size_per_im=256, rpn_straddle_thresh=0.0, rpn_fg_fraction=0.5, rpn_positive_overlap=0.7, rpn_negative_overlap=0.3, use_random=True)[source] Target Assign Layer for region proposal network (RPN) in FasterRCNN detection.
This layer can be, for given the IntersectionoverUnion (IoU) overlap between anchors and ground truth boxes, to assign classification and regression targets to each each anchor, these target labels are used for train RPN. The classification targets is a binary class label (of being an object or not). Following the paper of FasterRCNN, the positive labels are two kinds of anchors: (i) the anchor/anchors with the highest IoU overlap with a groundtruth box, or (ii) an anchor that has an IoU overlap higher than rpn_positive_overlap(0.7) with any groundtruth box. Note that a single groundtruth box may assign positive labels to multiple anchors. A nonpositive anchor is when its IoU ratio is lower than rpn_negative_overlap (0.3) for all groundtruth boxes. Anchors that are neither positive nor negative do not contribute to the training objective. The regression targets are the encoded groundtruth boxes associated with the positive anchors.
 Parameters
bbox_pred (Variable) – A 3D 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]. The data type can be float32 or float64.
cls_logits (Variable) – A 3D Tensor with shape [N, M, 1] represents the predicted confidence predictions. N is the batch size, 1 is the frontground and background sigmoid, M is number of bounding boxes. The data type can be float32 or float64.
anchor_box (Variable) – A 2D 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. The data type can be float32 or float64.
anchor_var (Variable) – A 2D Tensor with shape [M,4] holds expanded variances of anchors. The data type can be float32 or float64.
gt_boxes (Variable) – The groundtruth bounding boxes (bboxes) are a 2D LoDTensor with shape [Ng, 4], Ng is the total number of groundtruth bboxes of minibatch input. The data type can be float32 or float64.
is_crowd (Variable) – A 1D LoDTensor which indicates groudtruth is crowd. The data type must be int32.
im_info (Variable) – A 2D LoDTensor with shape [N, 3]. N is the batch size,
is the height, width and scale. (3) –
rpn_batch_size_per_im (int) – Total number of RPN examples per image. The data type must be int32.
rpn_straddle_thresh (float) – Remove RPN anchors that go outside the image by straddle_thresh pixels. The data type must be float32.
rpn_fg_fraction (float) – Target fraction of RoI minibatch that is labeled foreground (i.e. class > 0), 0th class is background. The data type must be float32.
rpn_positive_overlap (float) – Minimum overlap required between an anchor and groundtruth box for the (anchor, gt box) pair to be a positive example. The data type must be float32.
rpn_negative_overlap (float) – Maximum overlap allowed between an anchor and groundtruth box for the (anchor, gt box) pair to be a negative examples. The data type must be float32.
 Returns
A tuple(predicted_scores, predicted_location, target_label, target_bbox, bbox_inside_weight) is returned. The predicted_scores and predicted_location is the predicted result of the RPN. The target_label and target_bbox is the ground truth, respectively. The predicted_location is a 2D Tensor with shape [F, 4], and the shape of target_bbox is same as the shape of the predicted_location, F is the number of the foreground anchors. The predicted_scores is a 2D Tensor with shape [F + B, 1], and the shape of target_label is same as the shape of the predicted_scores, B is the number of the background anchors, the F and B is depends on the input of this operator. Bbox_inside_weight represents whether the predicted loc is fake_fg or not and the shape is [F, 4].
 Return type
tuple
Examples
import paddle.fluid as fluid bbox_pred = fluid.data(name='bbox_pred', shape=[None, 4], dtype='float32') cls_logits = fluid.data(name='cls_logits', shape=[None, 1], dtype='float32') anchor_box = fluid.data(name='anchor_box', shape=[None, 4], dtype='float32') anchor_var = fluid.data(name='anchor_var', shape=[None, 4], dtype='float32') gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32') is_crowd = fluid.data(name='is_crowd', shape=[None], dtype='float32') im_info = fluid.data(name='im_infoss', shape=[None, 3], dtype='float32') loc, score, loc_target, score_target, inside_weight = fluid.layers.rpn_target_assign( bbox_pred, cls_logits, anchor_box, anchor_var, gt_boxes, is_crowd, im_info)
sigmoid_focal_loss¶

paddle.fluid.layers.
sigmoid_focal_loss
(x, label, fg_num, gamma=2, alpha=0.25)[source] Sigmoid Focal Loss Operator.
Focal Loss is used to address the foregroundbackground class imbalance existed on the training phase of many computer vision tasks. This OP computes the sigmoid value for each element in the input tensor
x
, after which focal loss is measured between the sigmoid value and target label.The focal loss is given as followed:
\[\begin{split}\mathop{loss_{i,\,j}}\limits_{i\in\mathbb{[0,\,N1]},\,j\in\mathbb{[0,\,C1]}}=\left\{ \begin{array}{rcl}  \frac{1}{fg\_num} * \alpha * {(1  \sigma(x_{i,\,j}))}^{\gamma} * \log(\sigma(x_{i,\,j})) & & {(j +1) = label_{i,\,0}} \\  \frac{1}{fg\_num} * (1  \alpha) * {\sigma(x_{i,\,j})}^{ \gamma} * \log(1  \sigma(x_{i,\,j})) & & {(j +1)!= label_{i,\,0}} \end{array} \right.\end{split}\]We know that
\[\sigma(x_j) = \frac{1}{1 + \exp(x_j)}\] Parameters
x (Variable) – A 2D tensor with shape \([N, C]\) represents the predicted categories of all samples. \(N\) is the number of all samples responsible for optimization in a minibatch, for example, samples are anchor boxes for object detection and \(N\) is the total number of positive and negative samples in a minibatch; Samples are images for image classification and \(N\) is the number of images in a minibatch. \(C\) is the number of classes (Notice: excluding background). The data type of
x
is float32 or float64.label (Variable) – A 2D tensor with shape \([N, 1]\) represents the target labels for classification. \(N\) is the number of all samples responsible for optimization in a minibatch, each sample has one target category. The values for positive samples are in the range of \([1, C]\), and the values for negative samples are 0. The data type of
label
is int32.fg_num (Variable) – A 1D tensor with shape [1] represents the number of positive samples in a minibatch, which should be obtained before this OP. The data type of
fg_num
is int32.gamma (float) – Hyperparameter to balance the easy and hard examples. Default value is set to 2.0.
alpha (float) – Hyperparameter to balance the positive and negative example. Default value is set to 0.25.
 Returns
A 2D tensor with shape \([N, C]\), which is the focal loss of each element in the input tensor
x
. Return type
Variable(the data type is float32 or float64)
Examples
import paddle.fluid as fluid input = fluid.data(name='data', shape=[10,80], dtype='float32') label = fluid.data(name='label', shape=[10,1], dtype='int32') fg_num = fluid.data(name='fg_num', shape=[1], dtype='int32') loss = fluid.layers.sigmoid_focal_loss(x=input, label=label, fg_num=fg_num, gamma=2., alpha=0.25)
ssd_loss¶

paddle.fluid.layers.
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)[source] Multibox 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 groundtruth 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:
Find matched bounding box by bipartite matching algorithm.
1.1 Compute IOU similarity between groundtruth boxes and prior boxes.
1.2 Compute matched boundding box by bipartite matching algorithm.
Compute confidence for mining hard examples
2.1. Get the target label based on matched indices.
2.2. Compute confidence loss.
Apply hard example mining to get the negative example indices and update the matched indices.
Assign classification and regression targets
4.1. Encoded bbox according to the prior boxes.
4.2. Assign regression targets.
4.3. Assign classification targets.
Compute the overall objective loss.
5.1 Compute confidence loss.
5.2 Compute localization loss.
5.3 Compute the overall weighted loss.
 Parameters
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 groundtruth bounding boxes (bboxes) are a 2D LoDTensor with shape [Ng, 4], Ng is the total number of groundtruth bboxes of minibatch input.The data type is float32 or float64.
gt_label (Variable) – The groundtruth labels are a 2D LoDTensor with shape [Ng, 1].Ng is the total number of groundtruth bboxes of minibatch 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
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.
 Return type
Variable(Tensor)
 Raises
ValueError
– If mining_type is ‘hard_example’, now only support mining type of max_negative.
Examples
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)
target_assign¶

paddle.fluid.layers.
target_assign
(input, matched_indices, negative_indices=None, mismatch_value=None, name=None)[source] 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.
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:
Assigning all outputs based on match_indices:
If id = match_indices[i][j] > 0, out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K] out_weight[i][j] = 1. Otherwise, out[j][j][0 : K] = {mismatch_value, mismatch_value, ...} out_weight[i][j] = 0.
Assigning outputs based on neg_indices if neg_indices is provided:
Assumed that ith instance in neg_indices is called neg_indice, for ith instance:
for id in neg_indice: out[i][id][0 : K] = {mismatch_value, mismatch_value, ...} out_weight[i][id] = 1.0
 Parameters
input (Variable) – This input is a 3D LoDTensor with shape [M, P, K]. Data type should be int32 or float32.
matched_indices (Variable) – The input matched indices is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is 1, the jth entity of column is not matched to any entity of row in ith instance.
negative_indices (Variable, optional) – 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, optional) – Fill this value to the mismatched location.
name (string) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name.
 Returns
A tuple(out, out_weight) is returned.
out (Variable): a 3D Tensor with shape [N, P, K] and same data type with input, N and P is the same as they are in matched_indices, K is the same as it in input of X.
out_weight (Variable): the weight for output with the shape of [N, P, 1]. Data type is float32.
 Return type
tuple
Examples
import paddle.fluid as fluid x = fluid.data( name='x', shape=[4, 20, 4], dtype='float', lod_level=1) matched_id = fluid.data( name='indices', shape=[8, 20], dtype='int32') trg, trg_weight = fluid.layers.target_assign( x, matched_id, mismatch_value=0)
yolo_box¶

paddle.fluid.layers.
yolo_box
(x, img_size, anchors, class_num, conf_thresh, downsample_ratio, name=None)[source] This operator generates YOLO detection boxes from output of YOLOv3 network.
The output of previous network is in shape [N, C, H, W], while H and W should be the same, H and W specify the grid size, each grid point predict given number boxes, this given number, which following will be represented as S, is specified by the number of anchors. In the second dimension(the channel dimension), C should be equal to S * (5 + class_num), class_num is the object category number of source dataset(such as 80 in coco dataset), so the second(channel) dimension, apart from 4 box location coordinates x, y, w, h, also includes confidence score of the box and class onehot key of each anchor box.
Assume the 4 location coordinates are \(t_x, t_y, t_w, t_h\), the box predictions should be as follows:
$$ b_x = \sigma(t_x) + c_x $$ $$ b_y = \sigma(t_y) + c_y $$ $$ b_w = p_w e^{t_w} $$ $$ b_h = p_h e^{t_h} $$
in the equation above, \(c_x, c_y\) is the left top corner of current grid and \(p_w, p_h\) is specified by anchors.
The logistic regression value of the 5th channel of each anchor prediction boxes represents the confidence score of each prediction box, and the logistic regression value of the last
class_num
channels of each anchor prediction boxes represents the classifcation scores. Boxes with confidence scores less thanconf_thresh
should be ignored, and box final scores is the product of confidence scores and classification scores.$$ score_{pred} = score_{conf} * score_{class} $$
 Parameters
x (Variable) – The input tensor of YoloBox operator is a 4D tensor with shape of [N, C, H, W]. The second dimension(C) stores box locations, confidence score and classification onehot keys of each anchor box. Generally, X should be the output of YOLOv3 network The data type is float32 or float64.
img_size (Variable) – The image size tensor of YoloBox operator, This is a 2D tensor with shape of [N, 2]. This tensor holds height and width of each input image used for resizing output box in input image scale The data type is int32.
anchors (listtuple) – The anchor width and height, it will be parsed pair by pair
class_num (int) – The number of classes to predict
conf_thresh (float) – The confidence scores threshold of detection boxes. Boxes with confidence scores under threshold should be ignored
downsample_ratio (int) – The downsample ratio from network input to YoloBox operator input, so 32, 16, 8 should be set for the first, second, and thrid YoloBox operators
name (string) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name
 Returns
A 3D tensor with shape [N, M, 4], the coordinates of boxes, and a 3D tensor with shape [N, M,
class_num
], the classification scores of boxes. Return type
Variable
 Raises
TypeError
– Input x of yolov_box must be VariableTypeError
– Attr anchors of yolo box must be list or tupleTypeError
– Attr class_num of yolo box must be an integerTypeError
– Attr conf_thresh of yolo box must be a float number
Examples:
import paddle.fluid as fluid x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32') img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64') anchors = [10, 13, 16, 30, 33, 23] boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors, conf_thresh=0.01, downsample_ratio=32)
yolov3_loss¶

paddle.fluid.layers.
yolov3_loss
(x, gt_box, gt_label, anchors, anchor_mask, class_num, ignore_thresh, downsample_ratio, gt_score=None, use_label_smooth=True, name=None)[source] This operator generates yolov3 loss based on given predict result and ground truth boxes.
The output of previous network is in shape [N, C, H, W], while H and W should be the same, H and W specify the grid size, each grid point predict given number bounding boxes, this given number, which following will be represented as S, is specified by the number of anchor clusters in each scale. In the second dimension(the channel dimension), C should be equal to S * (class_num + 5), class_num is the object category number of source dataset(such as 80 in coco dataset), so in the second(channel) dimension, apart from 4 box location coordinates x, y, w, h, also includes confidence score of the box and class onehot key of each anchor box.
Assume the 4 location coordinates are \(t_x, t_y, t_w, t_h\), the box predictions should be as follows:
$$ b_x = \sigma(t_x) + c_x $$ $$ b_y = \sigma(t_y) + c_y $$ $$ b_w = p_w e^{t_w} $$ $$ b_h = p_h e^{t_h} $$
In the equation above, \(c_x, c_y\) is the left top corner of current grid and \(p_w, p_h\) is specified by anchors.
As for confidence score, it is the logistic regression value of IoU between anchor boxes and ground truth boxes, the score of the anchor box which has the max IoU should be 1, and if the anchor box has IoU bigger than ignore thresh, the confidence score loss of this anchor box will be ignored.
Therefore, the yolov3 loss consists of three major parts: box location loss, objectness loss and classification loss. The L1 loss is used for box coordinates (w, h), sigmoid cross entropy loss is used for box coordinates (x, y), objectness loss and classification loss.
Each groud truth box finds a best matching anchor box in all anchors. Prediction of this anchor box will incur all three parts of losses, and prediction of anchor boxes with no GT box matched will only incur objectness loss.
In order to trade off box coordinate losses between big boxes and small boxes, box coordinate losses will be mutiplied by scale weight, which is calculated as follows.
$$ weight_{box} = 2.0  t_w * t_h $$
Final loss will be represented as follows.
$$ loss = (loss_{xy} + loss_{wh}) * weight_{box} + loss_{conf} + loss_{class} $$
While
use_label_smooth
is set to beTrue
, the classification target will be smoothed when calculating classification loss, target of positive samples will be smoothed to \(1.0  1.0 / class\_num\) and target of negetive samples will be smoothed to \(1.0 / class\_num\).While
GTScore
is given, which means the mixup score of ground truth boxes, all losses incured by a ground truth box will be multiplied by its mixup score. Parameters
x (Variable) – The input tensor of YOLOv3 loss operator, This is a 4D tensor with shape of [N, C, H, W].H and W should be same, and the second dimention(C) storesbox locations, confidence score and classification onehotkeys of each anchor boxThe data type is float32 or float64.
gt_box (Variable) – groud truth boxes, should be in shape of [N, B, 4], in the third dimenstion, x, y, w, h should be stored. x,y is the center cordinate of boxes, w, h are the width and height, x, y, w, h should be divided by input image height to scale to [0, 1]. N is the batch number and B is the max box number in an image.The data type is float32 or float64.
gt_label (Variable) – class id of ground truth boxes, shoud be in shape of [N, B].The data type is int32.
anchors (listtuple) – The anchor width and height, it will be parsed pair by pair
anchor_mask (listtuple) – The mask index of anchors used in current YOLOv3 loss calculation
class_num (int) – The number of classes to predict
ignore_thresh (float) – The ignore threshold to ignore confidence loss
downsample_ratio (int) – The downsample ratio from network input to YOLOv3 loss input, so 32, 16, 8 should be set for the first, second, and thrid YOLOv3 loss operators
name (string) – The default value is None. Normally there is no need for user to set this property. For more information, please refer to api_guide_Name
gt_score (Variable) – mixup score of ground truth boxes, shoud be in shape of [N, B]. Default None.
use_label_smooth (bool) – Whether to use label smooth. Default True
 Returns
A 1D tensor with shape [N], the value of yolov3 loss
 Return type
Variable
 Raises
TypeError
– Input x of yolov3_loss must be VariableTypeError
– Input gtbox of yolov3_loss must be VariableTypeError
– Input gtlabel of yolov3_loss must be VariableTypeError
– Input gtscore of yolov3_loss must be None or VariableTypeError
– Attr anchors of yolov3_loss must be list or tupleTypeError
– Attr class_num of yolov3_loss must be an integerTypeError
– Attr ignore_thresh of yolov3_loss must be a float numberTypeError
– Attr use_label_smooth of yolov3_loss must be a bool value
Examples
import paddle.fluid as fluid x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32') gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32') gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32') gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32') anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326] anchor_mask = [0, 1, 2] loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label, gt_score=gt_score, anchors=anchors, anchor_mask=anchor_mask, class_num=80, ignore_thresh=0.7, downsample_ratio=32)