body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
---|---|---|---|---|---|---|---|
def sigmoid_focal_loss(x, label, fg_num, gamma=2.0, alpha=0.25):
'\n\t:alias_main: paddle.nn.functional.sigmoid_focal_loss\n\t:alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss\n\t:old_api: paddle.fluid.layers.sigmoid_focal_loss\n\n **Sigmoid Focal Loss Operator.**\n\n `Focal Loss <https://arxiv.org/abs/1708.02002>`_ is used to address the foreground-background\n class imbalance existed on the training phase of many computer vision tasks. This OP computes\n the sigmoid value for each element in the input tensor :attr:`x`, after which focal loss is\n measured between the sigmoid value and target label. \n\n The focal loss is given as followed:\n\n .. math::\n \n \\mathop{loss_{i,\\,j}}\\limits_{i\\in\\mathbb{[0,\\,N-1]},\\,j\\in\\mathbb{[0,\\,C-1]}}=\\left\\{\n \\begin{array}{rcl}\n - \\frac{1}{fg\\_num} * \\alpha * {(1 - \\sigma(x_{i,\\,j}))}^{\\gamma} * \\log(\\sigma(x_{i,\\,j})) & & {(j +1) = label_{i,\\,0}} \\\\\n - \\frac{1}{fg\\_num} * (1 - \\alpha) * {\\sigma(x_{i,\\,j})}^{ \\gamma} * \\log(1 - \\sigma(x_{i,\\,j})) & & {(j +1)!= label_{i,\\,0}}\n \\end{array} \\right.\n\n\n We know that\n \n .. math::\n \\sigma(x_j) = \\frac{1}{1 + \\exp(-x_j)}\n\n\n Args:\n x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of\n all samples. :math:`N` is the number of all samples responsible for optimization in\n a mini-batch, for example, samples are anchor boxes for object detection and :math:`N`\n is the total number of positive and negative samples in a mini-batch; Samples are images\n for image classification and :math:`N` is the number of images in a mini-batch. :math:`C`\n is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is\n float32 or float64.\n label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for\n classification. :math:`N` is the number of all samples responsible for optimization in a\n mini-batch, each sample has one target category. The values for positive samples are in the\n range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label`\n is int32.\n fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a\n mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32.\n gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is\n set to 2.0.\n alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value\n is set to 0.25.\n\n Returns:\n Variable(the data type is float32 or float64): \n A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input\n tensor :attr:`x`.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle.fluid as fluid\n \n num_classes = 10 # exclude background\n image_width = 16\n image_height = 16\n batch_size = 32\n max_iter = 20\n \n \n def gen_train_data():\n x_data = np.random.uniform(0, 255, (batch_size, 3, image_height,\n image_width)).astype(\'float64\')\n label_data = np.random.randint(0, num_classes,\n (batch_size, 1)).astype(\'int32\')\n return {"x": x_data, "label": label_data}\n \n \n def get_focal_loss(pred, label, fg_num, num_classes):\n pred = fluid.layers.reshape(pred, [-1, num_classes])\n label = fluid.layers.reshape(label, [-1, 1])\n label.stop_gradient = True\n loss = fluid.layers.sigmoid_focal_loss(\n pred, label, fg_num, gamma=2.0, alpha=0.25)\n loss = fluid.layers.reduce_sum(loss)\n return loss\n \n \n def build_model(mode=\'train\'):\n x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype=\'float64\')\n output = fluid.layers.pool2d(input=x, pool_type=\'avg\', global_pooling=True)\n output = fluid.layers.fc(\n input=output,\n size=num_classes,\n # Notice: size is set to be the number of target classes (excluding backgorund)\n # because sigmoid activation will be done in the sigmoid_focal_loss op.\n act=None)\n if mode == \'train\':\n label = fluid.data(name="label", shape=[-1, 1], dtype=\'int32\')\n # Obtain the fg_num needed by the sigmoid_focal_loss op:\n # 0 in label represents background, >=1 in label represents foreground,\n # find the elements in label which are greater or equal than 1, then\n # computed the numbers of these elements.\n data = fluid.layers.fill_constant(shape=[1], value=1, dtype=\'int32\')\n fg_label = fluid.layers.greater_equal(label, data)\n fg_label = fluid.layers.cast(fg_label, dtype=\'int32\')\n fg_num = fluid.layers.reduce_sum(fg_label)\n fg_num.stop_gradient = True\n avg_loss = get_focal_loss(output, label, fg_num, num_classes)\n return avg_loss\n else:\n # During evaluating or testing phase,\n # output of the final fc layer should be connected to a sigmoid layer.\n pred = fluid.layers.sigmoid(output)\n return pred\n \n \n loss = build_model(\'train\')\n moment_optimizer = fluid.optimizer.MomentumOptimizer(\n learning_rate=0.001, momentum=0.9)\n moment_optimizer.minimize(loss)\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n for i in range(max_iter):\n outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name])\n print(outs)\n '
check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'sigmoid_focal_loss')
check_variable_and_dtype(label, 'label', ['int32'], 'sigmoid_focal_loss')
check_variable_and_dtype(fg_num, 'fg_num', ['int32'], 'sigmoid_focal_loss')
helper = LayerHelper('sigmoid_focal_loss', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(type='sigmoid_focal_loss', inputs={'X': x, 'Label': label, 'FgNum': fg_num}, attrs={'gamma': gamma, 'alpha': alpha}, outputs={'Out': out})
return out | -185,429,799,281,533,660 | :alias_main: paddle.nn.functional.sigmoid_focal_loss
:alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss
:old_api: paddle.fluid.layers.sigmoid_focal_loss
**Sigmoid Focal Loss Operator.**
`Focal Loss <https://arxiv.org/abs/1708.02002>`_ is used to address the foreground-background
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 :attr:`x`, after which focal loss is
measured between the sigmoid value and target label.
The focal loss is given as followed:
.. math::
\mathop{loss_{i,\,j}}\limits_{i\in\mathbb{[0,\,N-1]},\,j\in\mathbb{[0,\,C-1]}}=\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.
We know that
.. math::
\sigma(x_j) = \frac{1}{1 + \exp(-x_j)}
Args:
x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of
all samples. :math:`N` is the number of all samples responsible for optimization in
a mini-batch, for example, samples are anchor boxes for object detection and :math:`N`
is the total number of positive and negative samples in a mini-batch; Samples are images
for image classification and :math:`N` is the number of images in a mini-batch. :math:`C`
is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is
float32 or float64.
label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for
classification. :math:`N` is the number of all samples responsible for optimization in a
mini-batch, each sample has one target category. The values for positive samples are in the
range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label`
is int32.
fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a
mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32.
gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is
set to 2.0.
alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value
is set to 0.25.
Returns:
Variable(the data type is float32 or float64):
A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input
tensor :attr:`x`.
Examples:
.. code-block:: python
import numpy as np
import paddle.fluid as fluid
num_classes = 10 # exclude background
image_width = 16
image_height = 16
batch_size = 32
max_iter = 20
def gen_train_data():
x_data = np.random.uniform(0, 255, (batch_size, 3, image_height,
image_width)).astype('float64')
label_data = np.random.randint(0, num_classes,
(batch_size, 1)).astype('int32')
return {"x": x_data, "label": label_data}
def get_focal_loss(pred, label, fg_num, num_classes):
pred = fluid.layers.reshape(pred, [-1, num_classes])
label = fluid.layers.reshape(label, [-1, 1])
label.stop_gradient = True
loss = fluid.layers.sigmoid_focal_loss(
pred, label, fg_num, gamma=2.0, alpha=0.25)
loss = fluid.layers.reduce_sum(loss)
return loss
def build_model(mode='train'):
x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype='float64')
output = fluid.layers.pool2d(input=x, pool_type='avg', global_pooling=True)
output = fluid.layers.fc(
input=output,
size=num_classes,
# Notice: size is set to be the number of target classes (excluding backgorund)
# because sigmoid activation will be done in the sigmoid_focal_loss op.
act=None)
if mode == 'train':
label = fluid.data(name="label", shape=[-1, 1], dtype='int32')
# Obtain the fg_num needed by the sigmoid_focal_loss op:
# 0 in label represents background, >=1 in label represents foreground,
# find the elements in label which are greater or equal than 1, then
# computed the numbers of these elements.
data = fluid.layers.fill_constant(shape=[1], value=1, dtype='int32')
fg_label = fluid.layers.greater_equal(label, data)
fg_label = fluid.layers.cast(fg_label, dtype='int32')
fg_num = fluid.layers.reduce_sum(fg_label)
fg_num.stop_gradient = True
avg_loss = get_focal_loss(output, label, fg_num, num_classes)
return avg_loss
else:
# During evaluating or testing phase,
# output of the final fc layer should be connected to a sigmoid layer.
pred = fluid.layers.sigmoid(output)
return pred
loss = build_model('train')
moment_optimizer = fluid.optimizer.MomentumOptimizer(
learning_rate=0.001, momentum=0.9)
moment_optimizer.minimize(loss)
place = fluid.CPUPlace()
exe = fluid.Executor(place)
exe.run(fluid.default_startup_program())
for i in range(max_iter):
outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name])
print(outs) | python/paddle/fluid/layers/detection.py | sigmoid_focal_loss | 92lqllearning/Paddle | python | def sigmoid_focal_loss(x, label, fg_num, gamma=2.0, alpha=0.25):
'\n\t:alias_main: paddle.nn.functional.sigmoid_focal_loss\n\t:alias: paddle.nn.functional.sigmoid_focal_loss,paddle.nn.functional.loss.sigmoid_focal_loss\n\t:old_api: paddle.fluid.layers.sigmoid_focal_loss\n\n **Sigmoid Focal Loss Operator.**\n\n `Focal Loss <https://arxiv.org/abs/1708.02002>`_ is used to address the foreground-background\n class imbalance existed on the training phase of many computer vision tasks. This OP computes\n the sigmoid value for each element in the input tensor :attr:`x`, after which focal loss is\n measured between the sigmoid value and target label. \n\n The focal loss is given as followed:\n\n .. math::\n \n \\mathop{loss_{i,\\,j}}\\limits_{i\\in\\mathbb{[0,\\,N-1]},\\,j\\in\\mathbb{[0,\\,C-1]}}=\\left\\{\n \\begin{array}{rcl}\n - \\frac{1}{fg\\_num} * \\alpha * {(1 - \\sigma(x_{i,\\,j}))}^{\\gamma} * \\log(\\sigma(x_{i,\\,j})) & & {(j +1) = label_{i,\\,0}} \\\\\n - \\frac{1}{fg\\_num} * (1 - \\alpha) * {\\sigma(x_{i,\\,j})}^{ \\gamma} * \\log(1 - \\sigma(x_{i,\\,j})) & & {(j +1)!= label_{i,\\,0}}\n \\end{array} \\right.\n\n\n We know that\n \n .. math::\n \\sigma(x_j) = \\frac{1}{1 + \\exp(-x_j)}\n\n\n Args:\n x(Variable): A 2-D tensor with shape :math:`[N, C]` represents the predicted categories of\n all samples. :math:`N` is the number of all samples responsible for optimization in\n a mini-batch, for example, samples are anchor boxes for object detection and :math:`N`\n is the total number of positive and negative samples in a mini-batch; Samples are images\n for image classification and :math:`N` is the number of images in a mini-batch. :math:`C`\n is the number of classes (**Notice: excluding background**). The data type of :attr:`x` is\n float32 or float64.\n label(Variable): A 2-D tensor with shape :math:`[N, 1]` represents the target labels for\n classification. :math:`N` is the number of all samples responsible for optimization in a\n mini-batch, each sample has one target category. The values for positive samples are in the\n range of :math:`[1, C]`, and the values for negative samples are 0. The data type of :attr:`label`\n is int32.\n fg_num(Variable): A 1-D tensor with shape [1] represents the number of positive samples in a\n mini-batch, which should be obtained before this OP. The data type of :attr:`fg_num` is int32.\n gamma(int|float): Hyper-parameter to balance the easy and hard examples. Default value is\n set to 2.0.\n alpha(int|float): Hyper-parameter to balance the positive and negative example. Default value\n is set to 0.25.\n\n Returns:\n Variable(the data type is float32 or float64): \n A 2-D tensor with shape :math:`[N, C]`, which is the focal loss of each element in the input\n tensor :attr:`x`.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle.fluid as fluid\n \n num_classes = 10 # exclude background\n image_width = 16\n image_height = 16\n batch_size = 32\n max_iter = 20\n \n \n def gen_train_data():\n x_data = np.random.uniform(0, 255, (batch_size, 3, image_height,\n image_width)).astype(\'float64\')\n label_data = np.random.randint(0, num_classes,\n (batch_size, 1)).astype(\'int32\')\n return {"x": x_data, "label": label_data}\n \n \n def get_focal_loss(pred, label, fg_num, num_classes):\n pred = fluid.layers.reshape(pred, [-1, num_classes])\n label = fluid.layers.reshape(label, [-1, 1])\n label.stop_gradient = True\n loss = fluid.layers.sigmoid_focal_loss(\n pred, label, fg_num, gamma=2.0, alpha=0.25)\n loss = fluid.layers.reduce_sum(loss)\n return loss\n \n \n def build_model(mode=\'train\'):\n x = fluid.data(name="x", shape=[-1, 3, -1, -1], dtype=\'float64\')\n output = fluid.layers.pool2d(input=x, pool_type=\'avg\', global_pooling=True)\n output = fluid.layers.fc(\n input=output,\n size=num_classes,\n # Notice: size is set to be the number of target classes (excluding backgorund)\n # because sigmoid activation will be done in the sigmoid_focal_loss op.\n act=None)\n if mode == \'train\':\n label = fluid.data(name="label", shape=[-1, 1], dtype=\'int32\')\n # Obtain the fg_num needed by the sigmoid_focal_loss op:\n # 0 in label represents background, >=1 in label represents foreground,\n # find the elements in label which are greater or equal than 1, then\n # computed the numbers of these elements.\n data = fluid.layers.fill_constant(shape=[1], value=1, dtype=\'int32\')\n fg_label = fluid.layers.greater_equal(label, data)\n fg_label = fluid.layers.cast(fg_label, dtype=\'int32\')\n fg_num = fluid.layers.reduce_sum(fg_label)\n fg_num.stop_gradient = True\n avg_loss = get_focal_loss(output, label, fg_num, num_classes)\n return avg_loss\n else:\n # During evaluating or testing phase,\n # output of the final fc layer should be connected to a sigmoid layer.\n pred = fluid.layers.sigmoid(output)\n return pred\n \n \n loss = build_model(\'train\')\n moment_optimizer = fluid.optimizer.MomentumOptimizer(\n learning_rate=0.001, momentum=0.9)\n moment_optimizer.minimize(loss)\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n for i in range(max_iter):\n outs = exe.run(feed=gen_train_data(), fetch_list=[loss.name])\n print(outs)\n '
check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'sigmoid_focal_loss')
check_variable_and_dtype(label, 'label', ['int32'], 'sigmoid_focal_loss')
check_variable_and_dtype(fg_num, 'fg_num', ['int32'], 'sigmoid_focal_loss')
helper = LayerHelper('sigmoid_focal_loss', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(type='sigmoid_focal_loss', inputs={'X': x, 'Label': label, 'FgNum': fg_num}, attrs={'gamma': gamma, 'alpha': alpha}, outputs={'Out': out})
return out |
def 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):
"\n\t:alias_main: paddle.nn.functional.detection_output\n\t:alias: paddle.nn.functional.detection_output,paddle.nn.functional.vision.detection_output\n\t:old_api: paddle.fluid.layers.detection_output\n\n Given the regression locations, classification confidences and prior boxes,\n calculate the detection outputs by performing following steps:\n\n 1. Decode input bounding box predictions according to the prior boxes and\n regression locations.\n 2. Get the final detection results by applying multi-class non maximum\n suppression (NMS).\n\n Please note, this operation doesn't clip the final output bounding boxes\n to the image window.\n\n Args:\n loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the\n predicted locations of M bounding bboxes. Data type should be\n float32 or float64. N is the batch size,\n and each bounding box has four coordinate values and the layout\n is [xmin, ymin, xmax, ymax].\n scores(Variable): A 3-D Tensor with shape [N, M, C] represents the\n predicted confidence predictions. Data type should be float32\n or float64. N is the batch size, C is the\n class number, M is number of bounding boxes.\n prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,\n each box is represented as [xmin, ymin, xmax, ymax]. Data type\n should be float32 or float64.\n prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group\n of variance. Data type should be float32 or float64.\n background_label(int): The index of background label,\n the background label will be ignored. If set to -1, then all\n categories will be considered. Default: 0.\n nms_threshold(float): The threshold to be used in NMS. Default: 0.3.\n nms_top_k(int): Maximum number of detections to be kept according\n to the confidences after filtering detections based on\n score_threshold and before NMS. Default: 400.\n keep_top_k(int): Number of total bboxes to be kept per image after\n NMS step. -1 means keeping all bboxes after NMS step. Default: 200.\n score_threshold(float): Threshold to filter out bounding boxes with\n low confidence score. If not provided, consider all boxes.\n Default: 0.01.\n nms_eta(float): The parameter for adaptive NMS. It works only when the\n value is less than 1.0. Default: 1.0.\n return_index(bool): Whether return selected index. Default: False\n\n Returns:\n\n A tuple with two Variables: (Out, Index) if return_index is True,\n otherwise, a tuple with one Variable(Out) is returned. \n\n Out (Variable): The detection outputs is a LoDTensor with shape [No, 6].\n Data type is the same as input (loc). Each row has six values:\n [label, confidence, xmin, ymin, xmax, ymax]. `No` is\n the total number of detections in this mini-batch. For each instance,\n the offsets in first dimension are called LoD, the offset number is\n N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]`\n detected results, if it is 0, the i-th image has no detected results.\n\n Index (Variable): Only return when return_index is True. A 2-D LoDTensor\n with shape [No, 1] represents the selected index which type is Integer.\n The index is the absolute value cross batches. No is the same number\n as Out. If the index is used to gather other attribute such as age,\n one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where\n N is the batch size and M is the number of boxes.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32')\n pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32')\n loc = fluid.data(name='target_box', shape=[2, 21, 4], dtype='float32')\n scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32')\n nmsed_outs, index = fluid.layers.detection_output(scores=scores,\n loc=loc,\n prior_box=pb,\n prior_box_var=pbv,\n return_index=True)\n "
helper = LayerHelper('detection_output', **locals())
decoded_box = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=loc, code_type='decode_center_size')
scores = nn.softmax(input=scores)
scores = nn.transpose(scores, perm=[0, 2, 1])
scores.stop_gradient = True
nmsed_outs = helper.create_variable_for_type_inference(dtype=decoded_box.dtype)
if return_index:
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(type='multiclass_nms2', inputs={'Scores': scores, 'BBoxes': decoded_box}, outputs={'Out': nmsed_outs, 'Index': index}, attrs={'background_label': 0, 'nms_threshold': nms_threshold, 'nms_top_k': nms_top_k, 'keep_top_k': keep_top_k, 'score_threshold': score_threshold, 'nms_eta': 1.0})
index.stop_gradient = True
else:
helper.append_op(type='multiclass_nms', inputs={'Scores': scores, 'BBoxes': decoded_box}, outputs={'Out': nmsed_outs}, attrs={'background_label': 0, 'nms_threshold': nms_threshold, 'nms_top_k': nms_top_k, 'keep_top_k': keep_top_k, 'score_threshold': score_threshold, 'nms_eta': 1.0})
nmsed_outs.stop_gradient = True
if return_index:
return (nmsed_outs, index)
return nmsed_outs | 3,502,451,009,088,788,000 | :alias_main: paddle.nn.functional.detection_output
:alias: paddle.nn.functional.detection_output,paddle.nn.functional.vision.detection_output
:old_api: paddle.fluid.layers.detection_output
Given the regression locations, classification confidences and prior boxes,
calculate the detection outputs by performing following steps:
1. Decode input bounding box predictions according to the prior boxes and
regression locations.
2. Get the final detection results by applying multi-class non maximum
suppression (NMS).
Please note, this operation doesn't clip the final output bounding boxes
to the image window.
Args:
loc(Variable): A 3-D 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 3-D 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 2-D 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 2-D 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 after 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:
A tuple with two Variables: (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 mini-batch. For each instance,
the offsets in first dimension are called LoD, the offset number is
N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]`
detected results, if it is 0, the i-th image has no detected results.
Index (Variable): Only return when return_index is True. A 2-D 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.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32')
pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32')
loc = fluid.data(name='target_box', shape=[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) | python/paddle/fluid/layers/detection.py | detection_output | 92lqllearning/Paddle | python | def 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):
"\n\t:alias_main: paddle.nn.functional.detection_output\n\t:alias: paddle.nn.functional.detection_output,paddle.nn.functional.vision.detection_output\n\t:old_api: paddle.fluid.layers.detection_output\n\n Given the regression locations, classification confidences and prior boxes,\n calculate the detection outputs by performing following steps:\n\n 1. Decode input bounding box predictions according to the prior boxes and\n regression locations.\n 2. Get the final detection results by applying multi-class non maximum\n suppression (NMS).\n\n Please note, this operation doesn't clip the final output bounding boxes\n to the image window.\n\n Args:\n loc(Variable): A 3-D Tensor with shape [N, M, 4] represents the\n predicted locations of M bounding bboxes. Data type should be\n float32 or float64. N is the batch size,\n and each bounding box has four coordinate values and the layout\n is [xmin, ymin, xmax, ymax].\n scores(Variable): A 3-D Tensor with shape [N, M, C] represents the\n predicted confidence predictions. Data type should be float32\n or float64. N is the batch size, C is the\n class number, M is number of bounding boxes.\n prior_box(Variable): A 2-D Tensor with shape [M, 4] holds M boxes,\n each box is represented as [xmin, ymin, xmax, ymax]. Data type\n should be float32 or float64.\n prior_box_var(Variable): A 2-D Tensor with shape [M, 4] holds M group\n of variance. Data type should be float32 or float64.\n background_label(int): The index of background label,\n the background label will be ignored. If set to -1, then all\n categories will be considered. Default: 0.\n nms_threshold(float): The threshold to be used in NMS. Default: 0.3.\n nms_top_k(int): Maximum number of detections to be kept according\n to the confidences after filtering detections based on\n score_threshold and before NMS. Default: 400.\n keep_top_k(int): Number of total bboxes to be kept per image after\n NMS step. -1 means keeping all bboxes after NMS step. Default: 200.\n score_threshold(float): Threshold to filter out bounding boxes with\n low confidence score. If not provided, consider all boxes.\n Default: 0.01.\n nms_eta(float): The parameter for adaptive NMS. It works only when the\n value is less than 1.0. Default: 1.0.\n return_index(bool): Whether return selected index. Default: False\n\n Returns:\n\n A tuple with two Variables: (Out, Index) if return_index is True,\n otherwise, a tuple with one Variable(Out) is returned. \n\n Out (Variable): The detection outputs is a LoDTensor with shape [No, 6].\n Data type is the same as input (loc). Each row has six values:\n [label, confidence, xmin, ymin, xmax, ymax]. `No` is\n the total number of detections in this mini-batch. For each instance,\n the offsets in first dimension are called LoD, the offset number is\n N + 1, N is the batch size. The i-th image has `LoD[i + 1] - LoD[i]`\n detected results, if it is 0, the i-th image has no detected results.\n\n Index (Variable): Only return when return_index is True. A 2-D LoDTensor\n with shape [No, 1] represents the selected index which type is Integer.\n The index is the absolute value cross batches. No is the same number\n as Out. If the index is used to gather other attribute such as age,\n one needs to reshape the input(N, M, 1) to (N * M, 1) as first, where\n N is the batch size and M is the number of boxes.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n pb = fluid.data(name='prior_box', shape=[10, 4], dtype='float32')\n pbv = fluid.data(name='prior_box_var', shape=[10, 4], dtype='float32')\n loc = fluid.data(name='target_box', shape=[2, 21, 4], dtype='float32')\n scores = fluid.data(name='scores', shape=[2, 21, 10], dtype='float32')\n nmsed_outs, index = fluid.layers.detection_output(scores=scores,\n loc=loc,\n prior_box=pb,\n prior_box_var=pbv,\n return_index=True)\n "
helper = LayerHelper('detection_output', **locals())
decoded_box = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=loc, code_type='decode_center_size')
scores = nn.softmax(input=scores)
scores = nn.transpose(scores, perm=[0, 2, 1])
scores.stop_gradient = True
nmsed_outs = helper.create_variable_for_type_inference(dtype=decoded_box.dtype)
if return_index:
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(type='multiclass_nms2', inputs={'Scores': scores, 'BBoxes': decoded_box}, outputs={'Out': nmsed_outs, 'Index': index}, attrs={'background_label': 0, 'nms_threshold': nms_threshold, 'nms_top_k': nms_top_k, 'keep_top_k': keep_top_k, 'score_threshold': score_threshold, 'nms_eta': 1.0})
index.stop_gradient = True
else:
helper.append_op(type='multiclass_nms', inputs={'Scores': scores, 'BBoxes': decoded_box}, outputs={'Out': nmsed_outs}, attrs={'background_label': 0, 'nms_threshold': nms_threshold, 'nms_top_k': nms_top_k, 'keep_top_k': keep_top_k, 'score_threshold': score_threshold, 'nms_eta': 1.0})
nmsed_outs.stop_gradient = True
if return_index:
return (nmsed_outs, index)
return nmsed_outs |
@templatedoc()
def iou_similarity(x, y, box_normalized=True, name=None):
"\n\t:alias_main: paddle.nn.functional.iou_similarity\n\t:alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity\n\t:old_api: paddle.fluid.layers.iou_similarity\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment}.The data type is float32 or float64.\n y (Variable): ${y_comment}.The data type is float32 or float64.\n box_normalized(bool): Whether treat the priorbox as a normalized box.\n Set true by default.\n Returns:\n Variable: ${out_comment}.The data type is same with x.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle.fluid as fluid\n\n use_gpu = False\n place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()\n exe = fluid.Executor(place)\n\n x = fluid.data(name='x', shape=[None, 4], dtype='float32')\n y = fluid.data(name='y', shape=[None, 4], dtype='float32')\n iou = fluid.layers.iou_similarity(x=x, y=y)\n\n exe.run(fluid.default_startup_program())\n test_program = fluid.default_main_program().clone(for_test=True)\n\n [out_iou] = exe.run(test_program,\n fetch_list=iou,\n feed={'x': np.array([[0.5, 0.5, 2.0, 2.0],\n [0., 0., 1.0, 1.0]]).astype('float32'),\n 'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')})\n # out_iou is [[0.2857143],\n # [0. ]] with shape: [2, 1]\n "
helper = LayerHelper('iou_similarity', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(type='iou_similarity', inputs={'X': x, 'Y': y}, attrs={'box_normalized': box_normalized}, outputs={'Out': out})
return out | -1,729,417,256,943,608,600 | :alias_main: paddle.nn.functional.iou_similarity
:alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity
:old_api: paddle.fluid.layers.iou_similarity
${comment}
Args:
x (Variable): ${x_comment}.The data type is float32 or float64.
y (Variable): ${y_comment}.The data type is float32 or float64.
box_normalized(bool): Whether treat the priorbox as a normalized box.
Set true by default.
Returns:
Variable: ${out_comment}.The data type is same with x.
Examples:
.. code-block:: python
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] | python/paddle/fluid/layers/detection.py | iou_similarity | 92lqllearning/Paddle | python | @templatedoc()
def iou_similarity(x, y, box_normalized=True, name=None):
"\n\t:alias_main: paddle.nn.functional.iou_similarity\n\t:alias: paddle.nn.functional.iou_similarity,paddle.nn.functional.loss.iou_similarity\n\t:old_api: paddle.fluid.layers.iou_similarity\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment}.The data type is float32 or float64.\n y (Variable): ${y_comment}.The data type is float32 or float64.\n box_normalized(bool): Whether treat the priorbox as a normalized box.\n Set true by default.\n Returns:\n Variable: ${out_comment}.The data type is same with x.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle.fluid as fluid\n\n use_gpu = False\n place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()\n exe = fluid.Executor(place)\n\n x = fluid.data(name='x', shape=[None, 4], dtype='float32')\n y = fluid.data(name='y', shape=[None, 4], dtype='float32')\n iou = fluid.layers.iou_similarity(x=x, y=y)\n\n exe.run(fluid.default_startup_program())\n test_program = fluid.default_main_program().clone(for_test=True)\n\n [out_iou] = exe.run(test_program,\n fetch_list=iou,\n feed={'x': np.array([[0.5, 0.5, 2.0, 2.0],\n [0., 0., 1.0, 1.0]]).astype('float32'),\n 'y': np.array([[1.0, 1.0, 2.5, 2.5]]).astype('float32')})\n # out_iou is [[0.2857143],\n # [0. ]] with shape: [2, 1]\n "
helper = LayerHelper('iou_similarity', **locals())
out = helper.create_variable_for_type_inference(dtype=x.dtype)
helper.append_op(type='iou_similarity', inputs={'X': x, 'Y': y}, attrs={'box_normalized': box_normalized}, outputs={'Out': out})
return out |
@templatedoc()
def box_coder(prior_box, prior_box_var, target_box, code_type='encode_center_size', box_normalized=True, name=None, axis=0):
'\n\t:alias_main: paddle.nn.functional.box_coder\n\t:alias: paddle.nn.functional.box_coder,paddle.nn.functional.vision.box_coder\n\t:old_api: paddle.fluid.layers.box_coder\n\n **Box Coder Layer**\n\n Encode/Decode the target bounding box with the priorbox information.\n \n The Encoding schema described below:\n\n .. math::\n\n ox = (tx - px) / pw / pxv\n\n oy = (ty - py) / ph / pyv\n\n ow = \\log(\x07bs(tw / pw)) / pwv \n\n oh = \\log(\x07bs(th / ph)) / phv \n\n The Decoding schema described below:\n \n .. math::\n \n ox = (pw * pxv * tx * + px) - tw / 2\n\n oy = (ph * pyv * ty * + py) - th / 2\n\n ow = \\exp(pwv * tw) * pw + tw / 2\n\n oh = \\exp(phv * th) * ph + th / 2 \n\n where `tx`, `ty`, `tw`, `th` denote the target box\'s center coordinates, \n width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote \n the priorbox\'s (anchor) center coordinates, width and height. `pxv`, \n `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`, \n `ow`, `oh` denote the encoded/decoded coordinates, width and height. \n\n During Box Decoding, two modes for broadcast are supported. Say target \n box has shape [N, M, 4], and the shape of prior box can be [N, 4] or \n [M, 4]. Then prior box will broadcast to target box along the \n assigned axis. \n\n Args:\n prior_box(Variable): Box list prior_box is a 2-D Tensor with shape \n [M, 4] holds M boxes and data type is float32 or float64. Each box\n is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the \n left top coordinate of the anchor box, if the input is image feature\n map, they are close to the origin of the coordinate system. \n [xmax, ymax] is the right bottom coordinate of the anchor box. \n prior_box_var(List|Variable|None): prior_box_var supports three types \n of input. One is variable with shape [M, 4] which holds M group and \n data type is float32 or float64. The second is list consist of \n 4 elements shared by all boxes and data type is float32 or float64. \n Other is None and not involved in calculation. \n target_box(Variable): This input can be a 2-D LoDTensor with shape \n [N, 4] when code_type is \'encode_center_size\'. This input also can \n be a 3-D Tensor with shape [N, M, 4] when code_type is \n \'decode_center_size\'. Each box is represented as \n [xmin, ymin, xmax, ymax]. The data type is float32 or float64. \n This tensor can contain LoD information to represent a batch of inputs. \n code_type(str): The code type used with the target box. It can be\n `encode_center_size` or `decode_center_size`. `encode_center_size` \n by default.\n box_normalized(bool): Whether treat the priorbox as a normalized box.\n Set true by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n axis(int): Which axis in PriorBox to broadcast for box decode, \n for example, if axis is 0 and TargetBox has shape [N, M, 4] and \n PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]\n for decoding. It is only valid when code type is \n `decode_center_size`. Set 0 by default. \n\n Returns:\n Variable:\n\n output_box(Variable): When code_type is \'encode_center_size\', the \n output tensor of box_coder_op with shape [N, M, 4] representing the \n result of N target boxes encoded with M Prior boxes and variances. \n When code_type is \'decode_center_size\', N represents the batch size \n and M represents the number of decoded boxes.\n\n Examples:\n \n .. code-block:: python\n \n import paddle.fluid as fluid\n # For encode\n prior_box_encode = fluid.data(name=\'prior_box_encode\',\n shape=[512, 4],\n dtype=\'float32\')\n target_box_encode = fluid.data(name=\'target_box_encode\',\n shape=[81, 4],\n dtype=\'float32\')\n output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,\n prior_box_var=[0.1,0.1,0.2,0.2],\n target_box=target_box_encode,\n code_type="encode_center_size")\n # For decode\n prior_box_decode = fluid.data(name=\'prior_box_decode\',\n shape=[512, 4],\n dtype=\'float32\')\n target_box_decode = fluid.data(name=\'target_box_decode\',\n shape=[512, 81, 4],\n dtype=\'float32\')\n output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,\n prior_box_var=[0.1,0.1,0.2,0.2],\n target_box=target_box_decode,\n code_type="decode_center_size",\n box_normalized=False,\n axis=1)\n '
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'], 'box_coder')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'], 'box_coder')
helper = LayerHelper('box_coder', **locals())
output_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
inputs = {'PriorBox': prior_box, 'TargetBox': target_box}
attrs = {'code_type': code_type, 'box_normalized': box_normalized, 'axis': axis}
if isinstance(prior_box_var, Variable):
inputs['PriorBoxVar'] = prior_box_var
elif isinstance(prior_box_var, list):
attrs['variance'] = prior_box_var
else:
raise TypeError('Input variance of box_coder must be Variable or lisz')
helper.append_op(type='box_coder', inputs=inputs, attrs=attrs, outputs={'OutputBox': output_box})
return output_box | 8,675,982,313,976,703,000 | :alias_main: paddle.nn.functional.box_coder
:alias: paddle.nn.functional.box_coder,paddle.nn.functional.vision.box_coder
:old_api: paddle.fluid.layers.box_coder
**Box Coder Layer**
Encode/Decode the target bounding box with the priorbox information.
The Encoding schema described below:
.. math::
ox = (tx - px) / pw / pxv
oy = (ty - py) / ph / pyv
ow = \log(bs(tw / pw)) / pwv
oh = \log(bs(th / ph)) / phv
The Decoding schema described below:
.. math::
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
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.
Args:
prior_box(Variable): Box list prior_box is a 2-D 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(List|Variable|None): 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 2-D LoDTensor with shape
[N, 4] when code_type is 'encode_center_size'. This input also can
be a 3-D 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 normalized box.
Set true by default.
name(str, optional): For detailed information, please refer
to :ref:`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:
Variable:
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 decoded boxes.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | box_coder | 92lqllearning/Paddle | python | @templatedoc()
def box_coder(prior_box, prior_box_var, target_box, code_type='encode_center_size', box_normalized=True, name=None, axis=0):
'\n\t:alias_main: paddle.nn.functional.box_coder\n\t:alias: paddle.nn.functional.box_coder,paddle.nn.functional.vision.box_coder\n\t:old_api: paddle.fluid.layers.box_coder\n\n **Box Coder Layer**\n\n Encode/Decode the target bounding box with the priorbox information.\n \n The Encoding schema described below:\n\n .. math::\n\n ox = (tx - px) / pw / pxv\n\n oy = (ty - py) / ph / pyv\n\n ow = \\log(\x07bs(tw / pw)) / pwv \n\n oh = \\log(\x07bs(th / ph)) / phv \n\n The Decoding schema described below:\n \n .. math::\n \n ox = (pw * pxv * tx * + px) - tw / 2\n\n oy = (ph * pyv * ty * + py) - th / 2\n\n ow = \\exp(pwv * tw) * pw + tw / 2\n\n oh = \\exp(phv * th) * ph + th / 2 \n\n where `tx`, `ty`, `tw`, `th` denote the target box\'s center coordinates, \n width and height respectively. Similarly, `px`, `py`, `pw`, `ph` denote \n the priorbox\'s (anchor) center coordinates, width and height. `pxv`, \n `pyv`, `pwv`, `phv` denote the variance of the priorbox and `ox`, `oy`, \n `ow`, `oh` denote the encoded/decoded coordinates, width and height. \n\n During Box Decoding, two modes for broadcast are supported. Say target \n box has shape [N, M, 4], and the shape of prior box can be [N, 4] or \n [M, 4]. Then prior box will broadcast to target box along the \n assigned axis. \n\n Args:\n prior_box(Variable): Box list prior_box is a 2-D Tensor with shape \n [M, 4] holds M boxes and data type is float32 or float64. Each box\n is represented as [xmin, ymin, xmax, ymax], [xmin, ymin] is the \n left top coordinate of the anchor box, if the input is image feature\n map, they are close to the origin of the coordinate system. \n [xmax, ymax] is the right bottom coordinate of the anchor box. \n prior_box_var(List|Variable|None): prior_box_var supports three types \n of input. One is variable with shape [M, 4] which holds M group and \n data type is float32 or float64. The second is list consist of \n 4 elements shared by all boxes and data type is float32 or float64. \n Other is None and not involved in calculation. \n target_box(Variable): This input can be a 2-D LoDTensor with shape \n [N, 4] when code_type is \'encode_center_size\'. This input also can \n be a 3-D Tensor with shape [N, M, 4] when code_type is \n \'decode_center_size\'. Each box is represented as \n [xmin, ymin, xmax, ymax]. The data type is float32 or float64. \n This tensor can contain LoD information to represent a batch of inputs. \n code_type(str): The code type used with the target box. It can be\n `encode_center_size` or `decode_center_size`. `encode_center_size` \n by default.\n box_normalized(bool): Whether treat the priorbox as a normalized box.\n Set true by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n axis(int): Which axis in PriorBox to broadcast for box decode, \n for example, if axis is 0 and TargetBox has shape [N, M, 4] and \n PriorBox has shape [M, 4], then PriorBox will broadcast to [N, M, 4]\n for decoding. It is only valid when code type is \n `decode_center_size`. Set 0 by default. \n\n Returns:\n Variable:\n\n output_box(Variable): When code_type is \'encode_center_size\', the \n output tensor of box_coder_op with shape [N, M, 4] representing the \n result of N target boxes encoded with M Prior boxes and variances. \n When code_type is \'decode_center_size\', N represents the batch size \n and M represents the number of decoded boxes.\n\n Examples:\n \n .. code-block:: python\n \n import paddle.fluid as fluid\n # For encode\n prior_box_encode = fluid.data(name=\'prior_box_encode\',\n shape=[512, 4],\n dtype=\'float32\')\n target_box_encode = fluid.data(name=\'target_box_encode\',\n shape=[81, 4],\n dtype=\'float32\')\n output_encode = fluid.layers.box_coder(prior_box=prior_box_encode,\n prior_box_var=[0.1,0.1,0.2,0.2],\n target_box=target_box_encode,\n code_type="encode_center_size")\n # For decode\n prior_box_decode = fluid.data(name=\'prior_box_decode\',\n shape=[512, 4],\n dtype=\'float32\')\n target_box_decode = fluid.data(name=\'target_box_decode\',\n shape=[512, 81, 4],\n dtype=\'float32\')\n output_decode = fluid.layers.box_coder(prior_box=prior_box_decode,\n prior_box_var=[0.1,0.1,0.2,0.2],\n target_box=target_box_decode,\n code_type="decode_center_size",\n box_normalized=False,\n axis=1)\n '
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'], 'box_coder')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'], 'box_coder')
helper = LayerHelper('box_coder', **locals())
output_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
inputs = {'PriorBox': prior_box, 'TargetBox': target_box}
attrs = {'code_type': code_type, 'box_normalized': box_normalized, 'axis': axis}
if isinstance(prior_box_var, Variable):
inputs['PriorBoxVar'] = prior_box_var
elif isinstance(prior_box_var, list):
attrs['variance'] = prior_box_var
else:
raise TypeError('Input variance of box_coder must be Variable or lisz')
helper.append_op(type='box_coder', inputs=inputs, attrs=attrs, outputs={'OutputBox': output_box})
return output_box |
@templatedoc()
def polygon_box_transform(input, name=None):
"\n ${comment}\n\n Args:\n input(Variable): The input with shape [batch_size, geometry_channels, height, width].\n A Tensor with type float32, float64.\n name(str, Optional): For details, please refer to :ref:`api_guide_Name`.\n Generally, no setting is required. Default: None.\n\n Returns:\n Variable: The output with the same shape as input. A Tensor with type float32, float64.\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')\n out = fluid.layers.polygon_box_transform(input)\n "
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'polygon_box_transform')
helper = LayerHelper('polygon_box_transform', **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(type='polygon_box_transform', inputs={'Input': input}, attrs={}, outputs={'Output': output})
return output | -6,165,797,317,977,171,000 | ${comment}
Args:
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 :ref:`api_guide_Name`.
Generally, no setting is required. Default: None.
Returns:
Variable: The output with the same shape as input. A Tensor with type float32, float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')
out = fluid.layers.polygon_box_transform(input) | python/paddle/fluid/layers/detection.py | polygon_box_transform | 92lqllearning/Paddle | python | @templatedoc()
def polygon_box_transform(input, name=None):
"\n ${comment}\n\n Args:\n input(Variable): The input with shape [batch_size, geometry_channels, height, width].\n A Tensor with type float32, float64.\n name(str, Optional): For details, please refer to :ref:`api_guide_Name`.\n Generally, no setting is required. Default: None.\n\n Returns:\n Variable: The output with the same shape as input. A Tensor with type float32, float64.\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n input = fluid.data(name='input', shape=[4, 10, 5, 5], dtype='float32')\n out = fluid.layers.polygon_box_transform(input)\n "
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'polygon_box_transform')
helper = LayerHelper('polygon_box_transform', **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
helper.append_op(type='polygon_box_transform', inputs={'Input': input}, attrs={}, outputs={'Output': output})
return output |
@templatedoc(op_type='yolov3_loss')
def 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, scale_x_y=1.0):
"\n\t:alias_main: paddle.nn.functional.yolov3_loss\n\t:alias: paddle.nn.functional.yolov3_loss,paddle.nn.functional.vision.yolov3_loss\n\t:old_api: paddle.fluid.layers.yolov3_loss\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment}The data type is float32 or float64. \n gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4],\n in the third dimension, x, y, w, h should be stored. \n x,y is the center coordinate of boxes, w, h are the\n width and height, x, y, w, h should be divided by \n input image height to scale to [0, 1].\n N is the batch number and B is the max box number in \n an image.The data type is float32 or float64. \n gt_label (Variable): class id of ground truth boxes, should be in shape\n of [N, B].The data type is int32. \n anchors (list|tuple): ${anchors_comment}\n anchor_mask (list|tuple): ${anchor_mask_comment}\n class_num (int): ${class_num_comment}\n ignore_thresh (float): ${ignore_thresh_comment}\n downsample_ratio (int): ${downsample_ratio_comment}\n name (string): The default value is None. Normally there is no need \n for user to set this property. For more information, \n please refer to :ref:`api_guide_Name`\n gt_score (Variable): mixup score of ground truth boxes, should be in shape\n of [N, B]. Default None.\n use_label_smooth (bool): ${use_label_smooth_comment}\n scale_x_y (float): ${scale_x_y_comment}\n\n Returns:\n Variable: A 1-D tensor with shape [N], the value of yolov3 loss\n\n Raises:\n TypeError: Input x of yolov3_loss must be Variable\n TypeError: Input gtbox of yolov3_loss must be Variable\n TypeError: Input gtlabel of yolov3_loss must be Variable\n TypeError: Input gtscore of yolov3_loss must be None or Variable\n TypeError: Attr anchors of yolov3_loss must be list or tuple\n TypeError: Attr class_num of yolov3_loss must be an integer\n TypeError: Attr ignore_thresh of yolov3_loss must be a float number\n TypeError: Attr use_label_smooth of yolov3_loss must be a bool value\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')\n gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32')\n gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32')\n gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32')\n anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326]\n anchor_mask = [0, 1, 2]\n loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label,\n gt_score=gt_score, anchors=anchors, \n anchor_mask=anchor_mask, class_num=80,\n ignore_thresh=0.7, downsample_ratio=32)\n "
helper = LayerHelper('yolov3_loss', **locals())
if (not isinstance(x, Variable)):
raise TypeError('Input x of yolov3_loss must be Variable')
if (not isinstance(gt_box, Variable)):
raise TypeError('Input gtbox of yolov3_loss must be Variable')
if (not isinstance(gt_label, Variable)):
raise TypeError('Input gtlabel of yolov3_loss must be Variable')
if ((gt_score is not None) and (not isinstance(gt_score, Variable))):
raise TypeError('Input gtscore of yolov3_loss must be Variable')
if ((not isinstance(anchors, list)) and (not isinstance(anchors, tuple))):
raise TypeError('Attr anchors of yolov3_loss must be list or tuple')
if ((not isinstance(anchor_mask, list)) and (not isinstance(anchor_mask, tuple))):
raise TypeError('Attr anchor_mask of yolov3_loss must be list or tuple')
if (not isinstance(class_num, int)):
raise TypeError('Attr class_num of yolov3_loss must be an integer')
if (not isinstance(ignore_thresh, float)):
raise TypeError('Attr ignore_thresh of yolov3_loss must be a float number')
if (not isinstance(use_label_smooth, bool)):
raise TypeError('Attr use_label_smooth of yolov3_loss must be a bool value')
loss = helper.create_variable_for_type_inference(dtype=x.dtype)
objectness_mask = helper.create_variable_for_type_inference(dtype='int32')
gt_match_mask = helper.create_variable_for_type_inference(dtype='int32')
inputs = {'X': x, 'GTBox': gt_box, 'GTLabel': gt_label}
if (gt_score is not None):
inputs['GTScore'] = gt_score
attrs = {'anchors': anchors, 'anchor_mask': anchor_mask, 'class_num': class_num, 'ignore_thresh': ignore_thresh, 'downsample_ratio': downsample_ratio, 'use_label_smooth': use_label_smooth, 'scale_x_y': scale_x_y}
helper.append_op(type='yolov3_loss', inputs=inputs, outputs={'Loss': loss, 'ObjectnessMask': objectness_mask, 'GTMatchMask': gt_match_mask}, attrs=attrs)
return loss | -623,141,446,200,941,600 | :alias_main: paddle.nn.functional.yolov3_loss
:alias: paddle.nn.functional.yolov3_loss,paddle.nn.functional.vision.yolov3_loss
:old_api: paddle.fluid.layers.yolov3_loss
${comment}
Args:
x (Variable): ${x_comment}The data type is float32 or float64.
gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4],
in the third dimension, x, y, w, h should be stored.
x,y is the center coordinate 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, should be in shape
of [N, B].The data type is int32.
anchors (list|tuple): ${anchors_comment}
anchor_mask (list|tuple): ${anchor_mask_comment}
class_num (int): ${class_num_comment}
ignore_thresh (float): ${ignore_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
gt_score (Variable): mixup score of ground truth boxes, should be in shape
of [N, B]. Default None.
use_label_smooth (bool): ${use_label_smooth_comment}
scale_x_y (float): ${scale_x_y_comment}
Returns:
Variable: A 1-D tensor with shape [N], the value of yolov3 loss
Raises:
TypeError: Input x of yolov3_loss must be Variable
TypeError: Input gtbox of yolov3_loss must be Variable
TypeError: Input gtlabel of yolov3_loss must be Variable
TypeError: Input gtscore of yolov3_loss must be None or Variable
TypeError: Attr anchors of yolov3_loss must be list or tuple
TypeError: Attr class_num of yolov3_loss must be an integer
TypeError: Attr ignore_thresh of yolov3_loss must be a float number
TypeError: Attr use_label_smooth of yolov3_loss must be a bool value
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | yolov3_loss | 92lqllearning/Paddle | python | @templatedoc(op_type='yolov3_loss')
def 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, scale_x_y=1.0):
"\n\t:alias_main: paddle.nn.functional.yolov3_loss\n\t:alias: paddle.nn.functional.yolov3_loss,paddle.nn.functional.vision.yolov3_loss\n\t:old_api: paddle.fluid.layers.yolov3_loss\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment}The data type is float32 or float64. \n gt_box (Variable): groud truth boxes, should be in shape of [N, B, 4],\n in the third dimension, x, y, w, h should be stored. \n x,y is the center coordinate of boxes, w, h are the\n width and height, x, y, w, h should be divided by \n input image height to scale to [0, 1].\n N is the batch number and B is the max box number in \n an image.The data type is float32 or float64. \n gt_label (Variable): class id of ground truth boxes, should be in shape\n of [N, B].The data type is int32. \n anchors (list|tuple): ${anchors_comment}\n anchor_mask (list|tuple): ${anchor_mask_comment}\n class_num (int): ${class_num_comment}\n ignore_thresh (float): ${ignore_thresh_comment}\n downsample_ratio (int): ${downsample_ratio_comment}\n name (string): The default value is None. Normally there is no need \n for user to set this property. For more information, \n please refer to :ref:`api_guide_Name`\n gt_score (Variable): mixup score of ground truth boxes, should be in shape\n of [N, B]. Default None.\n use_label_smooth (bool): ${use_label_smooth_comment}\n scale_x_y (float): ${scale_x_y_comment}\n\n Returns:\n Variable: A 1-D tensor with shape [N], the value of yolov3 loss\n\n Raises:\n TypeError: Input x of yolov3_loss must be Variable\n TypeError: Input gtbox of yolov3_loss must be Variable\n TypeError: Input gtlabel of yolov3_loss must be Variable\n TypeError: Input gtscore of yolov3_loss must be None or Variable\n TypeError: Attr anchors of yolov3_loss must be list or tuple\n TypeError: Attr class_num of yolov3_loss must be an integer\n TypeError: Attr ignore_thresh of yolov3_loss must be a float number\n TypeError: Attr use_label_smooth of yolov3_loss must be a bool value\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')\n gt_box = fluid.data(name='gt_box', shape=[None, 6, 4], dtype='float32')\n gt_label = fluid.data(name='gt_label', shape=[None, 6], dtype='int32')\n gt_score = fluid.data(name='gt_score', shape=[None, 6], dtype='float32')\n anchors = [10, 13, 16, 30, 33, 23, 30, 61, 62, 45, 59, 119, 116, 90, 156, 198, 373, 326]\n anchor_mask = [0, 1, 2]\n loss = fluid.layers.yolov3_loss(x=x, gt_box=gt_box, gt_label=gt_label,\n gt_score=gt_score, anchors=anchors, \n anchor_mask=anchor_mask, class_num=80,\n ignore_thresh=0.7, downsample_ratio=32)\n "
helper = LayerHelper('yolov3_loss', **locals())
if (not isinstance(x, Variable)):
raise TypeError('Input x of yolov3_loss must be Variable')
if (not isinstance(gt_box, Variable)):
raise TypeError('Input gtbox of yolov3_loss must be Variable')
if (not isinstance(gt_label, Variable)):
raise TypeError('Input gtlabel of yolov3_loss must be Variable')
if ((gt_score is not None) and (not isinstance(gt_score, Variable))):
raise TypeError('Input gtscore of yolov3_loss must be Variable')
if ((not isinstance(anchors, list)) and (not isinstance(anchors, tuple))):
raise TypeError('Attr anchors of yolov3_loss must be list or tuple')
if ((not isinstance(anchor_mask, list)) and (not isinstance(anchor_mask, tuple))):
raise TypeError('Attr anchor_mask of yolov3_loss must be list or tuple')
if (not isinstance(class_num, int)):
raise TypeError('Attr class_num of yolov3_loss must be an integer')
if (not isinstance(ignore_thresh, float)):
raise TypeError('Attr ignore_thresh of yolov3_loss must be a float number')
if (not isinstance(use_label_smooth, bool)):
raise TypeError('Attr use_label_smooth of yolov3_loss must be a bool value')
loss = helper.create_variable_for_type_inference(dtype=x.dtype)
objectness_mask = helper.create_variable_for_type_inference(dtype='int32')
gt_match_mask = helper.create_variable_for_type_inference(dtype='int32')
inputs = {'X': x, 'GTBox': gt_box, 'GTLabel': gt_label}
if (gt_score is not None):
inputs['GTScore'] = gt_score
attrs = {'anchors': anchors, 'anchor_mask': anchor_mask, 'class_num': class_num, 'ignore_thresh': ignore_thresh, 'downsample_ratio': downsample_ratio, 'use_label_smooth': use_label_smooth, 'scale_x_y': scale_x_y}
helper.append_op(type='yolov3_loss', inputs=inputs, outputs={'Loss': loss, 'ObjectnessMask': objectness_mask, 'GTMatchMask': gt_match_mask}, attrs=attrs)
return loss |
@templatedoc(op_type='yolo_box')
def yolo_box(x, img_size, anchors, class_num, conf_thresh, downsample_ratio, clip_bbox=True, name=None, scale_x_y=1.0):
"\n\t:alias_main: paddle.nn.functional.yolo_box\n\t:alias: paddle.nn.functional.yolo_box,paddle.nn.functional.vision.yolo_box\n\t:old_api: paddle.fluid.layers.yolo_box\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment} The data type is float32 or float64. \n img_size (Variable): ${img_size_comment} The data type is int32. \n anchors (list|tuple): ${anchors_comment}\n class_num (int): ${class_num_comment}\n conf_thresh (float): ${conf_thresh_comment}\n downsample_ratio (int): ${downsample_ratio_comment}\n clip_bbox (bool): ${clip_bbox_comment}\n scale_x_y (float): ${scale_x_y_comment}\n name (string): The default value is None. Normally there is no need \n for user to set this property. For more information, \n please refer to :ref:`api_guide_Name`\n\n Returns:\n Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes,\n and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification \n scores of boxes.\n\n Raises:\n TypeError: Input x of yolov_box must be Variable\n TypeError: Attr anchors of yolo box must be list or tuple\n TypeError: Attr class_num of yolo box must be an integer\n TypeError: Attr conf_thresh of yolo box must be a float number\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')\n img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64')\n anchors = [10, 13, 16, 30, 33, 23]\n boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors, \n conf_thresh=0.01, downsample_ratio=32)\n "
helper = LayerHelper('yolo_box', **locals())
if (not isinstance(x, Variable)):
raise TypeError('Input x of yolo_box must be Variable')
if (not isinstance(img_size, Variable)):
raise TypeError('Input img_size of yolo_box must be Variable')
if ((not isinstance(anchors, list)) and (not isinstance(anchors, tuple))):
raise TypeError('Attr anchors of yolo_box must be list or tuple')
if (not isinstance(class_num, int)):
raise TypeError('Attr class_num of yolo_box must be an integer')
if (not isinstance(conf_thresh, float)):
raise TypeError('Attr ignore_thresh of yolo_box must be a float number')
boxes = helper.create_variable_for_type_inference(dtype=x.dtype)
scores = helper.create_variable_for_type_inference(dtype=x.dtype)
attrs = {'anchors': anchors, 'class_num': class_num, 'conf_thresh': conf_thresh, 'downsample_ratio': downsample_ratio, 'clip_bbox': clip_bbox, 'scale_x_y': scale_x_y}
helper.append_op(type='yolo_box', inputs={'X': x, 'ImgSize': img_size}, outputs={'Boxes': boxes, 'Scores': scores}, attrs=attrs)
return (boxes, scores) | -7,077,621,889,497,212,000 | :alias_main: paddle.nn.functional.yolo_box
:alias: paddle.nn.functional.yolo_box,paddle.nn.functional.vision.yolo_box
:old_api: paddle.fluid.layers.yolo_box
${comment}
Args:
x (Variable): ${x_comment} The data type is float32 or float64.
img_size (Variable): ${img_size_comment} The data type is int32.
anchors (list|tuple): ${anchors_comment}
class_num (int): ${class_num_comment}
conf_thresh (float): ${conf_thresh_comment}
downsample_ratio (int): ${downsample_ratio_comment}
clip_bbox (bool): ${clip_bbox_comment}
scale_x_y (float): ${scale_x_y_comment}
name (string): The default value is None. Normally there is no need
for user to set this property. For more information,
please refer to :ref:`api_guide_Name`
Returns:
Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes,
and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification
scores of boxes.
Raises:
TypeError: Input x of yolov_box must be Variable
TypeError: Attr anchors of yolo box must be list or tuple
TypeError: Attr class_num of yolo box must be an integer
TypeError: Attr conf_thresh of yolo box must be a float number
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | yolo_box | 92lqllearning/Paddle | python | @templatedoc(op_type='yolo_box')
def yolo_box(x, img_size, anchors, class_num, conf_thresh, downsample_ratio, clip_bbox=True, name=None, scale_x_y=1.0):
"\n\t:alias_main: paddle.nn.functional.yolo_box\n\t:alias: paddle.nn.functional.yolo_box,paddle.nn.functional.vision.yolo_box\n\t:old_api: paddle.fluid.layers.yolo_box\n\n ${comment}\n\n Args:\n x (Variable): ${x_comment} The data type is float32 or float64. \n img_size (Variable): ${img_size_comment} The data type is int32. \n anchors (list|tuple): ${anchors_comment}\n class_num (int): ${class_num_comment}\n conf_thresh (float): ${conf_thresh_comment}\n downsample_ratio (int): ${downsample_ratio_comment}\n clip_bbox (bool): ${clip_bbox_comment}\n scale_x_y (float): ${scale_x_y_comment}\n name (string): The default value is None. Normally there is no need \n for user to set this property. For more information, \n please refer to :ref:`api_guide_Name`\n\n Returns:\n Variable: A 3-D tensor with shape [N, M, 4], the coordinates of boxes,\n and a 3-D tensor with shape [N, M, :attr:`class_num`], the classification \n scores of boxes.\n\n Raises:\n TypeError: Input x of yolov_box must be Variable\n TypeError: Attr anchors of yolo box must be list or tuple\n TypeError: Attr class_num of yolo box must be an integer\n TypeError: Attr conf_thresh of yolo box must be a float number\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(name='x', shape=[None, 255, 13, 13], dtype='float32')\n img_size = fluid.data(name='img_size',shape=[None, 2],dtype='int64')\n anchors = [10, 13, 16, 30, 33, 23]\n boxes,scores = fluid.layers.yolo_box(x=x, img_size=img_size, class_num=80, anchors=anchors, \n conf_thresh=0.01, downsample_ratio=32)\n "
helper = LayerHelper('yolo_box', **locals())
if (not isinstance(x, Variable)):
raise TypeError('Input x of yolo_box must be Variable')
if (not isinstance(img_size, Variable)):
raise TypeError('Input img_size of yolo_box must be Variable')
if ((not isinstance(anchors, list)) and (not isinstance(anchors, tuple))):
raise TypeError('Attr anchors of yolo_box must be list or tuple')
if (not isinstance(class_num, int)):
raise TypeError('Attr class_num of yolo_box must be an integer')
if (not isinstance(conf_thresh, float)):
raise TypeError('Attr ignore_thresh of yolo_box must be a float number')
boxes = helper.create_variable_for_type_inference(dtype=x.dtype)
scores = helper.create_variable_for_type_inference(dtype=x.dtype)
attrs = {'anchors': anchors, 'class_num': class_num, 'conf_thresh': conf_thresh, 'downsample_ratio': downsample_ratio, 'clip_bbox': clip_bbox, 'scale_x_y': scale_x_y}
helper.append_op(type='yolo_box', inputs={'X': x, 'ImgSize': img_size}, outputs={'Boxes': boxes, 'Scores': scores}, attrs=attrs)
return (boxes, scores) |
@templatedoc()
def detection_map(detect_res, label, class_num, background_label=0, overlap_threshold=0.3, evaluate_difficult=True, has_state=None, input_states=None, out_states=None, ap_version='integral'):
"\n ${comment}\n\n Args:\n detect_res: ${detect_res_comment}\n label: ${label_comment}\n class_num: ${class_num_comment}\n background_label: ${background_label_comment}\n overlap_threshold: ${overlap_threshold_comment}\n evaluate_difficult: ${evaluate_difficult_comment}\n has_state: ${has_state_comment}\n input_states: (tuple|None) If not None, It contains 3 elements:\n (1) pos_count ${pos_count_comment}.\n (2) true_pos ${true_pos_comment}.\n (3) false_pos ${false_pos_comment}.\n out_states: (tuple|None) If not None, it contains 3 elements.\n (1) accum_pos_count ${accum_pos_count_comment}.\n (2) accum_true_pos ${accum_true_pos_comment}.\n (3) accum_false_pos ${accum_false_pos_comment}.\n ap_version: ${ap_type_comment}\n\n Returns:\n ${map_comment}\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n from fluid.layers import detection\n detect_res = fluid.data(\n name='detect_res',\n shape=[10, 6],\n dtype='float32')\n label = fluid.data(\n name='label',\n shape=[10, 6],\n dtype='float32')\n\n map_out = detection.detection_map(detect_res, label, 21)\n "
helper = LayerHelper('detection_map', **locals())
def __create_var(type):
return helper.create_variable_for_type_inference(dtype=type)
map_out = __create_var('float32')
accum_pos_count_out = (out_states[0] if (out_states is not None) else __create_var('int32'))
accum_true_pos_out = (out_states[1] if (out_states is not None) else __create_var('float32'))
accum_false_pos_out = (out_states[2] if (out_states is not None) else __create_var('float32'))
pos_count = (input_states[0] if (input_states is not None) else None)
true_pos = (input_states[1] if (input_states is not None) else None)
false_pos = (input_states[2] if (input_states is not None) else None)
helper.append_op(type='detection_map', inputs={'Label': label, 'DetectRes': detect_res, 'HasState': has_state, 'PosCount': pos_count, 'TruePos': true_pos, 'FalsePos': false_pos}, outputs={'MAP': map_out, 'AccumPosCount': accum_pos_count_out, 'AccumTruePos': accum_true_pos_out, 'AccumFalsePos': accum_false_pos_out}, attrs={'overlap_threshold': overlap_threshold, 'evaluate_difficult': evaluate_difficult, 'ap_type': ap_version, 'class_num': class_num})
return map_out | -7,399,942,053,922,242,000 | ${comment}
Args:
detect_res: ${detect_res_comment}
label: ${label_comment}
class_num: ${class_num_comment}
background_label: ${background_label_comment}
overlap_threshold: ${overlap_threshold_comment}
evaluate_difficult: ${evaluate_difficult_comment}
has_state: ${has_state_comment}
input_states: (tuple|None) If not None, It contains 3 elements:
(1) pos_count ${pos_count_comment}.
(2) true_pos ${true_pos_comment}.
(3) false_pos ${false_pos_comment}.
out_states: (tuple|None) If not None, it contains 3 elements.
(1) accum_pos_count ${accum_pos_count_comment}.
(2) accum_true_pos ${accum_true_pos_comment}.
(3) accum_false_pos ${accum_false_pos_comment}.
ap_version: ${ap_type_comment}
Returns:
${map_comment}
Examples:
.. code-block:: python
import paddle.fluid as fluid
from fluid.layers import detection
detect_res = fluid.data(
name='detect_res',
shape=[10, 6],
dtype='float32')
label = fluid.data(
name='label',
shape=[10, 6],
dtype='float32')
map_out = detection.detection_map(detect_res, label, 21) | python/paddle/fluid/layers/detection.py | detection_map | 92lqllearning/Paddle | python | @templatedoc()
def detection_map(detect_res, label, class_num, background_label=0, overlap_threshold=0.3, evaluate_difficult=True, has_state=None, input_states=None, out_states=None, ap_version='integral'):
"\n ${comment}\n\n Args:\n detect_res: ${detect_res_comment}\n label: ${label_comment}\n class_num: ${class_num_comment}\n background_label: ${background_label_comment}\n overlap_threshold: ${overlap_threshold_comment}\n evaluate_difficult: ${evaluate_difficult_comment}\n has_state: ${has_state_comment}\n input_states: (tuple|None) If not None, It contains 3 elements:\n (1) pos_count ${pos_count_comment}.\n (2) true_pos ${true_pos_comment}.\n (3) false_pos ${false_pos_comment}.\n out_states: (tuple|None) If not None, it contains 3 elements.\n (1) accum_pos_count ${accum_pos_count_comment}.\n (2) accum_true_pos ${accum_true_pos_comment}.\n (3) accum_false_pos ${accum_false_pos_comment}.\n ap_version: ${ap_type_comment}\n\n Returns:\n ${map_comment}\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n from fluid.layers import detection\n detect_res = fluid.data(\n name='detect_res',\n shape=[10, 6],\n dtype='float32')\n label = fluid.data(\n name='label',\n shape=[10, 6],\n dtype='float32')\n\n map_out = detection.detection_map(detect_res, label, 21)\n "
helper = LayerHelper('detection_map', **locals())
def __create_var(type):
return helper.create_variable_for_type_inference(dtype=type)
map_out = __create_var('float32')
accum_pos_count_out = (out_states[0] if (out_states is not None) else __create_var('int32'))
accum_true_pos_out = (out_states[1] if (out_states is not None) else __create_var('float32'))
accum_false_pos_out = (out_states[2] if (out_states is not None) else __create_var('float32'))
pos_count = (input_states[0] if (input_states is not None) else None)
true_pos = (input_states[1] if (input_states is not None) else None)
false_pos = (input_states[2] if (input_states is not None) else None)
helper.append_op(type='detection_map', inputs={'Label': label, 'DetectRes': detect_res, 'HasState': has_state, 'PosCount': pos_count, 'TruePos': true_pos, 'FalsePos': false_pos}, outputs={'MAP': map_out, 'AccumPosCount': accum_pos_count_out, 'AccumTruePos': accum_true_pos_out, 'AccumFalsePos': accum_false_pos_out}, attrs={'overlap_threshold': overlap_threshold, 'evaluate_difficult': evaluate_difficult, 'ap_type': ap_version, 'class_num': class_num})
return map_out |
def bipartite_match(dist_matrix, match_type=None, dist_threshold=None, name=None):
"\n\t:alias_main: paddle.nn.functional.bipartite_match\n\t:alias: paddle.nn.functional.bipartite_match,paddle.nn.functional.vision.bipartite_match\n\t:old_api: paddle.fluid.layers.bipartite_match\n\n This operator implements a greedy bipartite matching algorithm, which is\n used to obtain the matching with the maximum distance based on the input\n distance matrix. For input 2D matrix, the bipartite matching algorithm can\n find the matched column for each row (matched means the largest distance),\n also can find the matched row for each column. And this operator only\n calculate matched indices from column to row. For each instance,\n the number of matched indices is the column number of the input distance\n matrix. **The OP only supports CPU**.\n\n There are two outputs, matched indices and distance.\n A simple description, this algorithm matched the best (maximum distance)\n row entity to the column entity and the matched indices are not duplicated\n in each row of ColToRowMatchIndices. If the column entity is not matched\n any row entity, set -1 in ColToRowMatchIndices.\n\n NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor.\n If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.\n If Tensor, the height of ColToRowMatchIndices is 1.\n\n NOTE: This API is a very low level API. It is used by :code:`ssd_loss`\n layer. Please consider to use :code:`ssd_loss` instead.\n\n Args:\n dist_matrix(Variable): This input is a 2-D LoDTensor with shape\n [K, M]. The data type is float32 or float64. It is pair-wise \n distance matrix between the entities represented by each row and \n each column. For example, assumed one entity is A with shape [K], \n another entity is B with shape [M]. The dist_matrix[i][j] is the \n distance between A[i] and B[j]. The bigger the distance is, the \n better matching the pairs are. NOTE: This tensor can contain LoD \n information to represent a batch of inputs. One instance of this \n batch can contain different numbers of entities.\n match_type(str, optional): The type of matching method, should be\n 'bipartite' or 'per_prediction'. None ('bipartite') by default.\n dist_threshold(float32, optional): If `match_type` is 'per_prediction',\n this threshold is to determine the extra matching bboxes based\n on the maximum distance, 0.5 by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default.\n \n Returns:\n Tuple:\n\n matched_indices(Variable): A 2-D Tensor with shape [N, M]. The data\n type is int32. N is the batch size. If match_indices[i][j] is -1, it\n means B[j] does not match any entity in i-th instance.\n Otherwise, it means B[j] is matched to row\n match_indices[i][j] in i-th instance. The row number of\n i-th instance is saved in match_indices[i][j].\n\n matched_distance(Variable): A 2-D Tensor with shape [N, M]. The data\n type is float32. N is batch size. If match_indices[i][j] is -1,\n match_distance[i][j] is also -1.0. Otherwise, assumed\n match_distance[i][j] = d, and the row offsets of each instance\n are called LoD. Then match_distance[i][j] =\n dist_matrix[d+LoD[i]][j].\n\n Examples:\n\n >>> import paddle.fluid as fluid\n >>> x = fluid.data(name='x', shape=[None, 4], dtype='float32')\n >>> y = fluid.data(name='y', shape=[None, 4], dtype='float32')\n >>> iou = fluid.layers.iou_similarity(x=x, y=y)\n >>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou)\n "
helper = LayerHelper('bipartite_match', **locals())
match_indices = helper.create_variable_for_type_inference(dtype='int32')
match_distance = helper.create_variable_for_type_inference(dtype=dist_matrix.dtype)
helper.append_op(type='bipartite_match', inputs={'DistMat': dist_matrix}, attrs={'match_type': match_type, 'dist_threshold': dist_threshold}, outputs={'ColToRowMatchIndices': match_indices, 'ColToRowMatchDist': match_distance})
return (match_indices, match_distance) | -1,167,445,085,259,828,700 | :alias_main: paddle.nn.functional.bipartite_match
:alias: paddle.nn.functional.bipartite_match,paddle.nn.functional.vision.bipartite_match
:old_api: paddle.fluid.layers.bipartite_match
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 :code:`ssd_loss`
layer. Please consider to use :code:`ssd_loss` instead.
Args:
dist_matrix(Variable): This input is a 2-D LoDTensor with shape
[K, M]. The data type is float32 or float64. It is pair-wise
distance matrix between the entities represented by each row and
each column. For example, assumed one entity is A with shape [K],
another entity is B with shape [M]. The dist_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 :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
matched_indices(Variable): A 2-D 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 i-th instance.
Otherwise, it means B[j] is matched to row
match_indices[i][j] in i-th instance. The row number of
i-th instance is saved in match_indices[i][j].
matched_distance(Variable): A 2-D 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].
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) | python/paddle/fluid/layers/detection.py | bipartite_match | 92lqllearning/Paddle | python | def bipartite_match(dist_matrix, match_type=None, dist_threshold=None, name=None):
"\n\t:alias_main: paddle.nn.functional.bipartite_match\n\t:alias: paddle.nn.functional.bipartite_match,paddle.nn.functional.vision.bipartite_match\n\t:old_api: paddle.fluid.layers.bipartite_match\n\n This operator implements a greedy bipartite matching algorithm, which is\n used to obtain the matching with the maximum distance based on the input\n distance matrix. For input 2D matrix, the bipartite matching algorithm can\n find the matched column for each row (matched means the largest distance),\n also can find the matched row for each column. And this operator only\n calculate matched indices from column to row. For each instance,\n the number of matched indices is the column number of the input distance\n matrix. **The OP only supports CPU**.\n\n There are two outputs, matched indices and distance.\n A simple description, this algorithm matched the best (maximum distance)\n row entity to the column entity and the matched indices are not duplicated\n in each row of ColToRowMatchIndices. If the column entity is not matched\n any row entity, set -1 in ColToRowMatchIndices.\n\n NOTE: the input DistMat can be LoDTensor (with LoD) or Tensor.\n If LoDTensor with LoD, the height of ColToRowMatchIndices is batch size.\n If Tensor, the height of ColToRowMatchIndices is 1.\n\n NOTE: This API is a very low level API. It is used by :code:`ssd_loss`\n layer. Please consider to use :code:`ssd_loss` instead.\n\n Args:\n dist_matrix(Variable): This input is a 2-D LoDTensor with shape\n [K, M]. The data type is float32 or float64. It is pair-wise \n distance matrix between the entities represented by each row and \n each column. For example, assumed one entity is A with shape [K], \n another entity is B with shape [M]. The dist_matrix[i][j] is the \n distance between A[i] and B[j]. The bigger the distance is, the \n better matching the pairs are. NOTE: This tensor can contain LoD \n information to represent a batch of inputs. One instance of this \n batch can contain different numbers of entities.\n match_type(str, optional): The type of matching method, should be\n 'bipartite' or 'per_prediction'. None ('bipartite') by default.\n dist_threshold(float32, optional): If `match_type` is 'per_prediction',\n this threshold is to determine the extra matching bboxes based\n on the maximum distance, 0.5 by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default.\n \n Returns:\n Tuple:\n\n matched_indices(Variable): A 2-D Tensor with shape [N, M]. The data\n type is int32. N is the batch size. If match_indices[i][j] is -1, it\n means B[j] does not match any entity in i-th instance.\n Otherwise, it means B[j] is matched to row\n match_indices[i][j] in i-th instance. The row number of\n i-th instance is saved in match_indices[i][j].\n\n matched_distance(Variable): A 2-D Tensor with shape [N, M]. The data\n type is float32. N is batch size. If match_indices[i][j] is -1,\n match_distance[i][j] is also -1.0. Otherwise, assumed\n match_distance[i][j] = d, and the row offsets of each instance\n are called LoD. Then match_distance[i][j] =\n dist_matrix[d+LoD[i]][j].\n\n Examples:\n\n >>> import paddle.fluid as fluid\n >>> x = fluid.data(name='x', shape=[None, 4], dtype='float32')\n >>> y = fluid.data(name='y', shape=[None, 4], dtype='float32')\n >>> iou = fluid.layers.iou_similarity(x=x, y=y)\n >>> matched_indices, matched_dist = fluid.layers.bipartite_match(iou)\n "
helper = LayerHelper('bipartite_match', **locals())
match_indices = helper.create_variable_for_type_inference(dtype='int32')
match_distance = helper.create_variable_for_type_inference(dtype=dist_matrix.dtype)
helper.append_op(type='bipartite_match', inputs={'DistMat': dist_matrix}, attrs={'match_type': match_type, 'dist_threshold': dist_threshold}, outputs={'ColToRowMatchIndices': match_indices, 'ColToRowMatchDist': match_distance})
return (match_indices, match_distance) |
def target_assign(input, matched_indices, negative_indices=None, mismatch_value=None, name=None):
"\n\t:alias_main: paddle.nn.functional.target_assign\n\t:alias: paddle.nn.functional.target_assign,paddle.nn.functional.extension.target_assign\n\t:old_api: paddle.fluid.layers.target_assign\n\n This operator can be, for given the target bounding boxes or labels,\n to assign classification and regression targets to each prediction as well as\n weights to prediction. The weights is used to specify which prediction would\n not contribute to training loss.\n\n For each instance, the output `out` and`out_weight` are assigned based on\n `match_indices` and `negative_indices`.\n Assumed that the row offset for each instance in `input` is called lod,\n this operator assigns classification/regression targets by performing the\n following steps:\n\n 1. Assigning all outputs based on `match_indices`:\n\n .. code-block:: text\n\n If id = match_indices[i][j] > 0,\n\n out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]\n out_weight[i][j] = 1.\n\n Otherwise,\n\n out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}\n out_weight[i][j] = 0.\n\n 2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:\n\n Assumed that i-th instance in `neg_indices` is called `neg_indice`,\n for i-th instance:\n\n .. code-block:: text\n\n for id in neg_indice:\n out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}\n out_weight[i][id] = 1.0\n\n Args:\n input (Variable): This input is a 3D LoDTensor with shape [M, P, K].\n Data type should be int32 or float32.\n matched_indices (Variable): The input matched indices\n is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,\n the j-th entity of column is not matched to any entity of row in\n i-th instance.\n negative_indices (Variable, optional): The input negative example indices\n are an optional input with shape [Neg, 1] and int32 type, where Neg is\n the total number of negative example indices.\n mismatch_value (float32, optional): Fill this value to the mismatched\n location.\n name (string): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer\n to :ref:`api_guide_Name`.\n\n Returns:\n tuple: A tuple(out, out_weight) is returned.\n\n out (Variable): a 3D Tensor with shape [N, P, K] and same data type\n with `input`, N and P is the same as they are in `matched_indices`,\n K is the same as it in input of X.\n\n out_weight (Variable): the weight for output with the shape of [N, P, 1].\n Data type is float32.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(\n name='x',\n shape=[4, 20, 4],\n dtype='float',\n lod_level=1)\n matched_id = fluid.data(\n name='indices',\n shape=[8, 20],\n dtype='int32')\n trg, trg_weight = fluid.layers.target_assign(\n x,\n matched_id,\n mismatch_value=0)\n "
helper = LayerHelper('target_assign', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
out_weight = helper.create_variable_for_type_inference(dtype='float32')
helper.append_op(type='target_assign', inputs={'X': input, 'MatchIndices': matched_indices, 'NegIndices': negative_indices}, outputs={'Out': out, 'OutWeight': out_weight}, attrs={'mismatch_value': mismatch_value})
return (out, out_weight) | 1,944,621,000,617,827,300 | :alias_main: paddle.nn.functional.target_assign
:alias: paddle.nn.functional.target_assign,paddle.nn.functional.extension.target_assign
:old_api: paddle.fluid.layers.target_assign
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:
1. Assigning all outputs based on `match_indices`:
.. code-block:: text
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.
2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:
Assumed that i-th instance in `neg_indices` is called `neg_indice`,
for i-th instance:
.. code-block:: text
for id in neg_indice:
out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}
out_weight[i][id] = 1.0
Args:
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 j-th entity of column is not matched to any entity of row in
i-th 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 :ref:`api_guide_Name`.
Returns:
tuple: 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.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | target_assign | 92lqllearning/Paddle | python | def target_assign(input, matched_indices, negative_indices=None, mismatch_value=None, name=None):
"\n\t:alias_main: paddle.nn.functional.target_assign\n\t:alias: paddle.nn.functional.target_assign,paddle.nn.functional.extension.target_assign\n\t:old_api: paddle.fluid.layers.target_assign\n\n This operator can be, for given the target bounding boxes or labels,\n to assign classification and regression targets to each prediction as well as\n weights to prediction. The weights is used to specify which prediction would\n not contribute to training loss.\n\n For each instance, the output `out` and`out_weight` are assigned based on\n `match_indices` and `negative_indices`.\n Assumed that the row offset for each instance in `input` is called lod,\n this operator assigns classification/regression targets by performing the\n following steps:\n\n 1. Assigning all outputs based on `match_indices`:\n\n .. code-block:: text\n\n If id = match_indices[i][j] > 0,\n\n out[i][j][0 : K] = X[lod[i] + id][j % P][0 : K]\n out_weight[i][j] = 1.\n\n Otherwise,\n\n out[j][j][0 : K] = {mismatch_value, mismatch_value, ...}\n out_weight[i][j] = 0.\n\n 2. Assigning outputs based on `neg_indices` if `neg_indices` is provided:\n\n Assumed that i-th instance in `neg_indices` is called `neg_indice`,\n for i-th instance:\n\n .. code-block:: text\n\n for id in neg_indice:\n out[i][id][0 : K] = {mismatch_value, mismatch_value, ...}\n out_weight[i][id] = 1.0\n\n Args:\n input (Variable): This input is a 3D LoDTensor with shape [M, P, K].\n Data type should be int32 or float32.\n matched_indices (Variable): The input matched indices\n is 2D Tenosr<int32> with shape [N, P], If MatchIndices[i][j] is -1,\n the j-th entity of column is not matched to any entity of row in\n i-th instance.\n negative_indices (Variable, optional): The input negative example indices\n are an optional input with shape [Neg, 1] and int32 type, where Neg is\n the total number of negative example indices.\n mismatch_value (float32, optional): Fill this value to the mismatched\n location.\n name (string): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer\n to :ref:`api_guide_Name`.\n\n Returns:\n tuple: A tuple(out, out_weight) is returned.\n\n out (Variable): a 3D Tensor with shape [N, P, K] and same data type\n with `input`, N and P is the same as they are in `matched_indices`,\n K is the same as it in input of X.\n\n out_weight (Variable): the weight for output with the shape of [N, P, 1].\n Data type is float32.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n x = fluid.data(\n name='x',\n shape=[4, 20, 4],\n dtype='float',\n lod_level=1)\n matched_id = fluid.data(\n name='indices',\n shape=[8, 20],\n dtype='int32')\n trg, trg_weight = fluid.layers.target_assign(\n x,\n matched_id,\n mismatch_value=0)\n "
helper = LayerHelper('target_assign', **locals())
out = helper.create_variable_for_type_inference(dtype=input.dtype)
out_weight = helper.create_variable_for_type_inference(dtype='float32')
helper.append_op(type='target_assign', inputs={'X': input, 'MatchIndices': matched_indices, 'NegIndices': negative_indices}, outputs={'Out': out, 'OutWeight': out_weight}, attrs={'mismatch_value': mismatch_value})
return (out, out_weight) |
def ssd_loss(location, confidence, gt_box, gt_label, prior_box, prior_box_var=None, background_label=0, overlap_threshold=0.5, neg_pos_ratio=3.0, neg_overlap=0.5, loc_loss_weight=1.0, conf_loss_weight=1.0, match_type='per_prediction', mining_type='max_negative', normalize=True, sample_size=None):
"\n\t:alias_main: paddle.nn.functional.ssd_loss\n\t:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss\n\t:old_api: paddle.fluid.layers.ssd_loss\n\n **Multi-box loss layer for object detection algorithm of SSD**\n\n This layer is to compute detection loss for SSD given the location offset\n predictions, confidence predictions, prior boxes and ground-truth bounding\n boxes and labels, and the type of hard example mining. The returned loss\n is a weighted sum of the localization loss (or regression loss) and\n confidence loss (or classification loss) by performing the following steps:\n\n 1. Find matched bounding box by bipartite matching algorithm.\n\n 1.1 Compute IOU similarity between ground-truth boxes and prior boxes.\n\n 1.2 Compute matched bounding box by bipartite matching algorithm.\n\n 2. Compute confidence for mining hard examples\n\n 2.1. Get the target label based on matched indices.\n\n 2.2. Compute confidence loss.\n\n 3. Apply hard example mining to get the negative example indices and update\n the matched indices.\n\n 4. Assign classification and regression targets\n\n 4.1. Encoded bbox according to the prior boxes.\n\n 4.2. Assign regression targets.\n\n 4.3. Assign classification targets.\n\n 5. Compute the overall objective loss.\n\n 5.1 Compute confidence loss.\n\n 5.2 Compute localization loss.\n\n 5.3 Compute the overall weighted loss.\n\n Args:\n location (Variable): The location predictions are a 3D Tensor with\n shape [N, Np, 4], N is the batch size, Np is total number of\n predictions for each instance. 4 is the number of coordinate values,\n the layout is [xmin, ymin, xmax, ymax].The data type is float32 or\n float64.\n confidence (Variable): The confidence predictions are a 3D Tensor\n with shape [N, Np, C], N and Np are the same as they are in\n `location`, C is the class number.The data type is float32 or\n float64.\n gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D\n LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth\n bboxes of mini-batch input.The data type is float32 or float64.\n gt_label (Variable): The ground-truth labels are a 2D LoDTensor\n with shape [Ng, 1].Ng is the total number of ground-truth bboxes of\n mini-batch input, 1 is the number of class. The data type is float32\n or float64.\n prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].\n Np and 4 are the same as they are in `location`. The data type is\n float32 or float64.\n prior_box_var (Variable): The variance of prior boxes are a 2D Tensor\n with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`\n background_label (int): The index of background label, 0 by default.\n overlap_threshold (float): If match_type is 'per_prediction', use\n 'overlap_threshold' to determine the extra matching bboxes when finding matched boxes. 0.5 by default.\n neg_pos_ratio (float): The ratio of the negative boxes to the positive\n boxes, used only when mining_type is 'max_negative', 3.0 by default.\n neg_overlap (float): The negative overlap upper bound for the unmatched\n predictions. Use only when mining_type is 'max_negative',\n 0.5 by default.\n loc_loss_weight (float): Weight for localization loss, 1.0 by default.\n conf_loss_weight (float): Weight for confidence loss, 1.0 by default.\n match_type (str): The type of matching method during training, should\n be 'bipartite' or 'per_prediction', 'per_prediction' by default.\n mining_type (str): The hard example mining type, should be 'hard_example'\n or 'max_negative', now only support `max_negative`.\n normalize (bool): Whether to normalize the SSD loss by the total number\n of output locations, True by default.\n sample_size (int): The max sample size of negative box, used only when\n mining_type is 'hard_example'.\n\n Returns:\n Variable(Tensor): The weighted sum of the localization loss and confidence loss, with shape [N * Np, 1], N and Np are the same as they are in\n `location`.The data type is float32 or float64.\n\n Raises:\n ValueError: If mining_type is 'hard_example', now only support mining type of `max_negative`.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n pb = fluid.data(\n name='prior_box',\n shape=[10, 4],\n dtype='float32')\n pbv = fluid.data(\n name='prior_box_var',\n shape=[10, 4],\n dtype='float32')\n loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')\n scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')\n gt_box = fluid.data(\n name='gt_box', shape=[4], lod_level=1, dtype='float32')\n gt_label = fluid.data(\n name='gt_label', shape=[1], lod_level=1, dtype='float32')\n loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)\n "
helper = LayerHelper('ssd_loss', **locals())
if (mining_type != 'max_negative'):
raise ValueError('Only support mining_type == max_negative now.')
(num, num_prior, num_class) = confidence.shape
conf_shape = nn.shape(confidence)
def __reshape_to_2d(var):
return nn.flatten(x=var, axis=2)
iou = iou_similarity(x=gt_box, y=prior_box)
(matched_indices, matched_dist) = bipartite_match(iou, match_type, overlap_threshold)
gt_label = nn.reshape(x=gt_label, shape=(((len(gt_label.shape) - 1) * (0,)) + ((- 1), 1)))
gt_label.stop_gradient = True
(target_label, _) = target_assign(gt_label, matched_indices, mismatch_value=background_label)
confidence = __reshape_to_2d(confidence)
target_label = tensor.cast(x=target_label, dtype='int64')
target_label = __reshape_to_2d(target_label)
target_label.stop_gradient = True
conf_loss = softmax_with_cross_entropy(confidence, target_label)
actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2])
actual_shape.stop_gradient = True
conf_loss = nn.reshape(x=conf_loss, shape=((- 1), 0), actual_shape=actual_shape)
conf_loss.stop_gradient = True
neg_indices = helper.create_variable_for_type_inference(dtype='int32')
dtype = matched_indices.dtype
updated_matched_indices = helper.create_variable_for_type_inference(dtype=dtype)
helper.append_op(type='mine_hard_examples', inputs={'ClsLoss': conf_loss, 'LocLoss': None, 'MatchIndices': matched_indices, 'MatchDist': matched_dist}, outputs={'NegIndices': neg_indices, 'UpdatedMatchIndices': updated_matched_indices}, attrs={'neg_pos_ratio': neg_pos_ratio, 'neg_dist_threshold': neg_overlap, 'mining_type': mining_type, 'sample_size': sample_size})
encoded_bbox = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=gt_box, code_type='encode_center_size')
(target_bbox, target_loc_weight) = target_assign(encoded_bbox, updated_matched_indices, mismatch_value=background_label)
(target_label, target_conf_weight) = target_assign(gt_label, updated_matched_indices, negative_indices=neg_indices, mismatch_value=background_label)
target_label = __reshape_to_2d(target_label)
target_label = tensor.cast(x=target_label, dtype='int64')
conf_loss = softmax_with_cross_entropy(confidence, target_label)
target_conf_weight = __reshape_to_2d(target_conf_weight)
conf_loss = (conf_loss * target_conf_weight)
target_label.stop_gradient = True
target_conf_weight.stop_gradient = True
location = __reshape_to_2d(location)
target_bbox = __reshape_to_2d(target_bbox)
loc_loss = nn.smooth_l1(location, target_bbox)
target_loc_weight = __reshape_to_2d(target_loc_weight)
loc_loss = (loc_loss * target_loc_weight)
target_bbox.stop_gradient = True
target_loc_weight.stop_gradient = True
loss = ((conf_loss_weight * conf_loss) + (loc_loss_weight * loc_loss))
loss = nn.reshape(x=loss, shape=((- 1), 0), actual_shape=actual_shape)
loss = nn.reduce_sum(loss, dim=1, keep_dim=True)
if normalize:
normalizer = nn.reduce_sum(target_loc_weight)
loss = (loss / normalizer)
return loss | 3,573,965,390,815,687,000 | :alias_main: paddle.nn.functional.ssd_loss
:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss
:old_api: paddle.fluid.layers.ssd_loss
**Multi-box loss layer for object detection algorithm of SSD**
This layer is to compute detection loss for SSD given the location offset
predictions, confidence predictions, prior boxes and ground-truth bounding
boxes and labels, and the type of hard example mining. The returned loss
is a weighted sum of the localization loss (or regression loss) and
confidence loss (or classification loss) by performing the following steps:
1. Find matched bounding box by bipartite matching algorithm.
1.1 Compute IOU similarity between ground-truth boxes and prior boxes.
1.2 Compute matched bounding box by bipartite matching algorithm.
2. Compute confidence for mining hard examples
2.1. Get the target label based on matched indices.
2.2. Compute confidence loss.
3. Apply hard example mining to get the negative example indices and update
the matched indices.
4. Assign classification and regression targets
4.1. Encoded bbox according to the prior boxes.
4.2. Assign regression targets.
4.3. Assign classification targets.
5. Compute the overall objective loss.
5.1 Compute confidence loss.
5.2 Compute localization loss.
5.3 Compute the overall weighted loss.
Args:
location (Variable): The location predictions are a 3D Tensor with
shape [N, Np, 4], N is the batch size, Np is total number of
predictions for each instance. 4 is the number of coordinate values,
the layout is [xmin, ymin, xmax, ymax].The data type is float32 or
float64.
confidence (Variable): The confidence predictions are a 3D Tensor
with shape [N, Np, C], N and Np are the same as they are in
`location`, C is the class number.The data type is float32 or
float64.
gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D
LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth
bboxes of mini-batch input.The data type is float32 or float64.
gt_label (Variable): The ground-truth labels are a 2D LoDTensor
with shape [Ng, 1].Ng is the total number of ground-truth bboxes of
mini-batch input, 1 is the number of class. The data type is float32
or float64.
prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].
Np and 4 are the same as they are in `location`. The data type is
float32 or float64.
prior_box_var (Variable): The variance of prior boxes are a 2D Tensor
with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`
background_label (int): The index of background label, 0 by default.
overlap_threshold (float): If match_type is 'per_prediction', use
'overlap_threshold' to determine the extra matching bboxes when finding matched boxes. 0.5 by default.
neg_pos_ratio (float): The ratio of the negative boxes to the positive
boxes, used only when mining_type is 'max_negative', 3.0 by default.
neg_overlap (float): The negative overlap upper bound for the unmatched
predictions. Use only when mining_type is 'max_negative',
0.5 by default.
loc_loss_weight (float): Weight for localization loss, 1.0 by default.
conf_loss_weight (float): Weight for confidence loss, 1.0 by default.
match_type (str): The type of matching method during training, should
be 'bipartite' or 'per_prediction', 'per_prediction' by default.
mining_type (str): The hard example mining type, should be 'hard_example'
or 'max_negative', now only support `max_negative`.
normalize (bool): Whether to normalize the SSD loss by the total number
of output locations, True by default.
sample_size (int): The max sample size of negative box, used only when
mining_type is 'hard_example'.
Returns:
Variable(Tensor): The weighted sum of the localization loss and confidence loss, with shape [N * Np, 1], N and Np are the same as they are in
`location`.The data type is float32 or float64.
Raises:
ValueError: If mining_type is 'hard_example', now only support mining type of `max_negative`.
Examples:
.. code-block:: python
import paddle.fluid as fluid
pb = fluid.data(
name='prior_box',
shape=[10, 4],
dtype='float32')
pbv = fluid.data(
name='prior_box_var',
shape=[10, 4],
dtype='float32')
loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')
scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')
gt_box = fluid.data(
name='gt_box', shape=[4], lod_level=1, dtype='float32')
gt_label = fluid.data(
name='gt_label', shape=[1], lod_level=1, dtype='float32')
loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv) | python/paddle/fluid/layers/detection.py | ssd_loss | 92lqllearning/Paddle | python | def ssd_loss(location, confidence, gt_box, gt_label, prior_box, prior_box_var=None, background_label=0, overlap_threshold=0.5, neg_pos_ratio=3.0, neg_overlap=0.5, loc_loss_weight=1.0, conf_loss_weight=1.0, match_type='per_prediction', mining_type='max_negative', normalize=True, sample_size=None):
"\n\t:alias_main: paddle.nn.functional.ssd_loss\n\t:alias: paddle.nn.functional.ssd_loss,paddle.nn.functional.loss.ssd_loss\n\t:old_api: paddle.fluid.layers.ssd_loss\n\n **Multi-box loss layer for object detection algorithm of SSD**\n\n This layer is to compute detection loss for SSD given the location offset\n predictions, confidence predictions, prior boxes and ground-truth bounding\n boxes and labels, and the type of hard example mining. The returned loss\n is a weighted sum of the localization loss (or regression loss) and\n confidence loss (or classification loss) by performing the following steps:\n\n 1. Find matched bounding box by bipartite matching algorithm.\n\n 1.1 Compute IOU similarity between ground-truth boxes and prior boxes.\n\n 1.2 Compute matched bounding box by bipartite matching algorithm.\n\n 2. Compute confidence for mining hard examples\n\n 2.1. Get the target label based on matched indices.\n\n 2.2. Compute confidence loss.\n\n 3. Apply hard example mining to get the negative example indices and update\n the matched indices.\n\n 4. Assign classification and regression targets\n\n 4.1. Encoded bbox according to the prior boxes.\n\n 4.2. Assign regression targets.\n\n 4.3. Assign classification targets.\n\n 5. Compute the overall objective loss.\n\n 5.1 Compute confidence loss.\n\n 5.2 Compute localization loss.\n\n 5.3 Compute the overall weighted loss.\n\n Args:\n location (Variable): The location predictions are a 3D Tensor with\n shape [N, Np, 4], N is the batch size, Np is total number of\n predictions for each instance. 4 is the number of coordinate values,\n the layout is [xmin, ymin, xmax, ymax].The data type is float32 or\n float64.\n confidence (Variable): The confidence predictions are a 3D Tensor\n with shape [N, Np, C], N and Np are the same as they are in\n `location`, C is the class number.The data type is float32 or\n float64.\n gt_box (Variable): The ground-truth bounding boxes (bboxes) are a 2D\n LoDTensor with shape [Ng, 4], Ng is the total number of ground-truth\n bboxes of mini-batch input.The data type is float32 or float64.\n gt_label (Variable): The ground-truth labels are a 2D LoDTensor\n with shape [Ng, 1].Ng is the total number of ground-truth bboxes of\n mini-batch input, 1 is the number of class. The data type is float32\n or float64.\n prior_box (Variable): The prior boxes are a 2D Tensor with shape [Np, 4].\n Np and 4 are the same as they are in `location`. The data type is\n float32 or float64.\n prior_box_var (Variable): The variance of prior boxes are a 2D Tensor\n with shape [Np, 4]. Np and 4 are the same as they are in `prior_box`\n background_label (int): The index of background label, 0 by default.\n overlap_threshold (float): If match_type is 'per_prediction', use\n 'overlap_threshold' to determine the extra matching bboxes when finding matched boxes. 0.5 by default.\n neg_pos_ratio (float): The ratio of the negative boxes to the positive\n boxes, used only when mining_type is 'max_negative', 3.0 by default.\n neg_overlap (float): The negative overlap upper bound for the unmatched\n predictions. Use only when mining_type is 'max_negative',\n 0.5 by default.\n loc_loss_weight (float): Weight for localization loss, 1.0 by default.\n conf_loss_weight (float): Weight for confidence loss, 1.0 by default.\n match_type (str): The type of matching method during training, should\n be 'bipartite' or 'per_prediction', 'per_prediction' by default.\n mining_type (str): The hard example mining type, should be 'hard_example'\n or 'max_negative', now only support `max_negative`.\n normalize (bool): Whether to normalize the SSD loss by the total number\n of output locations, True by default.\n sample_size (int): The max sample size of negative box, used only when\n mining_type is 'hard_example'.\n\n Returns:\n Variable(Tensor): The weighted sum of the localization loss and confidence loss, with shape [N * Np, 1], N and Np are the same as they are in\n `location`.The data type is float32 or float64.\n\n Raises:\n ValueError: If mining_type is 'hard_example', now only support mining type of `max_negative`.\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n pb = fluid.data(\n name='prior_box',\n shape=[10, 4],\n dtype='float32')\n pbv = fluid.data(\n name='prior_box_var',\n shape=[10, 4],\n dtype='float32')\n loc = fluid.data(name='target_box', shape=[10, 4], dtype='float32')\n scores = fluid.data(name='scores', shape=[10, 21], dtype='float32')\n gt_box = fluid.data(\n name='gt_box', shape=[4], lod_level=1, dtype='float32')\n gt_label = fluid.data(\n name='gt_label', shape=[1], lod_level=1, dtype='float32')\n loss = fluid.layers.ssd_loss(loc, scores, gt_box, gt_label, pb, pbv)\n "
helper = LayerHelper('ssd_loss', **locals())
if (mining_type != 'max_negative'):
raise ValueError('Only support mining_type == max_negative now.')
(num, num_prior, num_class) = confidence.shape
conf_shape = nn.shape(confidence)
def __reshape_to_2d(var):
return nn.flatten(x=var, axis=2)
iou = iou_similarity(x=gt_box, y=prior_box)
(matched_indices, matched_dist) = bipartite_match(iou, match_type, overlap_threshold)
gt_label = nn.reshape(x=gt_label, shape=(((len(gt_label.shape) - 1) * (0,)) + ((- 1), 1)))
gt_label.stop_gradient = True
(target_label, _) = target_assign(gt_label, matched_indices, mismatch_value=background_label)
confidence = __reshape_to_2d(confidence)
target_label = tensor.cast(x=target_label, dtype='int64')
target_label = __reshape_to_2d(target_label)
target_label.stop_gradient = True
conf_loss = softmax_with_cross_entropy(confidence, target_label)
actual_shape = nn.slice(conf_shape, axes=[0], starts=[0], ends=[2])
actual_shape.stop_gradient = True
conf_loss = nn.reshape(x=conf_loss, shape=((- 1), 0), actual_shape=actual_shape)
conf_loss.stop_gradient = True
neg_indices = helper.create_variable_for_type_inference(dtype='int32')
dtype = matched_indices.dtype
updated_matched_indices = helper.create_variable_for_type_inference(dtype=dtype)
helper.append_op(type='mine_hard_examples', inputs={'ClsLoss': conf_loss, 'LocLoss': None, 'MatchIndices': matched_indices, 'MatchDist': matched_dist}, outputs={'NegIndices': neg_indices, 'UpdatedMatchIndices': updated_matched_indices}, attrs={'neg_pos_ratio': neg_pos_ratio, 'neg_dist_threshold': neg_overlap, 'mining_type': mining_type, 'sample_size': sample_size})
encoded_bbox = box_coder(prior_box=prior_box, prior_box_var=prior_box_var, target_box=gt_box, code_type='encode_center_size')
(target_bbox, target_loc_weight) = target_assign(encoded_bbox, updated_matched_indices, mismatch_value=background_label)
(target_label, target_conf_weight) = target_assign(gt_label, updated_matched_indices, negative_indices=neg_indices, mismatch_value=background_label)
target_label = __reshape_to_2d(target_label)
target_label = tensor.cast(x=target_label, dtype='int64')
conf_loss = softmax_with_cross_entropy(confidence, target_label)
target_conf_weight = __reshape_to_2d(target_conf_weight)
conf_loss = (conf_loss * target_conf_weight)
target_label.stop_gradient = True
target_conf_weight.stop_gradient = True
location = __reshape_to_2d(location)
target_bbox = __reshape_to_2d(target_bbox)
loc_loss = nn.smooth_l1(location, target_bbox)
target_loc_weight = __reshape_to_2d(target_loc_weight)
loc_loss = (loc_loss * target_loc_weight)
target_bbox.stop_gradient = True
target_loc_weight.stop_gradient = True
loss = ((conf_loss_weight * conf_loss) + (loc_loss_weight * loc_loss))
loss = nn.reshape(x=loss, shape=((- 1), 0), actual_shape=actual_shape)
loss = nn.reduce_sum(loss, dim=1, keep_dim=True)
if normalize:
normalizer = nn.reduce_sum(target_loc_weight)
loss = (loss / normalizer)
return loss |
def 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):
'\n\t:alias_main: paddle.nn.functional.prior_box\n\t:alias: paddle.nn.functional.prior_box,paddle.nn.functional.vision.prior_box\n\t:old_api: paddle.fluid.layers.prior_box\n\n This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.\n Each position of the input produce N prior boxes, N is determined by\n the count of min_sizes, max_sizes and aspect_ratios, The size of the\n box is in range(min_size, max_size) interval, which is generated in\n sequence according to the aspect_ratios.\n\n Parameters:\n input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64.\n image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,\n the data type should be float32 or float64.\n min_sizes(list|tuple|float): the min sizes of generated prior boxes.\n max_sizes(list|tuple|None): the max sizes of generated prior boxes.\n Default: None.\n aspect_ratios(list|tuple|float): the aspect ratios of generated\n prior boxes. Default: [1.].\n variance(list|tuple): the variances to be encoded in prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n flip(bool): Whether to flip aspect ratios. Default:False.\n clip(bool): Whether to clip out-of-boundary boxes. Default: False.\n step(list|tuple): Prior boxes step across width and height, If\n step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across\n height or weight of the input will be automatically calculated.\n Default: [0., 0.]\n offset(float): Prior boxes center offset. Default: 0.5\n min_max_aspect_ratios_order(bool): If set True, the output prior box is\n in order of [min, max, aspect_ratios], which is consistent with\n Caffe. Please note, this order affects the weights order of\n convolution layer followed by and does not affect the final\n detection results. Default: False.\n 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 :ref:`api_guide_Name`\n\n Returns:\n Tuple: A tuple with two Variable (boxes, variances)\n\n boxes(Variable): the output prior boxes of PriorBox.\n\t4-D tensor, the layout is [H, W, num_priors, 4].\n H is the height of input, W is the width of input,\n num_priors is the total box count of each position of input.\n\n variances(Variable): the expanded variances of PriorBox.\n \t4-D tensor, the layput is [H, W, num_priors, 4].\n H is the height of input, W is the width of input\n num_priors is the total box count of each position of input\n\n Examples:\n .. code-block:: python\n\n\t #declarative mode\n\t import paddle.fluid as fluid\n\t import numpy as np\n\t input = fluid.data(name="input", shape=[None,3,6,9])\n\t image = fluid.data(name="image", shape=[None,3,9,12])\n\t box, var = fluid.layers.prior_box(\n input=input,\n image=image,\n\t\t min_sizes=[100.],\n clip=True,\n flip=True)\n\n\t place = fluid.CPUPlace()\n\t exe = fluid.Executor(place)\n\t exe.run(fluid.default_startup_program())\n \n\t # prepare a batch of data\n\t input_data = np.random.rand(1,3,6,9).astype("float32")\n\t image_data = np.random.rand(1,3,9,12).astype("float32")\n \n\t box_out, var_out = exe.run(fluid.default_main_program(),\n feed={"input":input_data,"image":image_data},\n fetch_list=[box,var],\n return_numpy=True)\n \n\t # print(box_out.shape)\n\t # (6, 9, 1, 4)\n\t # print(var_out.shape)\n\t # (6, 9, 1, 4)\n\n\t # imperative mode\n\t import paddle.fluid.dygraph as dg\n\n\t with dg.guard(place) as g:\n \t\tinput = dg.to_variable(input_data)\n \t\timage = dg.to_variable(image_data)\n \t\tbox, var = fluid.layers.prior_box(\n\t\t input=input,\n\t\t image=image,\n\t\t min_sizes=[100.],\n\t\t clip=True,\n\t\t flip=True)\n\t\t# print(box.shape)\n\t\t# [6L, 9L, 1L, 4L]\n # print(var.shape)\n\t\t# [6L, 9L, 1L, 4L]\n\n '
helper = LayerHelper('prior_box', **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if (not _is_list_or_tuple_(min_sizes)):
min_sizes = [min_sizes]
if (not _is_list_or_tuple_(aspect_ratios)):
aspect_ratios = [aspect_ratios]
if (not (_is_list_or_tuple_(steps) and (len(steps) == 2))):
raise ValueError('steps should be a list or tuple ', 'with length 2, (step_width, step_height).')
min_sizes = list(map(float, min_sizes))
aspect_ratios = list(map(float, aspect_ratios))
steps = list(map(float, steps))
attrs = {'min_sizes': min_sizes, 'aspect_ratios': aspect_ratios, 'variances': variance, 'flip': flip, 'clip': clip, 'step_w': steps[0], 'step_h': steps[1], 'offset': offset, 'min_max_aspect_ratios_order': min_max_aspect_ratios_order}
if ((max_sizes is not None) and (len(max_sizes) > 0) and (max_sizes[0] > 0)):
if (not _is_list_or_tuple_(max_sizes)):
max_sizes = [max_sizes]
attrs['max_sizes'] = max_sizes
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='prior_box', inputs={'Input': input, 'Image': image}, outputs={'Boxes': box, 'Variances': var}, attrs=attrs)
box.stop_gradient = True
var.stop_gradient = True
return (box, var) | 5,445,573,688,111,395,000 | :alias_main: paddle.nn.functional.prior_box
:alias: paddle.nn.functional.prior_box,paddle.nn.functional.vision.prior_box
:old_api: paddle.fluid.layers.prior_box
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): 4-D tensor(NCHW), the data type should be float32 or float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,
the data type should be float32 or float64.
min_sizes(list|tuple|float): the min sizes of generated prior boxes.
max_sizes(list|tuple|None): the max sizes of generated prior boxes.
Default: None.
aspect_ratios(list|tuple|float): the aspect ratios of generated
prior boxes. Default: [1.].
variance(list|tuple): 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 out-of-boundary boxes. Default: False.
step(list|tuple): 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 :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes(Variable): the output prior boxes of PriorBox.
4-D 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.
4-D 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
Examples:
.. code-block:: python
#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] | python/paddle/fluid/layers/detection.py | prior_box | 92lqllearning/Paddle | python | def 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):
'\n\t:alias_main: paddle.nn.functional.prior_box\n\t:alias: paddle.nn.functional.prior_box,paddle.nn.functional.vision.prior_box\n\t:old_api: paddle.fluid.layers.prior_box\n\n This op generates prior boxes for SSD(Single Shot MultiBox Detector) algorithm.\n Each position of the input produce N prior boxes, N is determined by\n the count of min_sizes, max_sizes and aspect_ratios, The size of the\n box is in range(min_size, max_size) interval, which is generated in\n sequence according to the aspect_ratios.\n\n Parameters:\n input(Variable): 4-D tensor(NCHW), the data type should be float32 or float64.\n image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp,\n the data type should be float32 or float64.\n min_sizes(list|tuple|float): the min sizes of generated prior boxes.\n max_sizes(list|tuple|None): the max sizes of generated prior boxes.\n Default: None.\n aspect_ratios(list|tuple|float): the aspect ratios of generated\n prior boxes. Default: [1.].\n variance(list|tuple): the variances to be encoded in prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n flip(bool): Whether to flip aspect ratios. Default:False.\n clip(bool): Whether to clip out-of-boundary boxes. Default: False.\n step(list|tuple): Prior boxes step across width and height, If\n step[0] equals to 0.0 or step[1] equals to 0.0, the prior boxes step across\n height or weight of the input will be automatically calculated.\n Default: [0., 0.]\n offset(float): Prior boxes center offset. Default: 0.5\n min_max_aspect_ratios_order(bool): If set True, the output prior box is\n in order of [min, max, aspect_ratios], which is consistent with\n Caffe. Please note, this order affects the weights order of\n convolution layer followed by and does not affect the final\n detection results. Default: False.\n 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 :ref:`api_guide_Name`\n\n Returns:\n Tuple: A tuple with two Variable (boxes, variances)\n\n boxes(Variable): the output prior boxes of PriorBox.\n\t4-D tensor, the layout is [H, W, num_priors, 4].\n H is the height of input, W is the width of input,\n num_priors is the total box count of each position of input.\n\n variances(Variable): the expanded variances of PriorBox.\n \t4-D tensor, the layput is [H, W, num_priors, 4].\n H is the height of input, W is the width of input\n num_priors is the total box count of each position of input\n\n Examples:\n .. code-block:: python\n\n\t #declarative mode\n\t import paddle.fluid as fluid\n\t import numpy as np\n\t input = fluid.data(name="input", shape=[None,3,6,9])\n\t image = fluid.data(name="image", shape=[None,3,9,12])\n\t box, var = fluid.layers.prior_box(\n input=input,\n image=image,\n\t\t min_sizes=[100.],\n clip=True,\n flip=True)\n\n\t place = fluid.CPUPlace()\n\t exe = fluid.Executor(place)\n\t exe.run(fluid.default_startup_program())\n \n\t # prepare a batch of data\n\t input_data = np.random.rand(1,3,6,9).astype("float32")\n\t image_data = np.random.rand(1,3,9,12).astype("float32")\n \n\t box_out, var_out = exe.run(fluid.default_main_program(),\n feed={"input":input_data,"image":image_data},\n fetch_list=[box,var],\n return_numpy=True)\n \n\t # print(box_out.shape)\n\t # (6, 9, 1, 4)\n\t # print(var_out.shape)\n\t # (6, 9, 1, 4)\n\n\t # imperative mode\n\t import paddle.fluid.dygraph as dg\n\n\t with dg.guard(place) as g:\n \t\tinput = dg.to_variable(input_data)\n \t\timage = dg.to_variable(image_data)\n \t\tbox, var = fluid.layers.prior_box(\n\t\t input=input,\n\t\t image=image,\n\t\t min_sizes=[100.],\n\t\t clip=True,\n\t\t flip=True)\n\t\t# print(box.shape)\n\t\t# [6L, 9L, 1L, 4L]\n # print(var.shape)\n\t\t# [6L, 9L, 1L, 4L]\n\n '
helper = LayerHelper('prior_box', **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(input, 'input', ['uint8', 'int8', 'float32', 'float64'], 'prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if (not _is_list_or_tuple_(min_sizes)):
min_sizes = [min_sizes]
if (not _is_list_or_tuple_(aspect_ratios)):
aspect_ratios = [aspect_ratios]
if (not (_is_list_or_tuple_(steps) and (len(steps) == 2))):
raise ValueError('steps should be a list or tuple ', 'with length 2, (step_width, step_height).')
min_sizes = list(map(float, min_sizes))
aspect_ratios = list(map(float, aspect_ratios))
steps = list(map(float, steps))
attrs = {'min_sizes': min_sizes, 'aspect_ratios': aspect_ratios, 'variances': variance, 'flip': flip, 'clip': clip, 'step_w': steps[0], 'step_h': steps[1], 'offset': offset, 'min_max_aspect_ratios_order': min_max_aspect_ratios_order}
if ((max_sizes is not None) and (len(max_sizes) > 0) and (max_sizes[0] > 0)):
if (not _is_list_or_tuple_(max_sizes)):
max_sizes = [max_sizes]
attrs['max_sizes'] = max_sizes
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='prior_box', inputs={'Input': input, 'Image': image}, outputs={'Boxes': box, 'Variances': var}, attrs=attrs)
box.stop_gradient = True
var.stop_gradient = True
return (box, var) |
def 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):
'\n\t:alias_main: paddle.nn.functional.density_prior_box\n\t:alias: paddle.nn.functional.density_prior_box,paddle.nn.functional.vision.density_prior_box\n\t:old_api: paddle.fluid.layers.density_prior_box\n\n\n This op generates density prior boxes for SSD(Single Shot MultiBox Detector) \n algorithm. Each position of the input produce N prior boxes, N is \n determined by the count of densities, fixed_sizes and fixed_ratios. \n Boxes center at grid points around each input position is generated by \n this operator, and the grid points is determined by densities and \n the count of density prior box is determined by fixed_sizes and fixed_ratios. \n Obviously, the number of fixed_sizes is equal to the number of densities.\n \n For densities_i in densities:\n \n .. math::\n\n N\\_density_prior\\_box = SUM(N\\_fixed\\_ratios * densities\\_i^2)\n\n N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.\n\n Parameters:\n input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64.\n image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.\n the layout is NCHW.\n densities(list|tuple|None): The densities of generated density prior \n boxes, this attribute should be a list or tuple of integers. \n Default: None.\n fixed_sizes(list|tuple|None): The fixed sizes of generated density\n prior boxes, this attribute should a list or tuple of same \n length with :attr:`densities`. Default: None.\n fixed_ratios(list|tuple|None): The fixed ratios of generated density\n prior boxes, if this attribute is not set and :attr:`densities`\n and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used\n to generate density prior boxes.\n variance(list|tuple): The variances to be encoded in density prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n clip(bool): Whether to clip out of boundary boxes. Default: False.\n step(list|tuple): Prior boxes step across width and height, If\n step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across\n height or weight of the input will be automatically calculated.\n Default: [0., 0.]\n offset(float): Prior boxes center offset. Default: 0.5\n flatten_to_2d(bool): Whether to flatten output prior boxes and variance\n to 2D shape, the second dim is 4. Default: False.\n 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 :ref:`api_guide_Name`\n \n Returns:\n Tuple: A tuple with two Variable (boxes, variances)\n\n boxes: the output density prior boxes of PriorBox.\n 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.\n 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.\n 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.\n\n variances: the expanded variances of PriorBox.\n 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.\n 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.\n 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.\n\n\n Examples:\n\n .. code-block:: python\n\n #declarative mode\n\n import paddle.fluid as fluid\n import numpy as np\n\n input = fluid.data(name="input", shape=[None,3,6,9])\n image = fluid.data(name="image", shape=[None,3,9,12])\n box, var = fluid.layers.density_prior_box(\n input=input,\n image=image,\n densities=[4, 2, 1],\n fixed_sizes=[32.0, 64.0, 128.0],\n fixed_ratios=[1.],\n clip=True,\n flatten_to_2d=True)\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n \n # prepare a batch of data\n input_data = np.random.rand(1,3,6,9).astype("float32")\n image_data = np.random.rand(1,3,9,12).astype("float32")\n\n box_out, var_out = exe.run(\n fluid.default_main_program(),\n feed={"input":input_data,\n "image":image_data},\n fetch_list=[box,var],\n return_numpy=True)\n\n # print(box_out.shape)\n # (1134, 4)\n # print(var_out.shape)\n # (1134, 4)\n\n\n #imperative mode\n import paddle.fluid.dygraph as dg\n\n with dg.guard(place) as g:\n input = dg.to_variable(input_data)\n image = dg.to_variable(image_data)\n box, var = fluid.layers.density_prior_box(\n input=input,\n image=image,\n densities=[4, 2, 1],\n fixed_sizes=[32.0, 64.0, 128.0],\n fixed_ratios=[1.],\n clip=True)\n\n # print(box.shape)\n # [6L, 9L, 21L, 4L]\n # print(var.shape)\n # [6L, 9L, 21L, 4L]\n\n '
helper = LayerHelper('density_prior_box', **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'density_prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
check_type(densities, 'densities', (list, tuple), 'density_prior_box')
check_type(fixed_sizes, 'fixed_sizes', (list, tuple), 'density_prior_box')
check_type(fixed_ratios, 'fixed_ratios', (list, tuple), 'density_prior_box')
if (len(densities) != len(fixed_sizes)):
raise ValueError('densities and fixed_sizes length should be euqal.')
if (not (_is_list_or_tuple_(steps) and (len(steps) == 2))):
raise ValueError('steps should be a list or tuple ', 'with length 2, (step_width, step_height).')
densities = list(map(int, densities))
fixed_sizes = list(map(float, fixed_sizes))
fixed_ratios = list(map(float, fixed_ratios))
steps = list(map(float, steps))
attrs = {'variances': variance, 'clip': clip, 'step_w': steps[0], 'step_h': steps[1], 'offset': offset, 'densities': densities, 'fixed_sizes': fixed_sizes, 'fixed_ratios': fixed_ratios, 'flatten_to_2d': flatten_to_2d}
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='density_prior_box', inputs={'Input': input, 'Image': image}, outputs={'Boxes': box, 'Variances': var}, attrs=attrs)
box.stop_gradient = True
var.stop_gradient = True
return (box, var) | -4,812,473,693,915,520,000 | :alias_main: paddle.nn.functional.density_prior_box
:alias: paddle.nn.functional.density_prior_box,paddle.nn.functional.vision.density_prior_box
:old_api: paddle.fluid.layers.density_prior_box
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:
.. math::
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): 4-D tensor(NCHW), the data type should be float32 of float64.
image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.
the layout is NCHW.
densities(list|tuple|None): The densities of generated density prior
boxes, this attribute should be a list or tuple of integers.
Default: None.
fixed_sizes(list|tuple|None): The fixed sizes of generated density
prior boxes, this attribute should a list or tuple of same
length with :attr:`densities`. Default: None.
fixed_ratios(list|tuple|None): The fixed ratios of generated density
prior boxes, if this attribute is not set and :attr:`densities`
and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used
to generate density prior boxes.
variance(list|tuple): 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(list|tuple): 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 :ref:`api_guide_Name`
Returns:
Tuple: A tuple with two Variable (boxes, variances)
boxes: the output density prior boxes of PriorBox.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D 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.
4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.
2-D 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.
Examples:
.. code-block:: python
#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(box_out.shape)
# (1134, 4)
# print(var_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] | python/paddle/fluid/layers/detection.py | density_prior_box | 92lqllearning/Paddle | python | def 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):
'\n\t:alias_main: paddle.nn.functional.density_prior_box\n\t:alias: paddle.nn.functional.density_prior_box,paddle.nn.functional.vision.density_prior_box\n\t:old_api: paddle.fluid.layers.density_prior_box\n\n\n This op generates density prior boxes for SSD(Single Shot MultiBox Detector) \n algorithm. Each position of the input produce N prior boxes, N is \n determined by the count of densities, fixed_sizes and fixed_ratios. \n Boxes center at grid points around each input position is generated by \n this operator, and the grid points is determined by densities and \n the count of density prior box is determined by fixed_sizes and fixed_ratios. \n Obviously, the number of fixed_sizes is equal to the number of densities.\n \n For densities_i in densities:\n \n .. math::\n\n N\\_density_prior\\_box = SUM(N\\_fixed\\_ratios * densities\\_i^2)\n\n N_density_prior_box is the number of density_prior_box and N_fixed_ratios is the number of fixed_ratios.\n\n Parameters:\n input(Variable): 4-D tensor(NCHW), the data type should be float32 of float64.\n image(Variable): 4-D tensor(NCHW), the input image data of PriorBoxOp, the data type should be float32 or float64.\n the layout is NCHW.\n densities(list|tuple|None): The densities of generated density prior \n boxes, this attribute should be a list or tuple of integers. \n Default: None.\n fixed_sizes(list|tuple|None): The fixed sizes of generated density\n prior boxes, this attribute should a list or tuple of same \n length with :attr:`densities`. Default: None.\n fixed_ratios(list|tuple|None): The fixed ratios of generated density\n prior boxes, if this attribute is not set and :attr:`densities`\n and :attr:`fix_sizes` is set, :attr:`aspect_ratios` will be used\n to generate density prior boxes.\n variance(list|tuple): The variances to be encoded in density prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n clip(bool): Whether to clip out of boundary boxes. Default: False.\n step(list|tuple): Prior boxes step across width and height, If\n step[0] equals 0.0 or step[1] equals 0.0, the density prior boxes step across\n height or weight of the input will be automatically calculated.\n Default: [0., 0.]\n offset(float): Prior boxes center offset. Default: 0.5\n flatten_to_2d(bool): Whether to flatten output prior boxes and variance\n to 2D shape, the second dim is 4. Default: False.\n 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 :ref:`api_guide_Name`\n \n Returns:\n Tuple: A tuple with two Variable (boxes, variances)\n\n boxes: the output density prior boxes of PriorBox.\n 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.\n 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.\n 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.\n\n variances: the expanded variances of PriorBox.\n 4-D tensor, the layout is [H, W, num_priors, 4] when flatten_to_2d is False.\n 2-D tensor, the layout is [H * W * num_priors, 4] when flatten_to_2d is True.\n 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.\n\n\n Examples:\n\n .. code-block:: python\n\n #declarative mode\n\n import paddle.fluid as fluid\n import numpy as np\n\n input = fluid.data(name="input", shape=[None,3,6,9])\n image = fluid.data(name="image", shape=[None,3,9,12])\n box, var = fluid.layers.density_prior_box(\n input=input,\n image=image,\n densities=[4, 2, 1],\n fixed_sizes=[32.0, 64.0, 128.0],\n fixed_ratios=[1.],\n clip=True,\n flatten_to_2d=True)\n\n place = fluid.CPUPlace()\n exe = fluid.Executor(place)\n exe.run(fluid.default_startup_program())\n \n # prepare a batch of data\n input_data = np.random.rand(1,3,6,9).astype("float32")\n image_data = np.random.rand(1,3,9,12).astype("float32")\n\n box_out, var_out = exe.run(\n fluid.default_main_program(),\n feed={"input":input_data,\n "image":image_data},\n fetch_list=[box,var],\n return_numpy=True)\n\n # print(box_out.shape)\n # (1134, 4)\n # print(var_out.shape)\n # (1134, 4)\n\n\n #imperative mode\n import paddle.fluid.dygraph as dg\n\n with dg.guard(place) as g:\n input = dg.to_variable(input_data)\n image = dg.to_variable(image_data)\n box, var = fluid.layers.density_prior_box(\n input=input,\n image=image,\n densities=[4, 2, 1],\n fixed_sizes=[32.0, 64.0, 128.0],\n fixed_ratios=[1.],\n clip=True)\n\n # print(box.shape)\n # [6L, 9L, 21L, 4L]\n # print(var.shape)\n # [6L, 9L, 21L, 4L]\n\n '
helper = LayerHelper('density_prior_box', **locals())
dtype = helper.input_dtype()
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'density_prior_box')
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
check_type(densities, 'densities', (list, tuple), 'density_prior_box')
check_type(fixed_sizes, 'fixed_sizes', (list, tuple), 'density_prior_box')
check_type(fixed_ratios, 'fixed_ratios', (list, tuple), 'density_prior_box')
if (len(densities) != len(fixed_sizes)):
raise ValueError('densities and fixed_sizes length should be euqal.')
if (not (_is_list_or_tuple_(steps) and (len(steps) == 2))):
raise ValueError('steps should be a list or tuple ', 'with length 2, (step_width, step_height).')
densities = list(map(int, densities))
fixed_sizes = list(map(float, fixed_sizes))
fixed_ratios = list(map(float, fixed_ratios))
steps = list(map(float, steps))
attrs = {'variances': variance, 'clip': clip, 'step_w': steps[0], 'step_h': steps[1], 'offset': offset, 'densities': densities, 'fixed_sizes': fixed_sizes, 'fixed_ratios': fixed_ratios, 'flatten_to_2d': flatten_to_2d}
box = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='density_prior_box', inputs={'Input': input, 'Image': image}, outputs={'Boxes': box, 'Variances': var}, attrs=attrs)
box.stop_gradient = True
var.stop_gradient = True
return (box, var) |
def 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):
"\n\t:api_attr: Static Graph\n\n Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes,\n regression location and classification confidence on multiple input feature\n maps, then output the concatenate results. The details of this algorithm,\n please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector\n <https://arxiv.org/abs/1512.02325>`_ .\n\n Args:\n inputs (list(Variable)|tuple(Variable)): The list of input variables,\n the format of all Variables are 4-D Tensor, layout is NCHW.\n Data type should be float32 or float64.\n image (Variable): The input image, layout is NCHW. Data type should be\n the same as inputs.\n base_size(int): the base_size is input image size. When len(inputs) > 2\n and `min_size` and `max_size` are None, the `min_size` and `max_size`\n are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The\n formula is as follows:\n\n .. code-block:: text\n\n min_sizes = []\n max_sizes = []\n step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))\n for ratio in six.moves.range(min_ratio, max_ratio + 1, step):\n min_sizes.append(base_size * ratio / 100.)\n max_sizes.append(base_size * (ratio + step) / 100.)\n min_sizes = [base_size * .10] + min_sizes\n max_sizes = [base_size * .20] + max_sizes\n\n num_classes(int): The number of classes.\n aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated\n prior boxes. The length of input and aspect_ratios must be equal.\n min_ratio(int): the min ratio of generated prior boxes.\n max_ratio(int): the max ratio of generated prior boxes.\n min_sizes(list|tuple|None): If `len(inputs) <=2`,\n min_sizes must be set up, and the length of min_sizes\n should equal to the length of inputs. Default: None.\n max_sizes(list|tuple|None): If `len(inputs) <=2`,\n max_sizes must be set up, and the length of min_sizes\n should equal to the length of inputs. Default: None.\n steps(list|tuple): If step_w and step_h are the same,\n step_w and step_h can be replaced by steps.\n step_w(list|tuple): Prior boxes step\n across width. If step_w[i] == 0.0, the prior boxes step\n across width of the inputs[i] will be automatically\n calculated. Default: None.\n step_h(list|tuple): Prior boxes step across height, If\n step_h[i] == 0.0, the prior boxes step across height of\n the inputs[i] will be automatically calculated. Default: None.\n offset(float): Prior boxes center offset. Default: 0.5\n variance(list|tuple): the variances to be encoded in prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n flip(bool): Whether to flip aspect ratios. Default:False.\n clip(bool): Whether to clip out-of-boundary boxes. Default: False.\n kernel_size(int): The kernel size of conv2d. Default: 1.\n pad(int|list|tuple): The padding of conv2d. Default:0.\n stride(int|list|tuple): The stride of conv2d. Default:1,\n name(str): The default value is None. Normally there is no need\n for user to set this property. For more information, please\n refer to :ref:`api_guide_Name`.\n min_max_aspect_ratios_order(bool): If set True, the output prior box is\n in order of [min, max, aspect_ratios], which is consistent with\n Caffe. Please note, this order affects the weights order of\n convolution layer followed by and does not affect the final\n detection results. Default: False.\n\n Returns:\n tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)\n\n mbox_loc (Variable): The predicted boxes' location of the inputs. The\n layout is [N, num_priors, 4], where N is batch size, ``num_priors``\n is the number of prior boxes. Data type is the same as input.\n\n mbox_conf (Variable): The predicted boxes' confidence of the inputs.\n The layout is [N, num_priors, C], where ``N`` and ``num_priors`` \n has the same meaning as above. C is the number of Classes.\n Data type is the same as input.\n\n boxes (Variable): the output prior boxes. The layout is [num_priors, 4].\n The meaning of num_priors is the same as above.\n Data type is the same as input.\n\n variances (Variable): the expanded variances for prior boxes.\n The layout is [num_priors, 4]. Data type is the same as input.\n\n Examples 1: set min_ratio and max_ratio:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')\n conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')\n conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')\n conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')\n conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')\n conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')\n conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')\n\n mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(\n inputs=[conv1, conv2, conv3, conv4, conv5, conv6],\n image=images,\n num_classes=21,\n min_ratio=20,\n max_ratio=90,\n aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],\n base_size=300,\n offset=0.5,\n flip=True,\n clip=True)\n\n Examples 2: set min_sizes and max_sizes:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')\n conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')\n conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')\n conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')\n conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')\n conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')\n conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')\n\n mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(\n inputs=[conv1, conv2, conv3, conv4, conv5, conv6],\n image=images,\n num_classes=21,\n min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0],\n max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0],\n aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],\n base_size=300,\n offset=0.5,\n flip=True,\n clip=True)\n\n "
def _reshape_with_axis_(input, axis=1):
out = nn.flatten(x=input, axis=axis)
return out
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
def _is_list_or_tuple_and_equal(data, length, err_info):
if (not (_is_list_or_tuple_(data) and (len(data) == length))):
raise ValueError(err_info)
if (not _is_list_or_tuple_(inputs)):
raise ValueError('inputs should be a list or tuple.')
num_layer = len(inputs)
if (num_layer <= 2):
assert ((min_sizes is not None) and (max_sizes is not None))
assert ((len(min_sizes) == num_layer) and (len(max_sizes) == num_layer))
elif ((min_sizes is None) and (max_sizes is None)):
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.0))
max_sizes.append(((base_size * (ratio + step)) / 100.0))
min_sizes = ([(base_size * 0.1)] + min_sizes)
max_sizes = ([(base_size * 0.2)] + max_sizes)
if aspect_ratios:
_is_list_or_tuple_and_equal(aspect_ratios, num_layer, 'aspect_ratios should be list or tuple, and the length of inputs and aspect_ratios should be the same.')
if (step_h is not None):
_is_list_or_tuple_and_equal(step_h, num_layer, 'step_h should be list or tuple, and the length of inputs and step_h should be the same.')
if (step_w is not None):
_is_list_or_tuple_and_equal(step_w, num_layer, 'step_w should be list or tuple, and the length of inputs and step_w should be the same.')
if (steps is not None):
_is_list_or_tuple_and_equal(steps, num_layer, 'steps should be list or tuple, and the length of inputs and step_w should be the same.')
step_w = steps
step_h = steps
mbox_locs = []
mbox_confs = []
box_results = []
var_results = []
for (i, input) in enumerate(inputs):
min_size = min_sizes[i]
max_size = max_sizes[i]
if (not _is_list_or_tuple_(min_size)):
min_size = [min_size]
if (not _is_list_or_tuple_(max_size)):
max_size = [max_size]
aspect_ratio = []
if (aspect_ratios is not None):
aspect_ratio = aspect_ratios[i]
if (not _is_list_or_tuple_(aspect_ratio)):
aspect_ratio = [aspect_ratio]
step = [(step_w[i] if step_w else 0.0), (step_h[i] if step_w else 0.0)]
(box, var) = prior_box(input, image, min_size, max_size, aspect_ratio, variance, flip, clip, step, offset, None, min_max_aspect_ratios_order)
box_results.append(box)
var_results.append(var)
num_boxes = box.shape[2]
num_loc_output = (num_boxes * 4)
mbox_loc = nn.conv2d(input=input, num_filters=num_loc_output, filter_size=kernel_size, padding=pad, stride=stride)
mbox_loc = nn.transpose(mbox_loc, perm=[0, 2, 3, 1])
mbox_loc_flatten = nn.flatten(mbox_loc, axis=1)
mbox_locs.append(mbox_loc_flatten)
num_conf_output = (num_boxes * num_classes)
conf_loc = nn.conv2d(input=input, num_filters=num_conf_output, filter_size=kernel_size, padding=pad, stride=stride)
conf_loc = nn.transpose(conf_loc, perm=[0, 2, 3, 1])
conf_loc_flatten = nn.flatten(conf_loc, axis=1)
mbox_confs.append(conf_loc_flatten)
if (len(box_results) == 1):
box = box_results[0]
var = var_results[0]
mbox_locs_concat = mbox_locs[0]
mbox_confs_concat = mbox_confs[0]
else:
reshaped_boxes = []
reshaped_vars = []
for i in range(len(box_results)):
reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3))
reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3))
box = tensor.concat(reshaped_boxes)
var = tensor.concat(reshaped_vars)
mbox_locs_concat = tensor.concat(mbox_locs, axis=1)
mbox_locs_concat = nn.reshape(mbox_locs_concat, shape=[0, (- 1), 4])
mbox_confs_concat = tensor.concat(mbox_confs, axis=1)
mbox_confs_concat = nn.reshape(mbox_confs_concat, shape=[0, (- 1), num_classes])
box.stop_gradient = True
var.stop_gradient = True
return (mbox_locs_concat, mbox_confs_concat, box, var) | -2,723,292,436,989,180,400 | :api_attr: Static Graph
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
<https://arxiv.org/abs/1512.02325>`_ .
Args:
inputs (list(Variable)|tuple(Variable)): The list of input variables,
the format of all Variables are 4-D 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:
.. code-block:: text
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(list|tuple|None): 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(list|tuple|None): 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(list|tuple): If step_w and step_h are the same,
step_w and step_h can be replaced by steps.
step_w(list|tuple): 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(list|tuple): 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(list|tuple): 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 out-of-boundary boxes. Default: False.
kernel_size(int): The kernel size of conv2d. Default: 1.
pad(int|list|tuple): The padding of conv2d. Default:0.
stride(int|list|tuple): 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 :ref:`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 final
detection results. Default: False.
Returns:
tuple: 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`` and ``num_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.
Examples 1: set min_ratio and max_ratio:
.. code-block:: python
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:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | multi_box_head | 92lqllearning/Paddle | python | def 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):
"\n\t:api_attr: Static Graph\n\n Base on SSD ((Single Shot MultiBox Detector) algorithm, generate prior boxes,\n regression location and classification confidence on multiple input feature\n maps, then output the concatenate results. The details of this algorithm,\n please refer the section 2.2 of SSD paper `SSD: Single Shot MultiBox Detector\n <https://arxiv.org/abs/1512.02325>`_ .\n\n Args:\n inputs (list(Variable)|tuple(Variable)): The list of input variables,\n the format of all Variables are 4-D Tensor, layout is NCHW.\n Data type should be float32 or float64.\n image (Variable): The input image, layout is NCHW. Data type should be\n the same as inputs.\n base_size(int): the base_size is input image size. When len(inputs) > 2\n and `min_size` and `max_size` are None, the `min_size` and `max_size`\n are calculated by `baze_size`, 'min_ratio' and `max_ratio`. The\n formula is as follows:\n\n .. code-block:: text\n\n min_sizes = []\n max_sizes = []\n step = int(math.floor(((max_ratio - min_ratio)) / (num_layer - 2)))\n for ratio in six.moves.range(min_ratio, max_ratio + 1, step):\n min_sizes.append(base_size * ratio / 100.)\n max_sizes.append(base_size * (ratio + step) / 100.)\n min_sizes = [base_size * .10] + min_sizes\n max_sizes = [base_size * .20] + max_sizes\n\n num_classes(int): The number of classes.\n aspect_ratios(list(float) | tuple(float)): the aspect ratios of generated\n prior boxes. The length of input and aspect_ratios must be equal.\n min_ratio(int): the min ratio of generated prior boxes.\n max_ratio(int): the max ratio of generated prior boxes.\n min_sizes(list|tuple|None): If `len(inputs) <=2`,\n min_sizes must be set up, and the length of min_sizes\n should equal to the length of inputs. Default: None.\n max_sizes(list|tuple|None): If `len(inputs) <=2`,\n max_sizes must be set up, and the length of min_sizes\n should equal to the length of inputs. Default: None.\n steps(list|tuple): If step_w and step_h are the same,\n step_w and step_h can be replaced by steps.\n step_w(list|tuple): Prior boxes step\n across width. If step_w[i] == 0.0, the prior boxes step\n across width of the inputs[i] will be automatically\n calculated. Default: None.\n step_h(list|tuple): Prior boxes step across height, If\n step_h[i] == 0.0, the prior boxes step across height of\n the inputs[i] will be automatically calculated. Default: None.\n offset(float): Prior boxes center offset. Default: 0.5\n variance(list|tuple): the variances to be encoded in prior boxes.\n Default:[0.1, 0.1, 0.2, 0.2].\n flip(bool): Whether to flip aspect ratios. Default:False.\n clip(bool): Whether to clip out-of-boundary boxes. Default: False.\n kernel_size(int): The kernel size of conv2d. Default: 1.\n pad(int|list|tuple): The padding of conv2d. Default:0.\n stride(int|list|tuple): The stride of conv2d. Default:1,\n name(str): The default value is None. Normally there is no need\n for user to set this property. For more information, please\n refer to :ref:`api_guide_Name`.\n min_max_aspect_ratios_order(bool): If set True, the output prior box is\n in order of [min, max, aspect_ratios], which is consistent with\n Caffe. Please note, this order affects the weights order of\n convolution layer followed by and does not affect the final\n detection results. Default: False.\n\n Returns:\n tuple: A tuple with four Variables. (mbox_loc, mbox_conf, boxes, variances)\n\n mbox_loc (Variable): The predicted boxes' location of the inputs. The\n layout is [N, num_priors, 4], where N is batch size, ``num_priors``\n is the number of prior boxes. Data type is the same as input.\n\n mbox_conf (Variable): The predicted boxes' confidence of the inputs.\n The layout is [N, num_priors, C], where ``N`` and ``num_priors`` \n has the same meaning as above. C is the number of Classes.\n Data type is the same as input.\n\n boxes (Variable): the output prior boxes. The layout is [num_priors, 4].\n The meaning of num_priors is the same as above.\n Data type is the same as input.\n\n variances (Variable): the expanded variances for prior boxes.\n The layout is [num_priors, 4]. Data type is the same as input.\n\n Examples 1: set min_ratio and max_ratio:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')\n conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')\n conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')\n conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')\n conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')\n conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')\n conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')\n\n mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(\n inputs=[conv1, conv2, conv3, conv4, conv5, conv6],\n image=images,\n num_classes=21,\n min_ratio=20,\n max_ratio=90,\n aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],\n base_size=300,\n offset=0.5,\n flip=True,\n clip=True)\n\n Examples 2: set min_sizes and max_sizes:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n images = fluid.data(name='data', shape=[None, 3, 300, 300], dtype='float32')\n conv1 = fluid.data(name='conv1', shape=[None, 512, 19, 19], dtype='float32')\n conv2 = fluid.data(name='conv2', shape=[None, 1024, 10, 10], dtype='float32')\n conv3 = fluid.data(name='conv3', shape=[None, 512, 5, 5], dtype='float32')\n conv4 = fluid.data(name='conv4', shape=[None, 256, 3, 3], dtype='float32')\n conv5 = fluid.data(name='conv5', shape=[None, 256, 2, 2], dtype='float32')\n conv6 = fluid.data(name='conv6', shape=[None, 128, 1, 1], dtype='float32')\n\n mbox_locs, mbox_confs, box, var = fluid.layers.multi_box_head(\n inputs=[conv1, conv2, conv3, conv4, conv5, conv6],\n image=images,\n num_classes=21,\n min_sizes=[60.0, 105.0, 150.0, 195.0, 240.0, 285.0],\n max_sizes=[[], 150.0, 195.0, 240.0, 285.0, 300.0],\n aspect_ratios=[[2.], [2., 3.], [2., 3.], [2., 3.], [2.], [2.]],\n base_size=300,\n offset=0.5,\n flip=True,\n clip=True)\n\n "
def _reshape_with_axis_(input, axis=1):
out = nn.flatten(x=input, axis=axis)
return out
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
def _is_list_or_tuple_and_equal(data, length, err_info):
if (not (_is_list_or_tuple_(data) and (len(data) == length))):
raise ValueError(err_info)
if (not _is_list_or_tuple_(inputs)):
raise ValueError('inputs should be a list or tuple.')
num_layer = len(inputs)
if (num_layer <= 2):
assert ((min_sizes is not None) and (max_sizes is not None))
assert ((len(min_sizes) == num_layer) and (len(max_sizes) == num_layer))
elif ((min_sizes is None) and (max_sizes is None)):
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.0))
max_sizes.append(((base_size * (ratio + step)) / 100.0))
min_sizes = ([(base_size * 0.1)] + min_sizes)
max_sizes = ([(base_size * 0.2)] + max_sizes)
if aspect_ratios:
_is_list_or_tuple_and_equal(aspect_ratios, num_layer, 'aspect_ratios should be list or tuple, and the length of inputs and aspect_ratios should be the same.')
if (step_h is not None):
_is_list_or_tuple_and_equal(step_h, num_layer, 'step_h should be list or tuple, and the length of inputs and step_h should be the same.')
if (step_w is not None):
_is_list_or_tuple_and_equal(step_w, num_layer, 'step_w should be list or tuple, and the length of inputs and step_w should be the same.')
if (steps is not None):
_is_list_or_tuple_and_equal(steps, num_layer, 'steps should be list or tuple, and the length of inputs and step_w should be the same.')
step_w = steps
step_h = steps
mbox_locs = []
mbox_confs = []
box_results = []
var_results = []
for (i, input) in enumerate(inputs):
min_size = min_sizes[i]
max_size = max_sizes[i]
if (not _is_list_or_tuple_(min_size)):
min_size = [min_size]
if (not _is_list_or_tuple_(max_size)):
max_size = [max_size]
aspect_ratio = []
if (aspect_ratios is not None):
aspect_ratio = aspect_ratios[i]
if (not _is_list_or_tuple_(aspect_ratio)):
aspect_ratio = [aspect_ratio]
step = [(step_w[i] if step_w else 0.0), (step_h[i] if step_w else 0.0)]
(box, var) = prior_box(input, image, min_size, max_size, aspect_ratio, variance, flip, clip, step, offset, None, min_max_aspect_ratios_order)
box_results.append(box)
var_results.append(var)
num_boxes = box.shape[2]
num_loc_output = (num_boxes * 4)
mbox_loc = nn.conv2d(input=input, num_filters=num_loc_output, filter_size=kernel_size, padding=pad, stride=stride)
mbox_loc = nn.transpose(mbox_loc, perm=[0, 2, 3, 1])
mbox_loc_flatten = nn.flatten(mbox_loc, axis=1)
mbox_locs.append(mbox_loc_flatten)
num_conf_output = (num_boxes * num_classes)
conf_loc = nn.conv2d(input=input, num_filters=num_conf_output, filter_size=kernel_size, padding=pad, stride=stride)
conf_loc = nn.transpose(conf_loc, perm=[0, 2, 3, 1])
conf_loc_flatten = nn.flatten(conf_loc, axis=1)
mbox_confs.append(conf_loc_flatten)
if (len(box_results) == 1):
box = box_results[0]
var = var_results[0]
mbox_locs_concat = mbox_locs[0]
mbox_confs_concat = mbox_confs[0]
else:
reshaped_boxes = []
reshaped_vars = []
for i in range(len(box_results)):
reshaped_boxes.append(_reshape_with_axis_(box_results[i], axis=3))
reshaped_vars.append(_reshape_with_axis_(var_results[i], axis=3))
box = tensor.concat(reshaped_boxes)
var = tensor.concat(reshaped_vars)
mbox_locs_concat = tensor.concat(mbox_locs, axis=1)
mbox_locs_concat = nn.reshape(mbox_locs_concat, shape=[0, (- 1), 4])
mbox_confs_concat = tensor.concat(mbox_confs, axis=1)
mbox_confs_concat = nn.reshape(mbox_confs_concat, shape=[0, (- 1), num_classes])
box.stop_gradient = True
var.stop_gradient = True
return (mbox_locs_concat, mbox_confs_concat, box, var) |
def 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):
"\n\t:alias_main: paddle.nn.functional.anchor_generator\n\t:alias: paddle.nn.functional.anchor_generator,paddle.nn.functional.vision.anchor_generator\n\t:old_api: paddle.fluid.layers.anchor_generator\n\n **Anchor generator operator**\n\n Generate anchors for Faster RCNN algorithm.\n Each position of the input produce N anchors, N =\n size(anchor_sizes) * size(aspect_ratios). The order of generated anchors\n is firstly aspect_ratios loop then anchor_sizes loop.\n\n Args:\n input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.\n anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated\n anchors, given in absolute pixels e.g. [64., 128., 256., 512.].\n For instance, the anchor size of 64 means the area of this anchor \n equals to 64**2. None by default.\n aspect_ratios(float32|list|tuple, optional): The height / width ratios \n of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.\n variance(list|tuple, optional): The variances to be used in box \n regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by \n default.\n stride(list|tuple, optional): The anchors stride across width and height.\n The data type is float32. e.g. [16.0, 16.0]. None by default.\n offset(float32, optional): Prior boxes center offset. 0.5 by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and None \n by default. \n\n Returns:\n Tuple:\n\n Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4].\n H is the height of input, W is the width of input,\n num_anchors is the box count of each position. \n Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.\n \n Variances(Variable): The expanded variances of anchors\n with a layout of [H, W, num_priors, 4].\n H is the height of input, W is the width of input\n num_anchors is the box count of each position.\n Each variance is in (xcenter, ycenter, w, h) format.\n\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32')\n anchor, var = fluid.layers.anchor_generator(\n input=conv1,\n anchor_sizes=[64, 128, 256, 512],\n aspect_ratios=[0.5, 1.0, 2.0],\n variance=[0.1, 0.1, 0.2, 0.2],\n stride=[16.0, 16.0],\n offset=0.5)\n "
helper = LayerHelper('anchor_generator', **locals())
dtype = helper.input_dtype()
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if (not _is_list_or_tuple_(anchor_sizes)):
anchor_sizes = [anchor_sizes]
if (not _is_list_or_tuple_(aspect_ratios)):
aspect_ratios = [aspect_ratios]
if (not (_is_list_or_tuple_(stride) and (len(stride) == 2))):
raise ValueError('stride should be a list or tuple ', 'with length 2, (stride_width, stride_height).')
anchor_sizes = list(map(float, anchor_sizes))
aspect_ratios = list(map(float, aspect_ratios))
stride = list(map(float, stride))
attrs = {'anchor_sizes': anchor_sizes, 'aspect_ratios': aspect_ratios, 'variances': variance, 'stride': stride, 'offset': offset}
anchor = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='anchor_generator', inputs={'Input': input}, outputs={'Anchors': anchor, 'Variances': var}, attrs=attrs)
anchor.stop_gradient = True
var.stop_gradient = True
return (anchor, var) | 6,149,320,233,878,684,000 | :alias_main: paddle.nn.functional.anchor_generator
:alias: paddle.nn.functional.anchor_generator,paddle.nn.functional.vision.anchor_generator
:old_api: paddle.fluid.layers.anchor_generator
**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.
Args:
input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.
anchor_sizes(float32|list|tuple, 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(float32|list|tuple, optional): The height / width ratios
of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.
variance(list|tuple, 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(list|tuple, 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 :ref:`api_guide_Name`. Usually name is no need to set and None
by default.
Returns:
Tuple:
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.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | anchor_generator | 92lqllearning/Paddle | python | def 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):
"\n\t:alias_main: paddle.nn.functional.anchor_generator\n\t:alias: paddle.nn.functional.anchor_generator,paddle.nn.functional.vision.anchor_generator\n\t:old_api: paddle.fluid.layers.anchor_generator\n\n **Anchor generator operator**\n\n Generate anchors for Faster RCNN algorithm.\n Each position of the input produce N anchors, N =\n size(anchor_sizes) * size(aspect_ratios). The order of generated anchors\n is firstly aspect_ratios loop then anchor_sizes loop.\n\n Args:\n input(Variable): 4-D Tensor with shape [N,C,H,W]. The input feature map.\n anchor_sizes(float32|list|tuple, optional): The anchor sizes of generated\n anchors, given in absolute pixels e.g. [64., 128., 256., 512.].\n For instance, the anchor size of 64 means the area of this anchor \n equals to 64**2. None by default.\n aspect_ratios(float32|list|tuple, optional): The height / width ratios \n of generated anchors, e.g. [0.5, 1.0, 2.0]. None by default.\n variance(list|tuple, optional): The variances to be used in box \n regression deltas. The data type is float32, [0.1, 0.1, 0.2, 0.2] by \n default.\n stride(list|tuple, optional): The anchors stride across width and height.\n The data type is float32. e.g. [16.0, 16.0]. None by default.\n offset(float32, optional): Prior boxes center offset. 0.5 by default.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and None \n by default. \n\n Returns:\n Tuple:\n\n Anchors(Variable): The output anchors with a layout of [H, W, num_anchors, 4].\n H is the height of input, W is the width of input,\n num_anchors is the box count of each position. \n Each anchor is in (xmin, ymin, xmax, ymax) format an unnormalized.\n \n Variances(Variable): The expanded variances of anchors\n with a layout of [H, W, num_priors, 4].\n H is the height of input, W is the width of input\n num_anchors is the box count of each position.\n Each variance is in (xcenter, ycenter, w, h) format.\n\n\n Examples:\n\n .. code-block:: python\n\n import paddle.fluid as fluid\n conv1 = fluid.data(name='conv1', shape=[None, 48, 16, 16], dtype='float32')\n anchor, var = fluid.layers.anchor_generator(\n input=conv1,\n anchor_sizes=[64, 128, 256, 512],\n aspect_ratios=[0.5, 1.0, 2.0],\n variance=[0.1, 0.1, 0.2, 0.2],\n stride=[16.0, 16.0],\n offset=0.5)\n "
helper = LayerHelper('anchor_generator', **locals())
dtype = helper.input_dtype()
def _is_list_or_tuple_(data):
return (isinstance(data, list) or isinstance(data, tuple))
if (not _is_list_or_tuple_(anchor_sizes)):
anchor_sizes = [anchor_sizes]
if (not _is_list_or_tuple_(aspect_ratios)):
aspect_ratios = [aspect_ratios]
if (not (_is_list_or_tuple_(stride) and (len(stride) == 2))):
raise ValueError('stride should be a list or tuple ', 'with length 2, (stride_width, stride_height).')
anchor_sizes = list(map(float, anchor_sizes))
aspect_ratios = list(map(float, aspect_ratios))
stride = list(map(float, stride))
attrs = {'anchor_sizes': anchor_sizes, 'aspect_ratios': aspect_ratios, 'variances': variance, 'stride': stride, 'offset': offset}
anchor = helper.create_variable_for_type_inference(dtype)
var = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='anchor_generator', inputs={'Input': input}, outputs={'Anchors': anchor, 'Variances': var}, attrs=attrs)
anchor.stop_gradient = True
var.stop_gradient = True
return (anchor, var) |
def roi_perspective_transform(input, rois, transformed_height, transformed_width, spatial_scale=1.0, name=None):
"\n **The** `rois` **of this op should be a LoDTensor.**\n\n ROI perspective transform op applies perspective transform to map each roi into an \n rectangular region. Perspective transform is a type of transformation in linear algebra.\n\n Parameters:\n input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of \n input tensor is NCHW. Where N is batch size, C is the\n number of input channels, H is the height of the feature,\n and W is the width of the feature. The data type is float32.\n rois (Variable): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed. \n It should be a 2-D LoDTensor of shape (num_rois, 8). Given as \n [[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the \n top left coordinates, and (x2, y2) is the top right \n coordinates, and (x3, y3) is the bottom right coordinates, \n and (x4, y4) is the bottom left coordinates. The data type is the\n same as `input` \n transformed_height (int): The height of transformed output.\n transformed_width (int): The width of transformed output.\n spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0\n name(str, optional): The default value is None. \n Normally there is no need for user to set this property. \n For more information, please refer to :ref:`api_guide_Name`\n\n Returns:\n A tuple with three Variables. (out, mask, transform_matrix)\n\n out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape\n (num_rois, channels, transformed_h, transformed_w). The data type is the same as `input`\n\n mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape\n (num_rois, 1, transformed_h, transformed_w). The data type is int32\n\n transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is\n a 2-D tensor with shape (num_rois, 9). The data type is the same as `input`\n\n Return Type:\n tuple\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32')\n rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32')\n out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)\n "
check_variable_and_dtype(input, 'input', ['float32'], 'roi_perspective_transform')
check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_perspective_transform')
check_type(transformed_height, 'transformed_height', int, 'roi_perspective_transform')
check_type(transformed_width, 'transformed_width', int, 'roi_perspective_transform')
check_type(spatial_scale, 'spatial_scale', float, 'roi_perspective_transform')
helper = LayerHelper('roi_perspective_transform', **locals())
dtype = helper.input_dtype()
out = helper.create_variable_for_type_inference(dtype)
mask = helper.create_variable_for_type_inference(dtype='int32')
transform_matrix = helper.create_variable_for_type_inference(dtype)
out2in_idx = helper.create_variable_for_type_inference(dtype='int32')
out2in_w = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='roi_perspective_transform', inputs={'X': input, 'ROIs': rois}, outputs={'Out': out, 'Out2InIdx': out2in_idx, 'Out2InWeights': out2in_w, 'Mask': mask, 'TransformMatrix': transform_matrix}, attrs={'transformed_height': transformed_height, 'transformed_width': transformed_width, 'spatial_scale': spatial_scale})
return (out, mask, transform_matrix) | -6,383,202,107,289,695,000 | **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): 4-D 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): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed.
It should be a 2-D 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 :ref:`api_guide_Name`
Returns:
A tuple with three Variables. (out, mask, transform_matrix)
out: The output of ROIPerspectiveTransformOp which is a 4-D 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 4-D 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 2-D tensor with shape (num_rois, 9). The data type is the same as `input`
Return Type:
tuple
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | roi_perspective_transform | 92lqllearning/Paddle | python | def roi_perspective_transform(input, rois, transformed_height, transformed_width, spatial_scale=1.0, name=None):
"\n **The** `rois` **of this op should be a LoDTensor.**\n\n ROI perspective transform op applies perspective transform to map each roi into an \n rectangular region. Perspective transform is a type of transformation in linear algebra.\n\n Parameters:\n input (Variable): 4-D Tensor, input of ROIPerspectiveTransformOp. The format of \n input tensor is NCHW. Where N is batch size, C is the\n number of input channels, H is the height of the feature,\n and W is the width of the feature. The data type is float32.\n rois (Variable): 2-D LoDTensor, ROIs (Regions of Interest) to be transformed. \n It should be a 2-D LoDTensor of shape (num_rois, 8). Given as \n [[x1, y1, x2, y2, x3, y3, x4, y4], ...], (x1, y1) is the \n top left coordinates, and (x2, y2) is the top right \n coordinates, and (x3, y3) is the bottom right coordinates, \n and (x4, y4) is the bottom left coordinates. The data type is the\n same as `input` \n transformed_height (int): The height of transformed output.\n transformed_width (int): The width of transformed output.\n spatial_scale (float): Spatial scale factor to scale ROI coords. Default: 1.0\n name(str, optional): The default value is None. \n Normally there is no need for user to set this property. \n For more information, please refer to :ref:`api_guide_Name`\n\n Returns:\n A tuple with three Variables. (out, mask, transform_matrix)\n\n out: The output of ROIPerspectiveTransformOp which is a 4-D tensor with shape\n (num_rois, channels, transformed_h, transformed_w). The data type is the same as `input`\n\n mask: The mask of ROIPerspectiveTransformOp which is a 4-D tensor with shape\n (num_rois, 1, transformed_h, transformed_w). The data type is int32\n\n transform_matrix: The transform matrix of ROIPerspectiveTransformOp which is\n a 2-D tensor with shape (num_rois, 9). The data type is the same as `input`\n\n Return Type:\n tuple\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n x = fluid.data(name='x', shape=[100, 256, 28, 28], dtype='float32')\n rois = fluid.data(name='rois', shape=[None, 8], lod_level=1, dtype='float32')\n out, mask, transform_matrix = fluid.layers.roi_perspective_transform(x, rois, 7, 7, 1.0)\n "
check_variable_and_dtype(input, 'input', ['float32'], 'roi_perspective_transform')
check_variable_and_dtype(rois, 'rois', ['float32'], 'roi_perspective_transform')
check_type(transformed_height, 'transformed_height', int, 'roi_perspective_transform')
check_type(transformed_width, 'transformed_width', int, 'roi_perspective_transform')
check_type(spatial_scale, 'spatial_scale', float, 'roi_perspective_transform')
helper = LayerHelper('roi_perspective_transform', **locals())
dtype = helper.input_dtype()
out = helper.create_variable_for_type_inference(dtype)
mask = helper.create_variable_for_type_inference(dtype='int32')
transform_matrix = helper.create_variable_for_type_inference(dtype)
out2in_idx = helper.create_variable_for_type_inference(dtype='int32')
out2in_w = helper.create_variable_for_type_inference(dtype)
helper.append_op(type='roi_perspective_transform', inputs={'X': input, 'ROIs': rois}, outputs={'Out': out, 'Out2InIdx': out2in_idx, 'Out2InWeights': out2in_w, 'Mask': mask, 'TransformMatrix': transform_matrix}, attrs={'transformed_height': transformed_height, 'transformed_width': transformed_width, 'spatial_scale': spatial_scale})
return (out, mask, transform_matrix) |
def 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):
"\n\t:alias_main: paddle.nn.functional.generate_proposal_labels\n\t:alias: paddle.nn.functional.generate_proposal_labels,paddle.nn.functional.vision.generate_proposal_labels\n\t:old_api: paddle.fluid.layers.generate_proposal_labels\n\n **Generate Proposal Labels of Faster-RCNN**\n\n This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth,\n to sample foreground boxes and background boxes, and compute loss target.\n\n RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes\n were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction,\n If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample.\n If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi,\n then it was considered as a background sample.\n After all foreground and background boxes are chosen (so called Rois),\n then we apply random sampling to make sure\n the number of foreground boxes is no more than batch_size_per_im * fg_fraction.\n\n For each box in Rois, we assign the classification (class label) and regression targets (box label) to it.\n Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.\n\n Args:\n rpn_rois(Variable): A 2-D 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.\n gt_classes(Variable): A 2-D 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.\n is_crowd(Variable): A 2-D 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.\n gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.\n im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.\n\n batch_size_per_im(int): Batch size of rois per images. The data type must be int32.\n fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32.\n fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32.\n bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32.\n bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32.\n bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32.\n class_nums(int): Class number. The data type must be int32.\n use_random(bool): Use random sampling to choose foreground and background boxes.\n is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes.\n is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True.\n\n Returns:\n tuple:\n A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.\n\n - **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.\n - **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.\n - **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.\n - **bbox_inside_weights**: 2-D 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 as ``rpn_rois``.\n - **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32')\n gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='float32')\n is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='float32')\n gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')\n im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')\n rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels(\n rpn_rois, gt_classes, is_crowd, gt_boxes, im_info,\n class_nums=10)\n\n "
helper = LayerHelper('generate_proposal_labels', **locals())
check_variable_and_dtype(rpn_rois, 'rpn_rois', ['float32', 'float64'], 'generate_proposal_labels')
check_variable_and_dtype(gt_classes, 'gt_classes', ['int32'], 'generate_proposal_labels')
check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'], 'generate_proposal_labels')
rois = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
labels_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
bbox_targets = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
bbox_inside_weights = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
bbox_outside_weights = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
helper.append_op(type='generate_proposal_labels', inputs={'RpnRois': rpn_rois, 'GtClasses': gt_classes, 'IsCrowd': is_crowd, 'GtBoxes': gt_boxes, 'ImInfo': im_info}, outputs={'Rois': rois, 'LabelsInt32': labels_int32, 'BboxTargets': bbox_targets, 'BboxInsideWeights': bbox_inside_weights, 'BboxOutsideWeights': bbox_outside_weights}, attrs={'batch_size_per_im': batch_size_per_im, 'fg_fraction': fg_fraction, 'fg_thresh': fg_thresh, 'bg_thresh_hi': bg_thresh_hi, 'bg_thresh_lo': bg_thresh_lo, 'bbox_reg_weights': bbox_reg_weights, 'class_nums': class_nums, 'use_random': use_random, 'is_cls_agnostic': is_cls_agnostic, 'is_cascade_rcnn': is_cascade_rcnn})
rois.stop_gradient = True
labels_int32.stop_gradient = True
bbox_targets.stop_gradient = True
bbox_inside_weights.stop_gradient = True
bbox_outside_weights.stop_gradient = True
return (rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights) | 2,734,986,607,020,780,500 | :alias_main: paddle.nn.functional.generate_proposal_labels
:alias: paddle.nn.functional.generate_proposal_labels,paddle.nn.functional.vision.generate_proposal_labels
:old_api: paddle.fluid.layers.generate_proposal_labels
**Generate Proposal Labels of Faster-RCNN**
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.
Args:
rpn_rois(Variable): A 2-D 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 2-D 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 2-D 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 2-D 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 2-D 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(list|tuple): 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:
tuple:
A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.
- **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.
- **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.
- **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.
- **bbox_inside_weights**: 2-D 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 as ``rpn_rois``.
- **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | generate_proposal_labels | 92lqllearning/Paddle | python | def 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):
"\n\t:alias_main: paddle.nn.functional.generate_proposal_labels\n\t:alias: paddle.nn.functional.generate_proposal_labels,paddle.nn.functional.vision.generate_proposal_labels\n\t:old_api: paddle.fluid.layers.generate_proposal_labels\n\n **Generate Proposal Labels of Faster-RCNN**\n\n This operator can be, for given the GenerateProposalOp output bounding boxes and groundtruth,\n to sample foreground boxes and background boxes, and compute loss target.\n\n RpnRois is the output boxes of RPN and was processed by generate_proposal_op, these boxes\n were combined with groundtruth boxes and sampled according to batch_size_per_im and fg_fraction,\n If an instance with a groundtruth overlap greater than fg_thresh, then it was considered as a foreground sample.\n If an instance with a groundtruth overlap greater than bg_thresh_lo and lower than bg_thresh_hi,\n then it was considered as a background sample.\n After all foreground and background boxes are chosen (so called Rois),\n then we apply random sampling to make sure\n the number of foreground boxes is no more than batch_size_per_im * fg_fraction.\n\n For each box in Rois, we assign the classification (class label) and regression targets (box label) to it.\n Finally BboxInsideWeights and BboxOutsideWeights are used to specify whether it would contribute to training loss.\n\n Args:\n rpn_rois(Variable): A 2-D 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.\n gt_classes(Variable): A 2-D 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.\n is_crowd(Variable): A 2-D 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.\n gt_boxes(Variable): A 2-D LoDTensor with shape [M, 4]. M is the number of groundtruth, each element is a bounding box with [xmin, ymin, xmax, ymax] format.\n im_info(Variable): A 2-D LoDTensor with shape [B, 3]. B is the number of input images, each element consists of im_height, im_width, im_scale.\n\n batch_size_per_im(int): Batch size of rois per images. The data type must be int32.\n fg_fraction(float): Foreground fraction in total batch_size_per_im. The data type must be float32.\n fg_thresh(float): Overlap threshold which is used to chose foreground sample. The data type must be float32.\n bg_thresh_hi(float): Overlap threshold upper bound which is used to chose background sample. The data type must be float32.\n bg_thresh_lo(float): Overlap threshold lower bound which is used to chose background sample. The data type must be float32.\n bbox_reg_weights(list|tuple): Box regression weights. The data type must be float32.\n class_nums(int): Class number. The data type must be int32.\n use_random(bool): Use random sampling to choose foreground and background boxes.\n is_cls_agnostic(bool): bbox regression use class agnostic simply which only represent fg and bg boxes.\n is_cascade_rcnn(bool): it will filter some bbox crossing the image's boundary when setting True.\n\n Returns:\n tuple:\n A tuple with format``(rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights)``.\n\n - **rois**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4]``. The data type is the same as ``rpn_rois``.\n - **labels_int32**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 1]``. The data type must be int32.\n - **bbox_targets**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The regression targets of all RoIs. The data type is the same as ``rpn_rois``.\n - **bbox_inside_weights**: 2-D 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 as ``rpn_rois``.\n - **bbox_outside_weights**: 2-D LoDTensor with shape ``[batch_size_per_im * batch_size, 4 * class_num]``. The weights of regression loss. The data type is the same as ``rpn_rois``.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n rpn_rois = fluid.data(name='rpn_rois', shape=[None, 4], dtype='float32')\n gt_classes = fluid.data(name='gt_classes', shape=[None, 1], dtype='float32')\n is_crowd = fluid.data(name='is_crowd', shape=[None, 1], dtype='float32')\n gt_boxes = fluid.data(name='gt_boxes', shape=[None, 4], dtype='float32')\n im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')\n rois, labels, bbox, inside_weights, outside_weights = fluid.layers.generate_proposal_labels(\n rpn_rois, gt_classes, is_crowd, gt_boxes, im_info,\n class_nums=10)\n\n "
helper = LayerHelper('generate_proposal_labels', **locals())
check_variable_and_dtype(rpn_rois, 'rpn_rois', ['float32', 'float64'], 'generate_proposal_labels')
check_variable_and_dtype(gt_classes, 'gt_classes', ['int32'], 'generate_proposal_labels')
check_variable_and_dtype(is_crowd, 'is_crowd', ['int32'], 'generate_proposal_labels')
rois = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
labels_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
bbox_targets = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
bbox_inside_weights = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
bbox_outside_weights = helper.create_variable_for_type_inference(dtype=rpn_rois.dtype)
helper.append_op(type='generate_proposal_labels', inputs={'RpnRois': rpn_rois, 'GtClasses': gt_classes, 'IsCrowd': is_crowd, 'GtBoxes': gt_boxes, 'ImInfo': im_info}, outputs={'Rois': rois, 'LabelsInt32': labels_int32, 'BboxTargets': bbox_targets, 'BboxInsideWeights': bbox_inside_weights, 'BboxOutsideWeights': bbox_outside_weights}, attrs={'batch_size_per_im': batch_size_per_im, 'fg_fraction': fg_fraction, 'fg_thresh': fg_thresh, 'bg_thresh_hi': bg_thresh_hi, 'bg_thresh_lo': bg_thresh_lo, 'bbox_reg_weights': bbox_reg_weights, 'class_nums': class_nums, 'use_random': use_random, 'is_cls_agnostic': is_cls_agnostic, 'is_cascade_rcnn': is_cascade_rcnn})
rois.stop_gradient = True
labels_int32.stop_gradient = True
bbox_targets.stop_gradient = True
bbox_inside_weights.stop_gradient = True
bbox_outside_weights.stop_gradient = True
return (rois, labels_int32, bbox_targets, bbox_inside_weights, bbox_outside_weights) |
def generate_mask_labels(im_info, gt_classes, is_crowd, gt_segms, rois, labels_int32, num_classes, resolution):
'\n\t:alias_main: paddle.nn.functional.generate_mask_labels\n\t:alias: paddle.nn.functional.generate_mask_labels,paddle.nn.functional.vision.generate_mask_labels\n\t:old_api: paddle.fluid.layers.generate_mask_labels\n\n **Generate Mask Labels for Mask-RCNN**\n\n This operator can be, for given the RoIs and corresponding labels,\n to sample foreground RoIs. This mask branch also has\n a :math: `K \\times M^{2}` dimensional output targets for each foreground\n RoI, which encodes K binary masks of resolution M x M, one for each of the\n K classes. This mask targets are used to compute loss of mask branch.\n\n Please note, the data format of groud-truth segmentation, assumed the\n segmentations are as follows. The first instance has two gt objects.\n The second instance has one gt object, this object has two gt segmentations.\n\n .. code-block:: python\n\n #[\n # [[[229.14, 370.9, 229.14, 370.9, ...]],\n # [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance\n # [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance\n #]\n\n batch_masks = []\n for semgs in batch_semgs:\n gt_masks = []\n for semg in semgs:\n gt_segm = []\n for polys in semg:\n gt_segm.append(np.array(polys).reshape(-1, 2))\n gt_masks.append(gt_segm)\n batch_masks.append(gt_masks)\n \n \n place = fluid.CPUPlace()\n feeder = fluid.DataFeeder(place=place, feed_list=feeds)\n feeder.feed(batch_masks)\n\n Args:\n im_info (Variable): A 2-D Tensor with shape [N, 3] and float32\n data type. N is the batch size, each element is\n [height, width, scale] of image. Image scale is\n target_size / original_size, target_size is the size after resize,\n original_size is the original image size.\n gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type\n should be int. M is the total number of ground-truth, each\n element is a class label.\n is_crowd (Variable): A 2-D LoDTensor with same shape and same data type\n as gt_classes, each element is a flag indicating whether a\n groundtruth is crowd.\n gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and\n float32 data type, it\'s LoD level is 3.\n Usually users do not needs to understand LoD,\n The users should return correct data format in reader.\n The LoD[0] represents the ground-truth objects number of\n each instance. LoD[1] represents the segmentation counts of each\n objects. LoD[2] represents the polygons number of each segmentation.\n S the total number of polygons coordinate points. Each element is\n (x, y) coordinate points.\n rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type\n float32. R is the total number of RoIs, each element is a bounding\n box with (xmin, ymin, xmax, ymax) format in the range of original image.\n labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type\n of int32. R is the same as it in `rois`. Each element represents\n a class label of a RoI.\n num_classes (int): Class number.\n resolution (int): Resolution of mask predictions.\n\n Returns:\n mask_rois (Variable): A 2D LoDTensor with shape [P, 4] and same data\n type as `rois`. P is the total number of sampled RoIs. Each element\n is a bounding box with [xmin, ymin, xmax, ymax] format in range of\n original image size.\n\n mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]\n and int data type, each element represents the output mask RoI\n index with regard to input RoIs.\n\n mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int\n data type, K is the classes number and M is the resolution of mask\n predictions. Each element represents the binary mask targets.\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n im_info = fluid.data(name="im_info", shape=[None, 3],\n dtype="float32")\n gt_classes = fluid.data(name="gt_classes", shape=[None, 1],\n dtype="float32", lod_level=1)\n is_crowd = fluid.data(name="is_crowd", shape=[None, 1],\n dtype="float32", lod_level=1)\n gt_masks = fluid.data(name="gt_masks", shape=[None, 2],\n dtype="float32", lod_level=3)\n # rois, roi_labels can be the output of\n # fluid.layers.generate_proposal_labels.\n rois = fluid.data(name="rois", shape=[None, 4],\n dtype="float32", lod_level=1)\n roi_labels = fluid.data(name="roi_labels", shape=[None, 1],\n dtype="int32", lod_level=1)\n mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels(\n im_info=im_info,\n gt_classes=gt_classes,\n is_crowd=is_crowd,\n gt_segms=gt_masks,\n rois=rois,\n labels_int32=roi_labels,\n num_classes=81,\n resolution=14)\n '
helper = LayerHelper('generate_mask_labels', **locals())
mask_rois = helper.create_variable_for_type_inference(dtype=rois.dtype)
roi_has_mask_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
mask_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
helper.append_op(type='generate_mask_labels', inputs={'ImInfo': im_info, 'GtClasses': gt_classes, 'IsCrowd': is_crowd, 'GtSegms': gt_segms, 'Rois': rois, 'LabelsInt32': labels_int32}, outputs={'MaskRois': mask_rois, 'RoiHasMaskInt32': roi_has_mask_int32, 'MaskInt32': mask_int32}, attrs={'num_classes': num_classes, 'resolution': resolution})
mask_rois.stop_gradient = True
roi_has_mask_int32.stop_gradient = True
mask_int32.stop_gradient = True
return (mask_rois, roi_has_mask_int32, mask_int32) | 2,185,424,872,180,812,500 | :alias_main: paddle.nn.functional.generate_mask_labels
:alias: paddle.nn.functional.generate_mask_labels,paddle.nn.functional.vision.generate_mask_labels
:old_api: paddle.fluid.layers.generate_mask_labels
**Generate Mask Labels for Mask-RCNN**
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 groud-truth 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.
.. code-block:: python
#[
# [[[229.14, 370.9, 229.14, 370.9, ...]],
# [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance
# [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th 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)
Args:
im_info (Variable): A 2-D 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 2-D LoDTensor with shape [M, 1]. Data type
should be int. M is the total number of ground-truth, each
element is a class label.
is_crowd (Variable): A 2-D 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 ground-truth 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 2-D 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 2-D LoDTensor in shape of [R, 1] with type
of int32. R is the same as it in `rois`. Each element represents
a class label of a RoI.
num_classes (int): Class number.
resolution (int): Resolution of mask predictions.
Returns:
mask_rois (Variable): 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
original image size.
mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]
and int data type, each element represents 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 represents the binary mask targets.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | generate_mask_labels | 92lqllearning/Paddle | python | def generate_mask_labels(im_info, gt_classes, is_crowd, gt_segms, rois, labels_int32, num_classes, resolution):
'\n\t:alias_main: paddle.nn.functional.generate_mask_labels\n\t:alias: paddle.nn.functional.generate_mask_labels,paddle.nn.functional.vision.generate_mask_labels\n\t:old_api: paddle.fluid.layers.generate_mask_labels\n\n **Generate Mask Labels for Mask-RCNN**\n\n This operator can be, for given the RoIs and corresponding labels,\n to sample foreground RoIs. This mask branch also has\n a :math: `K \\times M^{2}` dimensional output targets for each foreground\n RoI, which encodes K binary masks of resolution M x M, one for each of the\n K classes. This mask targets are used to compute loss of mask branch.\n\n Please note, the data format of groud-truth segmentation, assumed the\n segmentations are as follows. The first instance has two gt objects.\n The second instance has one gt object, this object has two gt segmentations.\n\n .. code-block:: python\n\n #[\n # [[[229.14, 370.9, 229.14, 370.9, ...]],\n # [[343.7, 139.85, 349.01, 138.46, ...]]], # 0-th instance\n # [[[500.0, 390.62, ...],[115.48, 187.86, ...]]] # 1-th instance\n #]\n\n batch_masks = []\n for semgs in batch_semgs:\n gt_masks = []\n for semg in semgs:\n gt_segm = []\n for polys in semg:\n gt_segm.append(np.array(polys).reshape(-1, 2))\n gt_masks.append(gt_segm)\n batch_masks.append(gt_masks)\n \n \n place = fluid.CPUPlace()\n feeder = fluid.DataFeeder(place=place, feed_list=feeds)\n feeder.feed(batch_masks)\n\n Args:\n im_info (Variable): A 2-D Tensor with shape [N, 3] and float32\n data type. N is the batch size, each element is\n [height, width, scale] of image. Image scale is\n target_size / original_size, target_size is the size after resize,\n original_size is the original image size.\n gt_classes (Variable): A 2-D LoDTensor with shape [M, 1]. Data type\n should be int. M is the total number of ground-truth, each\n element is a class label.\n is_crowd (Variable): A 2-D LoDTensor with same shape and same data type\n as gt_classes, each element is a flag indicating whether a\n groundtruth is crowd.\n gt_segms (Variable): This input is a 2D LoDTensor with shape [S, 2] and\n float32 data type, it\'s LoD level is 3.\n Usually users do not needs to understand LoD,\n The users should return correct data format in reader.\n The LoD[0] represents the ground-truth objects number of\n each instance. LoD[1] represents the segmentation counts of each\n objects. LoD[2] represents the polygons number of each segmentation.\n S the total number of polygons coordinate points. Each element is\n (x, y) coordinate points.\n rois (Variable): A 2-D LoDTensor with shape [R, 4] and float32 data type\n float32. R is the total number of RoIs, each element is a bounding\n box with (xmin, ymin, xmax, ymax) format in the range of original image.\n labels_int32 (Variable): A 2-D LoDTensor in shape of [R, 1] with type\n of int32. R is the same as it in `rois`. Each element represents\n a class label of a RoI.\n num_classes (int): Class number.\n resolution (int): Resolution of mask predictions.\n\n Returns:\n mask_rois (Variable): A 2D LoDTensor with shape [P, 4] and same data\n type as `rois`. P is the total number of sampled RoIs. Each element\n is a bounding box with [xmin, ymin, xmax, ymax] format in range of\n original image size.\n\n mask_rois_has_mask_int32 (Variable): A 2D LoDTensor with shape [P, 1]\n and int data type, each element represents the output mask RoI\n index with regard to input RoIs.\n\n mask_int32 (Variable): A 2D LoDTensor with shape [P, K * M * M] and int\n data type, K is the classes number and M is the resolution of mask\n predictions. Each element represents the binary mask targets.\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n im_info = fluid.data(name="im_info", shape=[None, 3],\n dtype="float32")\n gt_classes = fluid.data(name="gt_classes", shape=[None, 1],\n dtype="float32", lod_level=1)\n is_crowd = fluid.data(name="is_crowd", shape=[None, 1],\n dtype="float32", lod_level=1)\n gt_masks = fluid.data(name="gt_masks", shape=[None, 2],\n dtype="float32", lod_level=3)\n # rois, roi_labels can be the output of\n # fluid.layers.generate_proposal_labels.\n rois = fluid.data(name="rois", shape=[None, 4],\n dtype="float32", lod_level=1)\n roi_labels = fluid.data(name="roi_labels", shape=[None, 1],\n dtype="int32", lod_level=1)\n mask_rois, mask_index, mask_int32 = fluid.layers.generate_mask_labels(\n im_info=im_info,\n gt_classes=gt_classes,\n is_crowd=is_crowd,\n gt_segms=gt_masks,\n rois=rois,\n labels_int32=roi_labels,\n num_classes=81,\n resolution=14)\n '
helper = LayerHelper('generate_mask_labels', **locals())
mask_rois = helper.create_variable_for_type_inference(dtype=rois.dtype)
roi_has_mask_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
mask_int32 = helper.create_variable_for_type_inference(dtype=gt_classes.dtype)
helper.append_op(type='generate_mask_labels', inputs={'ImInfo': im_info, 'GtClasses': gt_classes, 'IsCrowd': is_crowd, 'GtSegms': gt_segms, 'Rois': rois, 'LabelsInt32': labels_int32}, outputs={'MaskRois': mask_rois, 'RoiHasMaskInt32': roi_has_mask_int32, 'MaskInt32': mask_int32}, attrs={'num_classes': num_classes, 'resolution': resolution})
mask_rois.stop_gradient = True
roi_has_mask_int32.stop_gradient = True
mask_int32.stop_gradient = True
return (mask_rois, roi_has_mask_int32, mask_int32) |
def 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, return_rois_num=False):
"\n\t:alias_main: paddle.nn.functional.generate_proposals\n\t:alias: paddle.nn.functional.generate_proposals,paddle.nn.functional.vision.generate_proposals\n\t:old_api: paddle.fluid.layers.generate_proposals\n\n **Generate proposal Faster-RCNN**\n\n This operation proposes RoIs according to each box with their\n probability to be a foreground object and \n the box can be calculated by anchors. Bbox_deltais and scores\n to be an object are the output of RPN. Final proposals\n could be used to train detection net.\n\n For generating proposals, this operation performs following steps:\n\n 1. Transposes and resizes scores and bbox_deltas in size of\n (H*W*A, 1) and (H*W*A, 4)\n 2. Calculate box locations as proposals candidates. \n 3. Clip boxes to image\n 4. Remove predicted boxes with small area. \n 5. Apply NMS to get final proposals as output.\n\n Args:\n scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents\n the probability for each box to be an object.\n N is batch size, A is number of anchors, H and W are height and\n width of the feature map. The data type must be float32.\n bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W]\n represents the difference between predicted box location and\n anchor location. The data type must be float32.\n im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin\n image information for N batch. Height and width are the input sizes \n and scale is the ratio of network input size and original size. \n The data type can be float32 or float64.\n anchors(Variable): A 4-D Tensor represents the anchors with a layout\n of [H, W, A, 4]. H and W are height and width of the feature map,\n num_anchors is the box count of each position. Each anchor is\n in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.\n variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of\n [H, W, num_priors, 4]. Each variance is in\n (xcenter, ycenter, w, h) format. The data type must be float32.\n pre_nms_top_n(float): Number of total bboxes to be kept per\n image before NMS. The data type must be float32. `6000` by default.\n post_nms_top_n(float): Number of total bboxes to be kept per\n image after NMS. The data type must be float32. `1000` by default.\n nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.\n min_size(float): Remove predicted boxes with either height or\n width < min_size. The data type must be float32. `0.1` by default.\n eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,\n `adaptive_threshold = adaptive_threshold * eta` in each iteration.\n return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's \n num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents\n the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model. \n 'False' by default. \n Returns:\n tuple:\n A tuple with format ``(rpn_rois, rpn_roi_probs)``.\n\n - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.\n - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')\n bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')\n im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')\n anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')\n variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')\n rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas,\n im_info, anchors, variances)\n\n "
helper = LayerHelper('generate_proposals', **locals())
check_variable_and_dtype(scores, 'scores', ['float32'], 'generate_proposals')
check_variable_and_dtype(bbox_deltas, 'bbox_deltas', ['float32'], 'generate_proposals')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'generate_proposals')
check_variable_and_dtype(anchors, 'anchors', ['float32'], 'generate_proposals')
check_variable_and_dtype(variances, 'variances', ['float32'], 'generate_proposals')
rpn_rois = helper.create_variable_for_type_inference(dtype=bbox_deltas.dtype)
rpn_roi_probs = helper.create_variable_for_type_inference(dtype=scores.dtype)
rpn_rois_lod = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(type='generate_proposals', inputs={'Scores': scores, 'BboxDeltas': bbox_deltas, 'ImInfo': im_info, 'Anchors': anchors, 'Variances': variances}, attrs={'pre_nms_topN': pre_nms_top_n, 'post_nms_topN': post_nms_top_n, 'nms_thresh': nms_thresh, 'min_size': min_size, 'eta': eta}, outputs={'RpnRois': rpn_rois, 'RpnRoiProbs': rpn_roi_probs, 'RpnRoisLod': rpn_rois_lod})
rpn_rois.stop_gradient = True
rpn_roi_probs.stop_gradient = True
rpn_rois_lod.stop_gradient = True
if return_rois_num:
return (rpn_rois, rpn_roi_probs, rpn_rois_lod)
else:
return (rpn_rois, rpn_roi_probs) | 6,057,635,229,248,410,000 | :alias_main: paddle.nn.functional.generate_proposals
:alias: paddle.nn.functional.generate_proposals,paddle.nn.functional.vision.generate_proposals
:old_api: paddle.fluid.layers.generate_proposals
**Generate proposal Faster-RCNN**
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:
1. Transposes and resizes scores and bbox_deltas in size of
(H*W*A, 1) and (H*W*A, 4)
2. Calculate box locations as proposals candidates.
3. Clip boxes to image
4. Remove predicted boxes with small area.
5. Apply NMS to get final proposals as output.
Args:
scores(Variable): A 4-D 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 4-D Tensor with shape [N, 4*A, H, W]
represents the difference between predicted box location and
anchor location. The data type must be float32.
im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin
image information for N batch. Height and width are the input sizes
and scale is the ratio of network input size and original size.
The data type can be float32 or float64.
anchors(Variable): A 4-D 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 4-D 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.
return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's
num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents
the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model.
'False' by default.
Returns:
tuple:
A tuple with format ``(rpn_rois, rpn_roi_probs)``.
- **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
- **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | generate_proposals | 92lqllearning/Paddle | python | def 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, return_rois_num=False):
"\n\t:alias_main: paddle.nn.functional.generate_proposals\n\t:alias: paddle.nn.functional.generate_proposals,paddle.nn.functional.vision.generate_proposals\n\t:old_api: paddle.fluid.layers.generate_proposals\n\n **Generate proposal Faster-RCNN**\n\n This operation proposes RoIs according to each box with their\n probability to be a foreground object and \n the box can be calculated by anchors. Bbox_deltais and scores\n to be an object are the output of RPN. Final proposals\n could be used to train detection net.\n\n For generating proposals, this operation performs following steps:\n\n 1. Transposes and resizes scores and bbox_deltas in size of\n (H*W*A, 1) and (H*W*A, 4)\n 2. Calculate box locations as proposals candidates. \n 3. Clip boxes to image\n 4. Remove predicted boxes with small area. \n 5. Apply NMS to get final proposals as output.\n\n Args:\n scores(Variable): A 4-D Tensor with shape [N, A, H, W] represents\n the probability for each box to be an object.\n N is batch size, A is number of anchors, H and W are height and\n width of the feature map. The data type must be float32.\n bbox_deltas(Variable): A 4-D Tensor with shape [N, 4*A, H, W]\n represents the difference between predicted box location and\n anchor location. The data type must be float32.\n im_info(Variable): A 2-D Tensor with shape [N, 3] represents origin\n image information for N batch. Height and width are the input sizes \n and scale is the ratio of network input size and original size. \n The data type can be float32 or float64.\n anchors(Variable): A 4-D Tensor represents the anchors with a layout\n of [H, W, A, 4]. H and W are height and width of the feature map,\n num_anchors is the box count of each position. Each anchor is\n in (xmin, ymin, xmax, ymax) format an unnormalized. The data type must be float32.\n variances(Variable): A 4-D Tensor. The expanded variances of anchors with a layout of\n [H, W, num_priors, 4]. Each variance is in\n (xcenter, ycenter, w, h) format. The data type must be float32.\n pre_nms_top_n(float): Number of total bboxes to be kept per\n image before NMS. The data type must be float32. `6000` by default.\n post_nms_top_n(float): Number of total bboxes to be kept per\n image after NMS. The data type must be float32. `1000` by default.\n nms_thresh(float): Threshold in NMS. The data type must be float32. `0.5` by default.\n min_size(float): Remove predicted boxes with either height or\n width < min_size. The data type must be float32. `0.1` by default.\n eta(float): Apply in adaptive NMS, if adaptive `threshold > 0.5`,\n `adaptive_threshold = adaptive_threshold * eta` in each iteration.\n return_rois_num(bool): When setting True, it will return a 1D Tensor with shape [N, ] that includes Rois's \n num of each image in one batch. The N is the image's num. For example, the tensor has values [4,5] that represents\n the first image has 4 Rois, the second image has 5 Rois. It only used in rcnn model. \n 'False' by default. \n Returns:\n tuple:\n A tuple with format ``(rpn_rois, rpn_roi_probs)``.\n\n - **rpn_rois**: The generated RoIs. 2-D Tensor with shape ``[N, 4]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.\n - **rpn_roi_probs**: The scores of generated RoIs. 2-D Tensor with shape ``[N, 1]`` while ``N`` is the number of RoIs. The data type is the same as ``scores``.\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n scores = fluid.data(name='scores', shape=[None, 4, 5, 5], dtype='float32')\n bbox_deltas = fluid.data(name='bbox_deltas', shape=[None, 16, 5, 5], dtype='float32')\n im_info = fluid.data(name='im_info', shape=[None, 3], dtype='float32')\n anchors = fluid.data(name='anchors', shape=[None, 5, 4, 4], dtype='float32')\n variances = fluid.data(name='variances', shape=[None, 5, 10, 4], dtype='float32')\n rois, roi_probs = fluid.layers.generate_proposals(scores, bbox_deltas,\n im_info, anchors, variances)\n\n "
helper = LayerHelper('generate_proposals', **locals())
check_variable_and_dtype(scores, 'scores', ['float32'], 'generate_proposals')
check_variable_and_dtype(bbox_deltas, 'bbox_deltas', ['float32'], 'generate_proposals')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'generate_proposals')
check_variable_and_dtype(anchors, 'anchors', ['float32'], 'generate_proposals')
check_variable_and_dtype(variances, 'variances', ['float32'], 'generate_proposals')
rpn_rois = helper.create_variable_for_type_inference(dtype=bbox_deltas.dtype)
rpn_roi_probs = helper.create_variable_for_type_inference(dtype=scores.dtype)
rpn_rois_lod = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(type='generate_proposals', inputs={'Scores': scores, 'BboxDeltas': bbox_deltas, 'ImInfo': im_info, 'Anchors': anchors, 'Variances': variances}, attrs={'pre_nms_topN': pre_nms_top_n, 'post_nms_topN': post_nms_top_n, 'nms_thresh': nms_thresh, 'min_size': min_size, 'eta': eta}, outputs={'RpnRois': rpn_rois, 'RpnRoiProbs': rpn_roi_probs, 'RpnRoisLod': rpn_rois_lod})
rpn_rois.stop_gradient = True
rpn_roi_probs.stop_gradient = True
rpn_rois_lod.stop_gradient = True
if return_rois_num:
return (rpn_rois, rpn_roi_probs, rpn_rois_lod)
else:
return (rpn_rois, rpn_roi_probs) |
def box_clip(input, im_info, name=None):
"\n\t:alias_main: paddle.nn.functional.box_clip\n\t:alias: paddle.nn.functional.box_clip,paddle.nn.functional.vision.box_clip\n\t:old_api: paddle.fluid.layers.box_clip\n\t\n Clip the box into the size given by im_info\n For each input box, The formula is given as follows:\n \n .. code-block:: text\n\n xmin = max(min(xmin, im_w - 1), 0)\n ymin = max(min(ymin, im_h - 1), 0) \n xmax = max(min(xmax, im_w - 1), 0)\n ymax = max(min(ymax, im_h - 1), 0)\n \n where im_w and im_h are computed from im_info:\n \n .. code-block:: text\n\n im_h = round(height / scale)\n im_w = round(weight / scale)\n\n Args:\n input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,\n the last dimension is 4 and data type is float32 or float64.\n im_info(Variable): The 2-D Tensor with shape [N, 3] with layout \n (height, width, scale) representing the information of image. \n Height and width are the input sizes and scale is the ratio of network input\n size and original size. The data type is float32 or float64.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n \n Returns:\n Variable:\n\n output(Variable): The clipped tensor with data type float32 or float64. \n The shape is same as input.\n\n \n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n boxes = fluid.data(\n name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1)\n im_info = fluid.data(name='im_info', shape=[-1 ,3])\n out = fluid.layers.box_clip(\n input=boxes, im_info=im_info)\n "
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'box_clip')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'box_clip')
helper = LayerHelper('box_clip', **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
inputs = {'Input': input, 'ImInfo': im_info}
helper.append_op(type='box_clip', inputs=inputs, outputs={'Output': output})
return output | -4,038,965,544,099,605,000 | :alias_main: paddle.nn.functional.box_clip
:alias: paddle.nn.functional.box_clip,paddle.nn.functional.vision.box_clip
:old_api: paddle.fluid.layers.box_clip
Clip the box into the size given by im_info
For each input box, The formula is given as follows:
.. code-block:: text
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:
.. code-block:: text
im_h = round(height / scale)
im_w = round(weight / scale)
Args:
input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,
the last dimension is 4 and data type is float32 or float64.
im_info(Variable): The 2-D Tensor with shape [N, 3] with layout
(height, width, scale) representing the information of image.
Height and width are the input sizes and scale is the ratio of network input
size and original size. The data type is float32 or float64.
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
output(Variable): The clipped tensor with data type float32 or float64.
The shape is same as input.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | box_clip | 92lqllearning/Paddle | python | def box_clip(input, im_info, name=None):
"\n\t:alias_main: paddle.nn.functional.box_clip\n\t:alias: paddle.nn.functional.box_clip,paddle.nn.functional.vision.box_clip\n\t:old_api: paddle.fluid.layers.box_clip\n\t\n Clip the box into the size given by im_info\n For each input box, The formula is given as follows:\n \n .. code-block:: text\n\n xmin = max(min(xmin, im_w - 1), 0)\n ymin = max(min(ymin, im_h - 1), 0) \n xmax = max(min(xmax, im_w - 1), 0)\n ymax = max(min(ymax, im_h - 1), 0)\n \n where im_w and im_h are computed from im_info:\n \n .. code-block:: text\n\n im_h = round(height / scale)\n im_w = round(weight / scale)\n\n Args:\n input(Variable): The input Tensor with shape :math:`[N_1, N_2, ..., N_k, 4]`,\n the last dimension is 4 and data type is float32 or float64.\n im_info(Variable): The 2-D Tensor with shape [N, 3] with layout \n (height, width, scale) representing the information of image. \n Height and width are the input sizes and scale is the ratio of network input\n size and original size. The data type is float32 or float64.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n \n Returns:\n Variable:\n\n output(Variable): The clipped tensor with data type float32 or float64. \n The shape is same as input.\n\n \n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n boxes = fluid.data(\n name='boxes', shape=[None, 8, 4], dtype='float32', lod_level=1)\n im_info = fluid.data(name='im_info', shape=[-1 ,3])\n out = fluid.layers.box_clip(\n input=boxes, im_info=im_info)\n "
check_variable_and_dtype(input, 'input', ['float32', 'float64'], 'box_clip')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'box_clip')
helper = LayerHelper('box_clip', **locals())
output = helper.create_variable_for_type_inference(dtype=input.dtype)
inputs = {'Input': input, 'ImInfo': im_info}
helper.append_op(type='box_clip', inputs=inputs, outputs={'Output': output})
return output |
def 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):
'\n **Detection Output Layer for the detector RetinaNet.**\n\n In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many \n `FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category\n and location predictions, this OP is to get the detection results by\n performing following steps:\n\n 1. For each FPN level, decode box predictions according to the anchor\n boxes from at most :attr:`nms_top_k` top-scoring predictions after\n thresholding detector confidence at :attr:`score_threshold`.\n 2. Merge top predictions from all levels and apply multi-class non \n maximum suppression (NMS) on them to get the final detections.\n\n Args:\n bboxes(List): A list of Tensors from multiple FPN levels represents\n the location prediction for all anchor boxes. Each element is\n a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the\n batch size, :math:`Mi` is the number of bounding boxes from\n :math:`i`-th FPN level and each bounding box has four coordinate\n values and the layout is [xmin, ymin, xmax, ymax]. The data type\n of each element is float32 or float64.\n scores(List): A list of Tensors from multiple FPN levels represents\n the category prediction for all anchor boxes. Each element is a\n 3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch\n size, :math:`C` is the class number (**excluding background**),\n :math:`Mi` is the number of bounding boxes from :math:`i`-th FPN\n level. The data type of each element is float32 or float64.\n anchors(List): A list of Tensors from multiple FPN levels represents\n the locations of all anchor boxes. Each element is a 2-D Tensor\n with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding\n boxes from :math:`i`-th FPN level, and each bounding box has four\n coordinate values and the layout is [xmin, ymin, xmax, ymax].\n The data type of each element is float32 or float64.\n im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size\n information of input images. :math:`N` is the batch size, the size\n information of each image is a 3-vector which are the height and width\n of the network input along with the factor scaling the origin image to\n the network input. The data type of :attr:`im_info` is float32.\n score_threshold(float): Threshold to filter out bounding boxes\n with a confidence score before NMS, default value is set to 0.05.\n nms_top_k(int): Maximum number of detections per FPN layer to be\n kept according to the confidences before NMS, default value is set to\n 1000.\n keep_top_k(int): Number of total bounding boxes to be kept per image after\n NMS step. Default value is set to 100, -1 means keeping all bounding\n boxes after NMS step.\n nms_threshold(float): The Intersection-over-Union(IoU) threshold used to \n filter out boxes in NMS.\n nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.\n Default value is set to 1., which represents the value of\n :attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set\n to be lower than 1. and the value of :attr:`nms_threshold` is set to\n be higher than 0.5, everytime a bounding box is filtered out,\n the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`\n = :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until\n the actual value of :attr:`nms_threshold` is lower than or equal to\n 0.5.\n\n **Notice**: In some cases where the image sizes are very small, it\'s possible\n that there is no detection if :attr:`score_threshold` are used at all\n levels. Hence, this OP do not filter out anchors from the highest FPN level\n before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and\n :attr:`anchors` is required to be from the highest FPN level.\n\n Returns:\n Variable(The data type is float32 or float64):\n The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.\n Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].\n :math:`No` is the total number of detections in this mini-batch.\n The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected\n results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image\n has no detected results. If all images have no detected results,\n LoD will be set to 0, and the output tensor is empty (None).\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n bboxes_low = fluid.data(\n name=\'bboxes_low\', shape=[1, 44, 4], dtype=\'float32\')\n bboxes_high = fluid.data(\n name=\'bboxes_high\', shape=[1, 11, 4], dtype=\'float32\')\n scores_low = fluid.data(\n name=\'scores_low\', shape=[1, 44, 10], dtype=\'float32\')\n scores_high = fluid.data(\n name=\'scores_high\', shape=[1, 11, 10], dtype=\'float32\')\n anchors_low = fluid.data(\n name=\'anchors_low\', shape=[44, 4], dtype=\'float32\')\n anchors_high = fluid.data(\n name=\'anchors_high\', shape=[11, 4], dtype=\'float32\')\n im_info = fluid.data(\n name="im_info", shape=[1, 3], dtype=\'float32\')\n nmsed_outs = fluid.layers.retinanet_detection_output(\n bboxes=[bboxes_low, bboxes_high],\n scores=[scores_low, scores_high],\n anchors=[anchors_low, anchors_high],\n im_info=im_info,\n score_threshold=0.05,\n nms_top_k=1000,\n keep_top_k=100,\n nms_threshold=0.45,\n nms_eta=1.0)\n '
check_type(bboxes, 'bboxes', list, 'retinanet_detection_output')
for (i, bbox) in enumerate(bboxes):
check_variable_and_dtype(bbox, 'bbox{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_type(scores, 'scores', list, 'retinanet_detection_output')
for (i, score) in enumerate(scores):
check_variable_and_dtype(score, 'score{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_type(anchors, 'anchors', list, 'retinanet_detection_output')
for (i, anchor) in enumerate(anchors):
check_variable_and_dtype(anchor, 'anchor{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'retinanet_detection_output')
helper = LayerHelper('retinanet_detection_output', **locals())
output = helper.create_variable_for_type_inference(dtype=helper.input_dtype('scores'))
helper.append_op(type='retinanet_detection_output', inputs={'BBoxes': bboxes, 'Scores': scores, 'Anchors': anchors, 'ImInfo': im_info}, attrs={'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'keep_top_k': keep_top_k, 'nms_eta': 1.0}, outputs={'Out': output})
output.stop_gradient = True
return output | -6,385,242,098,909,211,000 | **Detection Output Layer for the detector RetinaNet.**
In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many
`FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category
and location predictions, this OP is to get the detection results by
performing following steps:
1. For each FPN level, decode box predictions according to the anchor
boxes from at most :attr:`nms_top_k` top-scoring predictions after
thresholding detector confidence at :attr:`score_threshold`.
2. Merge top predictions from all levels and apply multi-class non
maximum suppression (NMS) on them to get the final detections.
Args:
bboxes(List): A list of Tensors from multiple FPN levels represents
the location prediction for all anchor boxes. Each element is
a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the
batch size, :math:`Mi` is the number of bounding boxes from
:math:`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
3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch
size, :math:`C` is the class number (**excluding background**),
:math:`Mi` is the number of bounding boxes from :math:`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 2-D Tensor
with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding
boxes from :math:`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 2-D Tensor with shape :math:`[N, 3]` represents the size
information of input images. :math:`N` is the batch size, the size
information of each image is a 3-vector 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 :attr:`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 Intersection-over-Union(IoU) threshold used to
filter out boxes in NMS.
nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.
Default value is set to 1., which represents the value of
:attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set
to be lower than 1. and the value of :attr:`nms_threshold` is set to
be higher than 0.5, everytime a bounding box is filtered out,
the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`
= :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until
the actual value of :attr:`nms_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 :attr:`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 in :attr:`bboxes`:, :attr:`scores` and
:attr:`anchors` is required to be from the highest FPN level.
Returns:
Variable(The data type is float32 or float64):
The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.
Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].
:math:`No` is the total number of detections in this mini-batch.
The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected
results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`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).
Examples:
.. code-block:: python
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.0) | python/paddle/fluid/layers/detection.py | retinanet_detection_output | 92lqllearning/Paddle | python | def 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):
'\n **Detection Output Layer for the detector RetinaNet.**\n\n In the detector `RetinaNet <https://arxiv.org/abs/1708.02002>`_ , many \n `FPN <https://arxiv.org/abs/1612.03144>`_ levels output the category\n and location predictions, this OP is to get the detection results by\n performing following steps:\n\n 1. For each FPN level, decode box predictions according to the anchor\n boxes from at most :attr:`nms_top_k` top-scoring predictions after\n thresholding detector confidence at :attr:`score_threshold`.\n 2. Merge top predictions from all levels and apply multi-class non \n maximum suppression (NMS) on them to get the final detections.\n\n Args:\n bboxes(List): A list of Tensors from multiple FPN levels represents\n the location prediction for all anchor boxes. Each element is\n a 3-D Tensor with shape :math:`[N, Mi, 4]`, :math:`N` is the\n batch size, :math:`Mi` is the number of bounding boxes from\n :math:`i`-th FPN level and each bounding box has four coordinate\n values and the layout is [xmin, ymin, xmax, ymax]. The data type\n of each element is float32 or float64.\n scores(List): A list of Tensors from multiple FPN levels represents\n the category prediction for all anchor boxes. Each element is a\n 3-D Tensor with shape :math:`[N, Mi, C]`, :math:`N` is the batch\n size, :math:`C` is the class number (**excluding background**),\n :math:`Mi` is the number of bounding boxes from :math:`i`-th FPN\n level. The data type of each element is float32 or float64.\n anchors(List): A list of Tensors from multiple FPN levels represents\n the locations of all anchor boxes. Each element is a 2-D Tensor\n with shape :math:`[Mi, 4]`, :math:`Mi` is the number of bounding\n boxes from :math:`i`-th FPN level, and each bounding box has four\n coordinate values and the layout is [xmin, ymin, xmax, ymax].\n The data type of each element is float32 or float64.\n im_info(Variable): A 2-D Tensor with shape :math:`[N, 3]` represents the size\n information of input images. :math:`N` is the batch size, the size\n information of each image is a 3-vector which are the height and width\n of the network input along with the factor scaling the origin image to\n the network input. The data type of :attr:`im_info` is float32.\n score_threshold(float): Threshold to filter out bounding boxes\n with a confidence score before NMS, default value is set to 0.05.\n nms_top_k(int): Maximum number of detections per FPN layer to be\n kept according to the confidences before NMS, default value is set to\n 1000.\n keep_top_k(int): Number of total bounding boxes to be kept per image after\n NMS step. Default value is set to 100, -1 means keeping all bounding\n boxes after NMS step.\n nms_threshold(float): The Intersection-over-Union(IoU) threshold used to \n filter out boxes in NMS.\n nms_eta(float): The parameter for adjusting :attr:`nms_threshold` in NMS.\n Default value is set to 1., which represents the value of\n :attr:`nms_threshold` keep the same in NMS. If :attr:`nms_eta` is set\n to be lower than 1. and the value of :attr:`nms_threshold` is set to\n be higher than 0.5, everytime a bounding box is filtered out,\n the adjustment for :attr:`nms_threshold` like :attr:`nms_threshold`\n = :attr:`nms_threshold` * :attr:`nms_eta` will not be stopped until\n the actual value of :attr:`nms_threshold` is lower than or equal to\n 0.5.\n\n **Notice**: In some cases where the image sizes are very small, it\'s possible\n that there is no detection if :attr:`score_threshold` are used at all\n levels. Hence, this OP do not filter out anchors from the highest FPN level\n before NMS. And the last element in :attr:`bboxes`:, :attr:`scores` and\n :attr:`anchors` is required to be from the highest FPN level.\n\n Returns:\n Variable(The data type is float32 or float64):\n The detection output is a 1-level LoDTensor with shape :math:`[No, 6]`.\n Each row has six values: [label, confidence, xmin, ymin, xmax, ymax].\n :math:`No` is the total number of detections in this mini-batch.\n The :math:`i`-th image has `LoD[i + 1] - LoD[i]` detected\n results, if `LoD[i + 1] - LoD[i]` is 0, the :math:`i`-th image\n has no detected results. If all images have no detected results,\n LoD will be set to 0, and the output tensor is empty (None).\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n\n bboxes_low = fluid.data(\n name=\'bboxes_low\', shape=[1, 44, 4], dtype=\'float32\')\n bboxes_high = fluid.data(\n name=\'bboxes_high\', shape=[1, 11, 4], dtype=\'float32\')\n scores_low = fluid.data(\n name=\'scores_low\', shape=[1, 44, 10], dtype=\'float32\')\n scores_high = fluid.data(\n name=\'scores_high\', shape=[1, 11, 10], dtype=\'float32\')\n anchors_low = fluid.data(\n name=\'anchors_low\', shape=[44, 4], dtype=\'float32\')\n anchors_high = fluid.data(\n name=\'anchors_high\', shape=[11, 4], dtype=\'float32\')\n im_info = fluid.data(\n name="im_info", shape=[1, 3], dtype=\'float32\')\n nmsed_outs = fluid.layers.retinanet_detection_output(\n bboxes=[bboxes_low, bboxes_high],\n scores=[scores_low, scores_high],\n anchors=[anchors_low, anchors_high],\n im_info=im_info,\n score_threshold=0.05,\n nms_top_k=1000,\n keep_top_k=100,\n nms_threshold=0.45,\n nms_eta=1.0)\n '
check_type(bboxes, 'bboxes', list, 'retinanet_detection_output')
for (i, bbox) in enumerate(bboxes):
check_variable_and_dtype(bbox, 'bbox{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_type(scores, 'scores', list, 'retinanet_detection_output')
for (i, score) in enumerate(scores):
check_variable_and_dtype(score, 'score{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_type(anchors, 'anchors', list, 'retinanet_detection_output')
for (i, anchor) in enumerate(anchors):
check_variable_and_dtype(anchor, 'anchor{}'.format(i), ['float32', 'float64'], 'retinanet_detection_output')
check_variable_and_dtype(im_info, 'im_info', ['float32', 'float64'], 'retinanet_detection_output')
helper = LayerHelper('retinanet_detection_output', **locals())
output = helper.create_variable_for_type_inference(dtype=helper.input_dtype('scores'))
helper.append_op(type='retinanet_detection_output', inputs={'BBoxes': bboxes, 'Scores': scores, 'Anchors': anchors, 'ImInfo': im_info}, attrs={'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'keep_top_k': keep_top_k, 'nms_eta': 1.0}, outputs={'Out': output})
output.stop_gradient = True
return output |
def 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):
"\n\t:alias_main: paddle.nn.functional.multiclass_nms\n\t:alias: paddle.nn.functional.multiclass_nms,paddle.nn.functional.extension.multiclass_nms\n\t:old_api: paddle.fluid.layers.multiclass_nms\n\n **Multiclass NMS**\n \n This operator is to do multi-class non maximum suppression (NMS) on\n boxes and scores.\n\n In the NMS step, this operator greedily selects a subset of detection bounding\n boxes that have high scores larger than score_threshold, if providing this\n threshold, then selects the largest nms_top_k confidences scores if nms_top_k\n is larger than -1. Then this operator pruns away boxes that have high IOU\n (intersection over union) overlap with already selected boxes by adaptive\n threshold NMS based on parameters of nms_threshold and nms_eta.\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n See below for an example:\n\n .. code-block:: text\n\n if:\n box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax)\n box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4)\n\n box2.data = (3.0, 4.0, 8.0, 5.0)\n box2.score = (0.3, 0.3, 0.1)\n\n nms_threshold = 0.3\n background_label = 0\n score_threshold = 0\n\n\n Then:\n iou = 4/11 > 0.3\n out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0], \n [2, 0.4, 2.0, 3.0, 7.0, 5.0]]\n \n Out format is (label, confidence, xmin, ymin, xmax, ymax)\n Args:\n bboxes (Variable): Two types of bboxes are supported:\n 1. (Tensor) A 3-D Tensor with shape\n [N, M, 4 or 8 16 24 32] represents the\n predicted locations of M bounding bboxes,\n N is the batch size. Each bounding box has four\n coordinate values and the layout is \n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]\n M is the number of bounding boxes, C is the \n class number. The data type is float32 or float64. \n scores (Variable): Two types of scores are supported:\n 1. (Tensor) A 3-D Tensor with shape [N, C, M]\n represents the predicted confidence predictions.\n N is the batch size, C is the class number, M is \n number of bounding boxes. For each category there \n are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension\n of BBoxes.The data type is float32 or float64. \n 2. (LoDTensor) A 2-D LoDTensor with shape [M, C].\n M is the number of bbox, C is the class number.\n In this case, input BBoxes should be the second\n case with shape [M, C, 4].The data type is float32 or float64. \n background_label (int): The index of background label, the background \n label will be ignored. If set to -1, then all\n categories will be considered. Default: 0\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score. If not provided, \n consider all boxes.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n nms_threshold (float): The threshold to be used in NMS. Default: 0.3\n nms_eta (float): The threshold to be used in NMS. Default: 1.0\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n normalized (bool): Whether detections are normalized. Default: True\n name(str): Name of the multiclass nms op. Default: None.\n\n Returns:\n Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n or A 2-D LoDTensor with shape [No, 10] represents the detections.\n Each row has 10 values: \n [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the \n total number of detections. If there is no detected boxes for all\n images, lod will be set to {1} and Out only contains one value\n which is -1.\n (After version 1.3, when no boxes detected, the lod is changed \n from {0} to {1}) \n\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None,81, 4],\n dtype='float32', lod_level=1)\n scores = fluid.data(name='scores', shape=[None,81],\n dtype='float32', lod_level=1)\n out = fluid.layers.multiclass_nms(bboxes=boxes,\n scores=scores,\n background_label=0,\n score_threshold=0.5,\n nms_top_k=400,\n nms_threshold=0.3,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], 'multiclass_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], 'multiclass_nms')
check_type(score_threshold, 'score_threshold', float, 'multicalss_nms')
check_type(nms_top_k, 'nums_top_k', int, 'multiclass_nms')
check_type(keep_top_k, 'keep_top_k', int, 'mutliclass_nms')
check_type(nms_threshold, 'nms_threshold', float, 'multiclass_nms')
check_type(normalized, 'normalized', bool, 'multiclass_nms')
check_type(nms_eta, 'nms_eta', float, 'multiclass_nms')
check_type(background_label, 'background_label', int, 'multiclass_nms')
helper = LayerHelper('multiclass_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
helper.append_op(type='multiclass_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'nms_eta': nms_eta, 'keep_top_k': keep_top_k, 'normalized': normalized}, outputs={'Out': output})
output.stop_gradient = True
return output | 8,379,884,880,675,210,000 | :alias_main: paddle.nn.functional.multiclass_nms
:alias: paddle.nn.functional.multiclass_nms,paddle.nn.functional.extension.multiclass_nms
:old_api: paddle.fluid.layers.multiclass_nms
**Multiclass NMS**
This operator is to do multi-class 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:
.. code-block:: text
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)
Args:
bboxes (Variable): Two types of bboxes are supported:
1. (Tensor) A 3-D 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 3-D 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 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes.The data type is float32 or float64.
2. (LoDTensor) A 2-D 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 after 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:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D 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})
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | multiclass_nms | 92lqllearning/Paddle | python | def 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):
"\n\t:alias_main: paddle.nn.functional.multiclass_nms\n\t:alias: paddle.nn.functional.multiclass_nms,paddle.nn.functional.extension.multiclass_nms\n\t:old_api: paddle.fluid.layers.multiclass_nms\n\n **Multiclass NMS**\n \n This operator is to do multi-class non maximum suppression (NMS) on\n boxes and scores.\n\n In the NMS step, this operator greedily selects a subset of detection bounding\n boxes that have high scores larger than score_threshold, if providing this\n threshold, then selects the largest nms_top_k confidences scores if nms_top_k\n is larger than -1. Then this operator pruns away boxes that have high IOU\n (intersection over union) overlap with already selected boxes by adaptive\n threshold NMS based on parameters of nms_threshold and nms_eta.\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n See below for an example:\n\n .. code-block:: text\n\n if:\n box1.data = (2.0, 3.0, 7.0, 5.0) format is (xmin, ymin, xmax, ymax)\n box1.scores = (0.7, 0.2, 0.4) which is (label0.score=0.7, label1.score=0.2, label2.cores=0.4)\n\n box2.data = (3.0, 4.0, 8.0, 5.0)\n box2.score = (0.3, 0.3, 0.1)\n\n nms_threshold = 0.3\n background_label = 0\n score_threshold = 0\n\n\n Then:\n iou = 4/11 > 0.3\n out.data = [[1, 0.3, 3.0, 4.0, 8.0, 5.0], \n [2, 0.4, 2.0, 3.0, 7.0, 5.0]]\n \n Out format is (label, confidence, xmin, ymin, xmax, ymax)\n Args:\n bboxes (Variable): Two types of bboxes are supported:\n 1. (Tensor) A 3-D Tensor with shape\n [N, M, 4 or 8 16 24 32] represents the\n predicted locations of M bounding bboxes,\n N is the batch size. Each bounding box has four\n coordinate values and the layout is \n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n 2. (LoDTensor) A 3-D Tensor with shape [M, C, 4]\n M is the number of bounding boxes, C is the \n class number. The data type is float32 or float64. \n scores (Variable): Two types of scores are supported:\n 1. (Tensor) A 3-D Tensor with shape [N, C, M]\n represents the predicted confidence predictions.\n N is the batch size, C is the class number, M is \n number of bounding boxes. For each category there \n are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension\n of BBoxes.The data type is float32 or float64. \n 2. (LoDTensor) A 2-D LoDTensor with shape [M, C].\n M is the number of bbox, C is the class number.\n In this case, input BBoxes should be the second\n case with shape [M, C, 4].The data type is float32 or float64. \n background_label (int): The index of background label, the background \n label will be ignored. If set to -1, then all\n categories will be considered. Default: 0\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score. If not provided, \n consider all boxes.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n nms_threshold (float): The threshold to be used in NMS. Default: 0.3\n nms_eta (float): The threshold to be used in NMS. Default: 1.0\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n normalized (bool): Whether detections are normalized. Default: True\n name(str): Name of the multiclass nms op. Default: None.\n\n Returns:\n Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n or A 2-D LoDTensor with shape [No, 10] represents the detections.\n Each row has 10 values: \n [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the \n total number of detections. If there is no detected boxes for all\n images, lod will be set to {1} and Out only contains one value\n which is -1.\n (After version 1.3, when no boxes detected, the lod is changed \n from {0} to {1}) \n\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None,81, 4],\n dtype='float32', lod_level=1)\n scores = fluid.data(name='scores', shape=[None,81],\n dtype='float32', lod_level=1)\n out = fluid.layers.multiclass_nms(bboxes=boxes,\n scores=scores,\n background_label=0,\n score_threshold=0.5,\n nms_top_k=400,\n nms_threshold=0.3,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], 'multiclass_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], 'multiclass_nms')
check_type(score_threshold, 'score_threshold', float, 'multicalss_nms')
check_type(nms_top_k, 'nums_top_k', int, 'multiclass_nms')
check_type(keep_top_k, 'keep_top_k', int, 'mutliclass_nms')
check_type(nms_threshold, 'nms_threshold', float, 'multiclass_nms')
check_type(normalized, 'normalized', bool, 'multiclass_nms')
check_type(nms_eta, 'nms_eta', float, 'multiclass_nms')
check_type(background_label, 'background_label', int, 'multiclass_nms')
helper = LayerHelper('multiclass_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
helper.append_op(type='multiclass_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'nms_eta': nms_eta, 'keep_top_k': keep_top_k, 'normalized': normalized}, outputs={'Out': output})
output.stop_gradient = True
return output |
def locality_aware_nms(bboxes, scores, score_threshold, nms_top_k, keep_top_k, nms_threshold=0.3, normalized=True, nms_eta=1.0, background_label=(- 1), name=None):
"\n **Local Aware NMS**\n \n `Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum\n suppression (LANMS) on boxes and scores.\n\n Firstly, this operator merge box and score according their IOU\n (intersection over union). In the NMS step, this operator greedily selects a\n subset of detection bounding boxes that have high scores larger than score_threshold,\n if providing this threshold, then selects the largest nms_top_k confidences scores\n if nms_top_k is larger than -1. Then this operator pruns away boxes that have high\n IOU overlap with already selected boxes by adaptive threshold NMS based on parameters\n of nms_threshold and nms_eta.\n\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n Args:\n bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32]\n represents the predicted locations of M bounding\n bboxes, N is the batch size. Each bounding box\n has four coordinate values and the layout is\n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n scores (Variable): A 3-D Tensor with shape [N, C, M] represents the\n predicted confidence predictions. N is the batch\n size, C is the class number, M is number of bounding\n boxes. Now only support 1 class. For each category\n there are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension of\n BBoxes. The data type is float32 or float64.\n background_label (int): The index of background label, the background\n label will be ignored. If set to -1, then all\n categories will be considered. Default: -1\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score. If not provided,\n consider all boxes.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n nms_threshold (float): The threshold to be used in NMS. Default: 0.3\n nms_eta (float): The threshold to be used in NMS. Default: 1.0\n normalized (bool): Whether detections are normalized. Default: True\n name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .\n Default: None.\n\n Returns:\n Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n or A 2-D LoDTensor with shape [No, 10] represents the detections.\n Each row has 10 values:\n [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the\n total number of detections. If there is no detected boxes for all\n images, lod will be set to {1} and Out only contains one value\n which is -1.\n (After version 1.3, when no boxes detected, the lod is changed\n from {0} to {1}). The data type is float32 or float64.\n\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None, 81, 8],\n dtype='float32')\n scores = fluid.data(name='scores', shape=[None, 1, 81],\n dtype='float32')\n out = fluid.layers.locality_aware_nms(bboxes=boxes,\n scores=scores,\n score_threshold=0.5,\n nms_top_k=400,\n nms_threshold=0.3,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'bboxes', ['float32', 'float64'], 'locality_aware_nms')
check_variable_and_dtype(scores, 'scores', ['float32', 'float64'], 'locality_aware_nms')
check_type(background_label, 'background_label', int, 'locality_aware_nms')
check_type(score_threshold, 'score_threshold', float, 'locality_aware_nms')
check_type(nms_top_k, 'nms_top_k', int, 'locality_aware_nms')
check_type(nms_eta, 'nms_eta', float, 'locality_aware_nms')
check_type(nms_threshold, 'nms_threshold', float, 'locality_aware_nms')
check_type(keep_top_k, 'keep_top_k', int, 'locality_aware_nms')
check_type(normalized, 'normalized', bool, 'locality_aware_nms')
shape = scores.shape
assert (len(shape) == 3), 'dim size of scores must be 3'
assert (shape[1] == 1), 'locality_aware_nms only support one class, Tensor score shape must be [N, 1, M]'
helper = LayerHelper('locality_aware_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
out = {'Out': output}
helper.append_op(type='locality_aware_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'nms_eta': nms_eta, 'keep_top_k': keep_top_k, 'nms_eta': nms_eta, 'normalized': normalized}, outputs={'Out': output})
output.stop_gradient = True
return output | -8,855,049,203,573,389,000 | **Local Aware NMS**
`Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum
suppression (LANMS) on boxes and scores.
Firstly, this operator merge box and score according their IOU
(intersection over union). 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 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.
Args:
bboxes (Variable): A 3-D 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.
scores (Variable): A 3-D Tensor with shape [N, C, M] represents the
predicted confidence predictions. N is the batch
size, C is the class number, M is number of bounding
boxes. Now only support 1 class. 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.
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: -1
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 after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
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
normalized (bool): Whether detections are normalized. Default: True
name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .
Default: None.
Returns:
Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
or A 2-D 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}). The data type is float32 or float64.
Examples:
.. code-block:: python
import paddle.fluid as fluid
boxes = fluid.data(name='bboxes', shape=[None, 81, 8],
dtype='float32')
scores = fluid.data(name='scores', shape=[None, 1, 81],
dtype='float32')
out = fluid.layers.locality_aware_nms(bboxes=boxes,
scores=scores,
score_threshold=0.5,
nms_top_k=400,
nms_threshold=0.3,
keep_top_k=200,
normalized=False) | python/paddle/fluid/layers/detection.py | locality_aware_nms | 92lqllearning/Paddle | python | def locality_aware_nms(bboxes, scores, score_threshold, nms_top_k, keep_top_k, nms_threshold=0.3, normalized=True, nms_eta=1.0, background_label=(- 1), name=None):
"\n **Local Aware NMS**\n \n `Local Aware NMS <https://arxiv.org/abs/1704.03155>`_ is to do locality-aware non maximum\n suppression (LANMS) on boxes and scores.\n\n Firstly, this operator merge box and score according their IOU\n (intersection over union). In the NMS step, this operator greedily selects a\n subset of detection bounding boxes that have high scores larger than score_threshold,\n if providing this threshold, then selects the largest nms_top_k confidences scores\n if nms_top_k is larger than -1. Then this operator pruns away boxes that have high\n IOU overlap with already selected boxes by adaptive threshold NMS based on parameters\n of nms_threshold and nms_eta.\n\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n Args:\n bboxes (Variable): A 3-D Tensor with shape [N, M, 4 or 8 16 24 32]\n represents the predicted locations of M bounding\n bboxes, N is the batch size. Each bounding box\n has four coordinate values and the layout is\n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n scores (Variable): A 3-D Tensor with shape [N, C, M] represents the\n predicted confidence predictions. N is the batch\n size, C is the class number, M is number of bounding\n boxes. Now only support 1 class. For each category\n there are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension of\n BBoxes. The data type is float32 or float64.\n background_label (int): The index of background label, the background\n label will be ignored. If set to -1, then all\n categories will be considered. Default: -1\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score. If not provided,\n consider all boxes.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n nms_threshold (float): The threshold to be used in NMS. Default: 0.3\n nms_eta (float): The threshold to be used in NMS. Default: 1.0\n normalized (bool): Whether detections are normalized. Default: True\n name(str): Name of the locality aware nms op, please refer to :ref:`api_guide_Name` .\n Default: None.\n\n Returns:\n Variable: A 2-D LoDTensor with shape [No, 6] represents the detections.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n or A 2-D LoDTensor with shape [No, 10] represents the detections.\n Each row has 10 values:\n [label, confidence, x1, y1, x2, y2, x3, y3, x4, y4]. No is the\n total number of detections. If there is no detected boxes for all\n images, lod will be set to {1} and Out only contains one value\n which is -1.\n (After version 1.3, when no boxes detected, the lod is changed\n from {0} to {1}). The data type is float32 or float64.\n\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None, 81, 8],\n dtype='float32')\n scores = fluid.data(name='scores', shape=[None, 1, 81],\n dtype='float32')\n out = fluid.layers.locality_aware_nms(bboxes=boxes,\n scores=scores,\n score_threshold=0.5,\n nms_top_k=400,\n nms_threshold=0.3,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'bboxes', ['float32', 'float64'], 'locality_aware_nms')
check_variable_and_dtype(scores, 'scores', ['float32', 'float64'], 'locality_aware_nms')
check_type(background_label, 'background_label', int, 'locality_aware_nms')
check_type(score_threshold, 'score_threshold', float, 'locality_aware_nms')
check_type(nms_top_k, 'nms_top_k', int, 'locality_aware_nms')
check_type(nms_eta, 'nms_eta', float, 'locality_aware_nms')
check_type(nms_threshold, 'nms_threshold', float, 'locality_aware_nms')
check_type(keep_top_k, 'keep_top_k', int, 'locality_aware_nms')
check_type(normalized, 'normalized', bool, 'locality_aware_nms')
shape = scores.shape
assert (len(shape) == 3), 'dim size of scores must be 3'
assert (shape[1] == 1), 'locality_aware_nms only support one class, Tensor score shape must be [N, 1, M]'
helper = LayerHelper('locality_aware_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
out = {'Out': output}
helper.append_op(type='locality_aware_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'nms_top_k': nms_top_k, 'nms_threshold': nms_threshold, 'nms_eta': nms_eta, 'keep_top_k': keep_top_k, 'nms_eta': nms_eta, 'normalized': normalized}, outputs={'Out': output})
output.stop_gradient = True
return output |
def matrix_nms(bboxes, scores, score_threshold, post_threshold, nms_top_k, keep_top_k, use_gaussian=False, gaussian_sigma=2.0, background_label=0, normalized=True, return_index=False, name=None):
"\n **Matrix NMS**\n\n This operator does matrix non maximum suppression (NMS).\n\n First selects a subset of candidate bounding boxes that have higher scores\n than score_threshold (if provided), then the top k candidate is selected if\n nms_top_k is larger than -1. Score of the remaining candidate are then\n decayed according to the Matrix NMS scheme.\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n Args:\n bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the\n predicted locations of M bounding bboxes,\n N is the batch size. Each bounding box has four\n coordinate values and the layout is\n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n scores (Variable): A 3-D Tensor with shape [N, C, M]\n represents the predicted confidence predictions.\n N is the batch size, C is the class number, M is\n number of bounding boxes. For each category there\n are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension\n of BBoxes. The data type is float32 or float64.\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score.\n post_threshold (float): Threshold to filter out bounding boxes with\n low confidence score AFTER decaying.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n use_gaussian (bool): Use Gaussian as the decay function. Default: False\n gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0\n background_label (int): The index of background label, the background\n label will be ignored. If set to -1, then all\n categories will be considered. Default: 0\n normalized (bool): Whether detections are normalized. Default: True\n return_index(bool): Whether return selected index. Default: False\n name(str): Name of the matrix nms op. Default: None.\n\n Returns:\n A tuple with two Variables: (Out, Index) if return_index is True,\n otherwise, one Variable(Out) is returned.\n\n Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the\n detection results.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n (After version 1.3, when no boxes detected, the lod is changed\n from {0} to {1})\n\n Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the\n selected indices, which are absolute values cross batches.\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None,81, 4],\n dtype='float32', lod_level=1)\n scores = fluid.data(name='scores', shape=[None,81],\n dtype='float32', lod_level=1)\n out = fluid.layers.matrix_nms(bboxes=boxes,\n scores=scores,\n background_label=0,\n score_threshold=0.5,\n post_threshold=0.1,\n nms_top_k=400,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], 'matrix_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], 'matrix_nms')
check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
check_type(normalized, 'normalized', bool, 'matrix_nms')
check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
check_type(background_label, 'background_label', int, 'matrix_nms')
helper = LayerHelper('matrix_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(type='matrix_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'post_threshold': post_threshold, 'nms_top_k': nms_top_k, 'gaussian_sigma': gaussian_sigma, 'use_gaussian': use_gaussian, 'keep_top_k': keep_top_k, 'normalized': normalized}, outputs={'Out': output, 'Index': index})
output.stop_gradient = True
if return_index:
return (output, index)
else:
return output | 4,937,063,959,042,622,000 | **Matrix NMS**
This operator does matrix non maximum suppression (NMS).
First selects a subset of candidate bounding boxes that have higher scores
than score_threshold (if provided), then the top k candidate is selected if
nms_top_k is larger than -1. Score of the remaining candidate are then
decayed according to the Matrix NMS scheme.
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.
Args:
bboxes (Variable): A 3-D Tensor with shape [N, M, 4] 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.
scores (Variable): A 3-D Tensor with shape [N, C, M]
represents the predicted confidence predictions.
N is the batch size, C is the class number, M is
number of bounding boxes. For each category there
are total M scores which corresponding M bounding
boxes. Please note, M is equal to the 2nd dimension
of BBoxes. The data type is float32 or float64.
score_threshold (float): Threshold to filter out bounding boxes with
low confidence score.
post_threshold (float): Threshold to filter out bounding boxes with
low confidence score AFTER decaying.
nms_top_k (int): Maximum number of detections to be kept according to
the confidences after the filtering detections based
on score_threshold.
keep_top_k (int): Number of total bboxes to be kept per image after NMS
step. -1 means keeping all bboxes after NMS step.
use_gaussian (bool): Use Gaussian as the decay function. Default: False
gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0
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
normalized (bool): Whether detections are normalized. Default: True
return_index(bool): Whether return selected index. Default: False
name(str): Name of the matrix nms op. Default: None.
Returns:
A tuple with two Variables: (Out, Index) if return_index is True,
otherwise, one Variable(Out) is returned.
Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the
detection results.
Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]
(After version 1.3, when no boxes detected, the lod is changed
from {0} to {1})
Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the
selected indices, which are absolute values cross batches.
Examples:
.. code-block:: python
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.matrix_nms(bboxes=boxes,
scores=scores,
background_label=0,
score_threshold=0.5,
post_threshold=0.1,
nms_top_k=400,
keep_top_k=200,
normalized=False) | python/paddle/fluid/layers/detection.py | matrix_nms | 92lqllearning/Paddle | python | def matrix_nms(bboxes, scores, score_threshold, post_threshold, nms_top_k, keep_top_k, use_gaussian=False, gaussian_sigma=2.0, background_label=0, normalized=True, return_index=False, name=None):
"\n **Matrix NMS**\n\n This operator does matrix non maximum suppression (NMS).\n\n First selects a subset of candidate bounding boxes that have higher scores\n than score_threshold (if provided), then the top k candidate is selected if\n nms_top_k is larger than -1. Score of the remaining candidate are then\n decayed according to the Matrix NMS scheme.\n Aftern NMS step, at most keep_top_k number of total bboxes are to be kept\n per image if keep_top_k is larger than -1.\n\n Args:\n bboxes (Variable): A 3-D Tensor with shape [N, M, 4] represents the\n predicted locations of M bounding bboxes,\n N is the batch size. Each bounding box has four\n coordinate values and the layout is\n [xmin, ymin, xmax, ymax], when box size equals to 4.\n The data type is float32 or float64.\n scores (Variable): A 3-D Tensor with shape [N, C, M]\n represents the predicted confidence predictions.\n N is the batch size, C is the class number, M is\n number of bounding boxes. For each category there\n are total M scores which corresponding M bounding\n boxes. Please note, M is equal to the 2nd dimension\n of BBoxes. The data type is float32 or float64.\n score_threshold (float): Threshold to filter out bounding boxes with\n low confidence score.\n post_threshold (float): Threshold to filter out bounding boxes with\n low confidence score AFTER decaying.\n nms_top_k (int): Maximum number of detections to be kept according to\n the confidences after the filtering detections based\n on score_threshold.\n keep_top_k (int): Number of total bboxes to be kept per image after NMS\n step. -1 means keeping all bboxes after NMS step.\n use_gaussian (bool): Use Gaussian as the decay function. Default: False\n gaussian_sigma (float): Sigma for Gaussian decay function. Default: 2.0\n background_label (int): The index of background label, the background\n label will be ignored. If set to -1, then all\n categories will be considered. Default: 0\n normalized (bool): Whether detections are normalized. Default: True\n return_index(bool): Whether return selected index. Default: False\n name(str): Name of the matrix nms op. Default: None.\n\n Returns:\n A tuple with two Variables: (Out, Index) if return_index is True,\n otherwise, one Variable(Out) is returned.\n\n Out (Variable): A 2-D LoDTensor with shape [No, 6] containing the\n detection results.\n Each row has 6 values: [label, confidence, xmin, ymin, xmax, ymax]\n (After version 1.3, when no boxes detected, the lod is changed\n from {0} to {1})\n\n Index (Variable): A 2-D LoDTensor with shape [No, 1] containing the\n selected indices, which are absolute values cross batches.\n\n Examples:\n .. code-block:: python\n\n\n import paddle.fluid as fluid\n boxes = fluid.data(name='bboxes', shape=[None,81, 4],\n dtype='float32', lod_level=1)\n scores = fluid.data(name='scores', shape=[None,81],\n dtype='float32', lod_level=1)\n out = fluid.layers.matrix_nms(bboxes=boxes,\n scores=scores,\n background_label=0,\n score_threshold=0.5,\n post_threshold=0.1,\n nms_top_k=400,\n keep_top_k=200,\n normalized=False)\n "
check_variable_and_dtype(bboxes, 'BBoxes', ['float32', 'float64'], 'matrix_nms')
check_variable_and_dtype(scores, 'Scores', ['float32', 'float64'], 'matrix_nms')
check_type(score_threshold, 'score_threshold', float, 'matrix_nms')
check_type(post_threshold, 'post_threshold', float, 'matrix_nms')
check_type(nms_top_k, 'nums_top_k', int, 'matrix_nms')
check_type(keep_top_k, 'keep_top_k', int, 'matrix_nms')
check_type(normalized, 'normalized', bool, 'matrix_nms')
check_type(use_gaussian, 'use_gaussian', bool, 'matrix_nms')
check_type(gaussian_sigma, 'gaussian_sigma', float, 'matrix_nms')
check_type(background_label, 'background_label', int, 'matrix_nms')
helper = LayerHelper('matrix_nms', **locals())
output = helper.create_variable_for_type_inference(dtype=bboxes.dtype)
index = helper.create_variable_for_type_inference(dtype='int')
helper.append_op(type='matrix_nms', inputs={'BBoxes': bboxes, 'Scores': scores}, attrs={'background_label': background_label, 'score_threshold': score_threshold, 'post_threshold': post_threshold, 'nms_top_k': nms_top_k, 'gaussian_sigma': gaussian_sigma, 'use_gaussian': use_gaussian, 'keep_top_k': keep_top_k, 'normalized': normalized}, outputs={'Out': output, 'Index': index})
output.stop_gradient = True
if return_index:
return (output, index)
else:
return output |
def distribute_fpn_proposals(fpn_rois, min_level, max_level, refer_level, refer_scale, name=None):
"\n\t:alias_main: paddle.nn.functional.distribute_fpn_proposals\n\t:alias: paddle.nn.functional.distribute_fpn_proposals,paddle.nn.functional.vision.distribute_fpn_proposals\n\t:old_api: paddle.fluid.layers.distribute_fpn_proposals\n\t\n **This op only takes LoDTensor as input.** In Feature Pyramid Networks \n (FPN) models, it is needed to distribute all proposals into different FPN \n level, with respect to scale of the proposals, the referring scale and the \n referring level. Besides, to restore the order of proposals, we return an \n array which indicates the original index of rois in current proposals. \n To compute FPN level for each roi, the formula is given as follows:\n \n .. math::\n\n roi\\_scale &= \\sqrt{BBoxArea(fpn\\_roi)}\n\n level = floor(&\\log(\\frac{roi\\_scale}{refer\\_scale}) + refer\\_level)\n\n where BBoxArea is a function to compute the area of each roi.\n\n Args:\n\n fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is \n float32 or float64. The input fpn_rois.\n min_level(int32): The lowest level of FPN layer where the proposals come \n from.\n max_level(int32): The highest level of FPN layer where the proposals\n come from.\n refer_level(int32): The referring level of FPN layer with specified scale.\n refer_scale(int32): The referring scale of FPN layer with specified level.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Tuple:\n\n multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4] \n and data type of float32 and float64. The length is \n max_level-min_level+1. The proposals in each FPN level.\n\n restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is \n the number of total rois. The data type is int32. It is\n used to restore the order of fpn_rois.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n fpn_rois = fluid.data(\n name='data', shape=[None, 4], dtype='float32', lod_level=1)\n multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals(\n fpn_rois=fpn_rois,\n min_level=2,\n max_level=5,\n refer_level=4,\n refer_scale=224)\n "
check_variable_and_dtype(fpn_rois, 'fpn_rois', ['float32', 'float64'], 'distribute_fpn_proposals')
helper = LayerHelper('distribute_fpn_proposals', **locals())
dtype = helper.input_dtype('fpn_rois')
num_lvl = ((max_level - min_level) + 1)
multi_rois = [helper.create_variable_for_type_inference(dtype) for i in range(num_lvl)]
restore_ind = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(type='distribute_fpn_proposals', inputs={'FpnRois': fpn_rois}, outputs={'MultiFpnRois': multi_rois, 'RestoreIndex': restore_ind}, attrs={'min_level': min_level, 'max_level': max_level, 'refer_level': refer_level, 'refer_scale': refer_scale})
return (multi_rois, restore_ind) | -1,772,570,103,615,518,700 | :alias_main: paddle.nn.functional.distribute_fpn_proposals
:alias: paddle.nn.functional.distribute_fpn_proposals,paddle.nn.functional.vision.distribute_fpn_proposals
:old_api: paddle.fluid.layers.distribute_fpn_proposals
**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:
.. math::
roi\_scale &= \sqrt{BBoxArea(fpn\_roi)}
level = floor(&\log(\frac{roi\_scale}{refer\_scale}) + refer\_level)
where BBoxArea is a function to compute the area of each roi.
Args:
fpn_rois(Variable): 2-D 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 :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4]
and data type of float32 and float64. The length is
max_level-min_level+1. The proposals in each FPN level.
restore_ind(Variable): A 2-D 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.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | distribute_fpn_proposals | 92lqllearning/Paddle | python | def distribute_fpn_proposals(fpn_rois, min_level, max_level, refer_level, refer_scale, name=None):
"\n\t:alias_main: paddle.nn.functional.distribute_fpn_proposals\n\t:alias: paddle.nn.functional.distribute_fpn_proposals,paddle.nn.functional.vision.distribute_fpn_proposals\n\t:old_api: paddle.fluid.layers.distribute_fpn_proposals\n\t\n **This op only takes LoDTensor as input.** In Feature Pyramid Networks \n (FPN) models, it is needed to distribute all proposals into different FPN \n level, with respect to scale of the proposals, the referring scale and the \n referring level. Besides, to restore the order of proposals, we return an \n array which indicates the original index of rois in current proposals. \n To compute FPN level for each roi, the formula is given as follows:\n \n .. math::\n\n roi\\_scale &= \\sqrt{BBoxArea(fpn\\_roi)}\n\n level = floor(&\\log(\\frac{roi\\_scale}{refer\\_scale}) + refer\\_level)\n\n where BBoxArea is a function to compute the area of each roi.\n\n Args:\n\n fpn_rois(Variable): 2-D Tensor with shape [N, 4] and data type is \n float32 or float64. The input fpn_rois.\n min_level(int32): The lowest level of FPN layer where the proposals come \n from.\n max_level(int32): The highest level of FPN layer where the proposals\n come from.\n refer_level(int32): The referring level of FPN layer with specified scale.\n refer_scale(int32): The referring scale of FPN layer with specified level.\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Tuple:\n\n multi_rois(List) : A list of 2-D LoDTensor with shape [M, 4] \n and data type of float32 and float64. The length is \n max_level-min_level+1. The proposals in each FPN level.\n\n restore_ind(Variable): A 2-D Tensor with shape [N, 1], N is \n the number of total rois. The data type is int32. It is\n used to restore the order of fpn_rois.\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n fpn_rois = fluid.data(\n name='data', shape=[None, 4], dtype='float32', lod_level=1)\n multi_rois, restore_ind = fluid.layers.distribute_fpn_proposals(\n fpn_rois=fpn_rois,\n min_level=2,\n max_level=5,\n refer_level=4,\n refer_scale=224)\n "
check_variable_and_dtype(fpn_rois, 'fpn_rois', ['float32', 'float64'], 'distribute_fpn_proposals')
helper = LayerHelper('distribute_fpn_proposals', **locals())
dtype = helper.input_dtype('fpn_rois')
num_lvl = ((max_level - min_level) + 1)
multi_rois = [helper.create_variable_for_type_inference(dtype) for i in range(num_lvl)]
restore_ind = helper.create_variable_for_type_inference(dtype='int32')
helper.append_op(type='distribute_fpn_proposals', inputs={'FpnRois': fpn_rois}, outputs={'MultiFpnRois': multi_rois, 'RestoreIndex': restore_ind}, attrs={'min_level': min_level, 'max_level': max_level, 'refer_level': refer_level, 'refer_scale': refer_scale})
return (multi_rois, restore_ind) |
@templatedoc()
def box_decoder_and_assign(prior_box, prior_box_var, target_box, box_score, box_clip, name=None):
"\n\t:alias_main: paddle.nn.functional.box_decoder_and_assign\n\t:alias: paddle.nn.functional.box_decoder_and_assign,paddle.nn.functional.vision.box_decoder_and_assign\n\t:old_api: paddle.fluid.layers.box_decoder_and_assign\n\t\n ${comment}\n Args:\n prior_box(${prior_box_type}): ${prior_box_comment}\n prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}\n target_box(${target_box_type}): ${target_box_comment}\n box_score(${box_score_type}): ${box_score_comment}\n box_clip(${box_clip_type}): ${box_clip_comment}\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Tuple:\n\n decode_box(${decode_box_type}): ${decode_box_comment}\n\n output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n pb = fluid.data(\n name='prior_box', shape=[None, 4], dtype='float32')\n pbv = fluid.data(\n name='prior_box_var', shape=[4], dtype='float32')\n loc = fluid.data(\n name='target_box', shape=[None, 4*81], dtype='float32')\n scores = fluid.data(\n name='scores', shape=[None, 81], dtype='float32')\n decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign(\n pb, pbv, loc, scores, 4.135)\n\n "
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'], 'box_decoder_and_assign')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'], 'box_decoder_and_assign')
check_variable_and_dtype(box_score, 'box_score', ['float32', 'float64'], 'box_decoder_and_assign')
helper = LayerHelper('box_decoder_and_assign', **locals())
decoded_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
output_assign_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
helper.append_op(type='box_decoder_and_assign', inputs={'PriorBox': prior_box, 'PriorBoxVar': prior_box_var, 'TargetBox': target_box, 'BoxScore': box_score}, attrs={'box_clip': box_clip}, outputs={'DecodeBox': decoded_box, 'OutputAssignBox': output_assign_box})
return (decoded_box, output_assign_box) | 7,764,178,062,581,068,000 | :alias_main: paddle.nn.functional.box_decoder_and_assign
:alias: paddle.nn.functional.box_decoder_and_assign,paddle.nn.functional.vision.box_decoder_and_assign
:old_api: paddle.fluid.layers.box_decoder_and_assign
${comment}
Args:
prior_box(${prior_box_type}): ${prior_box_comment}
prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}
target_box(${target_box_type}): ${target_box_comment}
box_score(${box_score_type}): ${box_score_comment}
box_clip(${box_clip_type}): ${box_clip_comment}
name(str, optional): For detailed information, please refer
to :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Tuple:
decode_box(${decode_box_type}): ${decode_box_comment}
output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | box_decoder_and_assign | 92lqllearning/Paddle | python | @templatedoc()
def box_decoder_and_assign(prior_box, prior_box_var, target_box, box_score, box_clip, name=None):
"\n\t:alias_main: paddle.nn.functional.box_decoder_and_assign\n\t:alias: paddle.nn.functional.box_decoder_and_assign,paddle.nn.functional.vision.box_decoder_and_assign\n\t:old_api: paddle.fluid.layers.box_decoder_and_assign\n\t\n ${comment}\n Args:\n prior_box(${prior_box_type}): ${prior_box_comment}\n prior_box_var(${prior_box_var_type}): ${prior_box_var_comment}\n target_box(${target_box_type}): ${target_box_comment}\n box_score(${box_score_type}): ${box_score_comment}\n box_clip(${box_clip_type}): ${box_clip_comment}\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Tuple:\n\n decode_box(${decode_box_type}): ${decode_box_comment}\n\n output_assign_box(${output_assign_box_type}): ${output_assign_box_comment}\n\n\n Examples:\n .. code-block:: python\n\n import paddle.fluid as fluid\n pb = fluid.data(\n name='prior_box', shape=[None, 4], dtype='float32')\n pbv = fluid.data(\n name='prior_box_var', shape=[4], dtype='float32')\n loc = fluid.data(\n name='target_box', shape=[None, 4*81], dtype='float32')\n scores = fluid.data(\n name='scores', shape=[None, 81], dtype='float32')\n decoded_box, output_assign_box = fluid.layers.box_decoder_and_assign(\n pb, pbv, loc, scores, 4.135)\n\n "
check_variable_and_dtype(prior_box, 'prior_box', ['float32', 'float64'], 'box_decoder_and_assign')
check_variable_and_dtype(target_box, 'target_box', ['float32', 'float64'], 'box_decoder_and_assign')
check_variable_and_dtype(box_score, 'box_score', ['float32', 'float64'], 'box_decoder_and_assign')
helper = LayerHelper('box_decoder_and_assign', **locals())
decoded_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
output_assign_box = helper.create_variable_for_type_inference(dtype=prior_box.dtype)
helper.append_op(type='box_decoder_and_assign', inputs={'PriorBox': prior_box, 'PriorBoxVar': prior_box_var, 'TargetBox': target_box, 'BoxScore': box_score}, attrs={'box_clip': box_clip}, outputs={'DecodeBox': decoded_box, 'OutputAssignBox': output_assign_box})
return (decoded_box, output_assign_box) |
def collect_fpn_proposals(multi_rois, multi_scores, min_level, max_level, post_nms_top_n, name=None):
"\n\t:alias_main: paddle.nn.functional.collect_fpn_proposals\n\t:alias: paddle.nn.functional.collect_fpn_proposals,paddle.nn.functional.vision.collect_fpn_proposals\n\t:old_api: paddle.fluid.layers.collect_fpn_proposals\n\t\n **This OP only supports LoDTensor as input**. Concat multi-level RoIs \n (Region of Interest) and select N RoIs with respect to multi_scores. \n This operation performs the following steps:\n\n 1. Choose num_level RoIs and scores as input: num_level = max_level - min_level\n 2. Concat multi-level RoIs and scores\n 3. Sort scores and select post_nms_top_n scores\n 4. Gather RoIs by selected indices from scores\n 5. Re-sort RoIs by corresponding batch_id\n\n Args:\n multi_rois(list): List of RoIs to collect. Element in list is 2-D \n LoDTensor with shape [N, 4] and data type is float32 or float64, \n N is the number of RoIs.\n multi_scores(list): List of scores of RoIs to collect. Element in list \n is 2-D LoDTensor with shape [N, 1] and data type is float32 or\n float64, N is the number of RoIs.\n min_level(int): The lowest level of FPN layer to collect\n max_level(int): The highest level of FPN layer to collect\n post_nms_top_n(int): The number of selected RoIs\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Variable:\n\n fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is \n float32 or float64. Selected RoIs. \n\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n multi_rois = []\n multi_scores = []\n for i in range(4):\n multi_rois.append(fluid.data(\n name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))\n for i in range(4):\n multi_scores.append(fluid.data(\n name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))\n\n fpn_rois = fluid.layers.collect_fpn_proposals(\n multi_rois=multi_rois, \n multi_scores=multi_scores,\n min_level=2, \n max_level=5, \n post_nms_top_n=2000)\n "
check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals')
check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals')
helper = LayerHelper('collect_fpn_proposals', **locals())
dtype = helper.input_dtype('multi_rois')
check_dtype(dtype, 'multi_rois', ['float32', 'float64'], 'collect_fpn_proposals')
num_lvl = ((max_level - min_level) + 1)
input_rois = multi_rois[:num_lvl]
input_scores = multi_scores[:num_lvl]
output_rois = helper.create_variable_for_type_inference(dtype)
output_rois.stop_gradient = True
helper.append_op(type='collect_fpn_proposals', inputs={'MultiLevelRois': input_rois, 'MultiLevelScores': input_scores}, outputs={'FpnRois': output_rois}, attrs={'post_nms_topN': post_nms_top_n})
return output_rois | -8,454,494,883,364,616,000 | :alias_main: paddle.nn.functional.collect_fpn_proposals
:alias: paddle.nn.functional.collect_fpn_proposals,paddle.nn.functional.vision.collect_fpn_proposals
:old_api: paddle.fluid.layers.collect_fpn_proposals
**This OP only supports LoDTensor as input**. Concat multi-level RoIs
(Region of Interest) and select N RoIs with respect to multi_scores.
This operation performs the following steps:
1. Choose num_level RoIs and scores as input: num_level = max_level - min_level
2. Concat multi-level RoIs and scores
3. Sort scores and select post_nms_top_n scores
4. Gather RoIs by selected indices from scores
5. Re-sort RoIs by corresponding batch_id
Args:
multi_rois(list): List of RoIs to collect. Element in list is 2-D
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 2-D 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 :ref:`api_guide_Name`. Usually name is no need to set and
None by default.
Returns:
Variable:
fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is
float32 or float64. Selected RoIs.
Examples:
.. code-block:: python
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) | python/paddle/fluid/layers/detection.py | collect_fpn_proposals | 92lqllearning/Paddle | python | def collect_fpn_proposals(multi_rois, multi_scores, min_level, max_level, post_nms_top_n, name=None):
"\n\t:alias_main: paddle.nn.functional.collect_fpn_proposals\n\t:alias: paddle.nn.functional.collect_fpn_proposals,paddle.nn.functional.vision.collect_fpn_proposals\n\t:old_api: paddle.fluid.layers.collect_fpn_proposals\n\t\n **This OP only supports LoDTensor as input**. Concat multi-level RoIs \n (Region of Interest) and select N RoIs with respect to multi_scores. \n This operation performs the following steps:\n\n 1. Choose num_level RoIs and scores as input: num_level = max_level - min_level\n 2. Concat multi-level RoIs and scores\n 3. Sort scores and select post_nms_top_n scores\n 4. Gather RoIs by selected indices from scores\n 5. Re-sort RoIs by corresponding batch_id\n\n Args:\n multi_rois(list): List of RoIs to collect. Element in list is 2-D \n LoDTensor with shape [N, 4] and data type is float32 or float64, \n N is the number of RoIs.\n multi_scores(list): List of scores of RoIs to collect. Element in list \n is 2-D LoDTensor with shape [N, 1] and data type is float32 or\n float64, N is the number of RoIs.\n min_level(int): The lowest level of FPN layer to collect\n max_level(int): The highest level of FPN layer to collect\n post_nms_top_n(int): The number of selected RoIs\n name(str, optional): For detailed information, please refer \n to :ref:`api_guide_Name`. Usually name is no need to set and \n None by default. \n\n Returns:\n Variable:\n\n fpn_rois(Variable): 2-D LoDTensor with shape [N, 4] and data type is \n float32 or float64. Selected RoIs. \n\n\n Examples:\n .. code-block:: python\n \n import paddle.fluid as fluid\n multi_rois = []\n multi_scores = []\n for i in range(4):\n multi_rois.append(fluid.data(\n name='roi_'+str(i), shape=[None, 4], dtype='float32', lod_level=1))\n for i in range(4):\n multi_scores.append(fluid.data(\n name='score_'+str(i), shape=[None, 1], dtype='float32', lod_level=1))\n\n fpn_rois = fluid.layers.collect_fpn_proposals(\n multi_rois=multi_rois, \n multi_scores=multi_scores,\n min_level=2, \n max_level=5, \n post_nms_top_n=2000)\n "
check_type(multi_rois, 'multi_rois', list, 'collect_fpn_proposals')
check_type(multi_scores, 'multi_scores', list, 'collect_fpn_proposals')
helper = LayerHelper('collect_fpn_proposals', **locals())
dtype = helper.input_dtype('multi_rois')
check_dtype(dtype, 'multi_rois', ['float32', 'float64'], 'collect_fpn_proposals')
num_lvl = ((max_level - min_level) + 1)
input_rois = multi_rois[:num_lvl]
input_scores = multi_scores[:num_lvl]
output_rois = helper.create_variable_for_type_inference(dtype)
output_rois.stop_gradient = True
helper.append_op(type='collect_fpn_proposals', inputs={'MultiLevelRois': input_rois, 'MultiLevelScores': input_scores}, outputs={'FpnRois': output_rois}, attrs={'post_nms_topN': post_nms_top_n})
return output_rois |
def adm_doses_italy(save_image=False, show=False):
'\n Administration data about Italy.\n '
plt.bar(italy_df['data_somministrazione'], italy_df['prima_dose'], label='Prime dosi')
plt.bar(italy_df['data_somministrazione'], italy_df['seconda_dose'], bottom=italy_df['prima_dose'], label='Seconde dosi')
plt.title('Somministrazioni giornaliere Italia,\ncon distinzione prima dose/richiamo\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_italia.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() | 7,212,101,780,947,173,000 | Administration data about Italy. | chart-generation/charts/vaccines.py | adm_doses_italy | maldins46/CovidAnalysis | python | def adm_doses_italy(save_image=False, show=False):
'\n \n '
plt.bar(italy_df['data_somministrazione'], italy_df['prima_dose'], label='Prime dosi')
plt.bar(italy_df['data_somministrazione'], italy_df['seconda_dose'], bottom=italy_df['prima_dose'], label='Seconde dosi')
plt.title('Somministrazioni giornaliere Italia,\ncon distinzione prima dose/richiamo\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_italia.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() |
def adm_doses_marche(save_image=False, show=False):
'\n Administration data about Italy.\n '
plt.bar(marche_df['data_somministrazione'], marche_df['prima_dose'], label='Prime dosi')
plt.bar(marche_df['data_somministrazione'], marche_df['seconda_dose'], bottom=marche_df['prima_dose'], label='Seconde dosi')
plt.title('Somministrazioni giornaliere Marche,\ncon distinzione prima dose/richiamo\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_marche.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() | 4,750,569,846,045,732,000 | Administration data about Italy. | chart-generation/charts/vaccines.py | adm_doses_marche | maldins46/CovidAnalysis | python | def adm_doses_marche(save_image=False, show=False):
'\n \n '
plt.bar(marche_df['data_somministrazione'], marche_df['prima_dose'], label='Prime dosi')
plt.bar(marche_df['data_somministrazione'], marche_df['seconda_dose'], bottom=marche_df['prima_dose'], label='Seconde dosi')
plt.title('Somministrazioni giornaliere Marche,\ncon distinzione prima dose/richiamo\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_marche.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() |
def regional_doses(save_image=False, show=False):
'\n Comparation between doses administrated in various regions\n '
for (area_code, region_data) in benchmark_dict.items():
rolling_avg_adm = region_data['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(region_data['data_somministrazione'], rolling_avg_adm, label=area_names_dict[area_code])
rolling_avg_adm = italy_df['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(italy_df['data_somministrazione'], rolling_avg_adm, alpha=0.5, linestyle=':', label='Italia')
plt.title('Andamento delle somministrazioni giornaliere\nper 100.000 abitanti, confronto tra le regioni del benchmark\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_per_regioni.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() | 7,807,525,126,023,081,000 | Comparation between doses administrated in various regions | chart-generation/charts/vaccines.py | regional_doses | maldins46/CovidAnalysis | python | def regional_doses(save_image=False, show=False):
'\n \n '
for (area_code, region_data) in benchmark_dict.items():
rolling_avg_adm = region_data['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(region_data['data_somministrazione'], rolling_avg_adm, label=area_names_dict[area_code])
rolling_avg_adm = italy_df['totale_per_100000_ab'].rolling(7, center=True).mean()
plt.plot(italy_df['data_somministrazione'], rolling_avg_adm, alpha=0.5, linestyle=':', label='Italia')
plt.title('Andamento delle somministrazioni giornaliere\nper 100.000 abitanti, confronto tra le regioni del benchmark\n')
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/dosi_per_regioni.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() |
def immunes_percentage(save_image=False, show=False):
'\n Computes and plots relations between the population of a place and people that took the second shot.\n '
for (area_code, region_data) in benchmark_dict.items():
plt.plot(region_data['data_somministrazione'], region_data['seconda_dose_totale_storico_su_pop'], label=area_names_dict[area_code])
plt.plot(italy_df['data_somministrazione'], italy_df['seconda_dose_totale_storico_su_pop'], alpha=0.5, linestyle=':', label='Italia')
plt.title('Percentuale popolazione immunizzata,\nconfronto tra le regioni del benchmark\n')
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/immunizzati.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() | -1,740,053,331,135,391,200 | Computes and plots relations between the population of a place and people that took the second shot. | chart-generation/charts/vaccines.py | immunes_percentage | maldins46/CovidAnalysis | python | def immunes_percentage(save_image=False, show=False):
'\n \n '
for (area_code, region_data) in benchmark_dict.items():
plt.plot(region_data['data_somministrazione'], region_data['seconda_dose_totale_storico_su_pop'], label=area_names_dict[area_code])
plt.plot(italy_df['data_somministrazione'], italy_df['seconda_dose_totale_storico_su_pop'], alpha=0.5, linestyle=':', label='Italia')
plt.title('Percentuale popolazione immunizzata,\nconfronto tra le regioni del benchmark\n')
plt.gca().yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1))
plt.gca().xaxis.set_major_locator(MonthLocator())
plt.gca().xaxis.set_minor_locator(MonthLocator(bymonthday=15))
plt.gca().xaxis.set_major_formatter(utils.std_date_formatter)
plt.gca().xaxis.set_minor_formatter(utils.std_date_formatter)
plt.gcf().autofmt_xdate(which='both')
plt.grid(True, which='both', axis='both')
plt.legend(loc='upper left')
if save_image:
plt.savefig('./charts/vaccines/immunizzati.png', dpi=300, transparent=True, bbox_inches='tight')
if show:
plt.show()
plt.close() |
def getJsons(imgPath, maskPath, savePath, yamlPath=''):
'\n imgPath: origin image path \n\n maskPath : mask image path \n\n savePath : json file save path \n\n \n >>> getJsons(path-to-your-imgs,path-to-your-maskimgs,path-to-your-jsonfiles) \n\n '
logger.info('currently, only *.jpg supported')
if os.path.isfile(imgPath):
getMultiShapes.getMultiShapes(imgPath, maskPath, savePath, yamlPath)
elif os.path.isdir(imgPath):
oriImgs = glob.glob(((imgPath + os.sep) + '*.jpg'))
maskImgs = glob.glob(((maskPath + os.sep) + '*.jpg'))
for i in tqdm(oriImgs):
i_mask = i.replace(imgPath, maskPath)
if os.path.exists(i_mask):
getMultiShapes.getMultiShapes(i, i_mask, savePath, yamlPath)
else:
logger.warning('corresponding mask image not found!')
continue
else:
logger.error('input error. got [{},{},{},{}]. file maybe missing.'.format(imgPath, maskPath, savePath, yamlPath))
logger.info('Done! See here. {}'.format(savePath)) | 5,811,460,459,359,987,000 | imgPath: origin image path
maskPath : mask image path
savePath : json file save path
>>> getJsons(path-to-your-imgs,path-to-your-maskimgs,path-to-your-jsonfiles) | convertmask/utils/mask2json_script.py | getJsons | guchengxi1994/mask2json | python | def getJsons(imgPath, maskPath, savePath, yamlPath=):
'\n imgPath: origin image path \n\n maskPath : mask image path \n\n savePath : json file save path \n\n \n >>> getJsons(path-to-your-imgs,path-to-your-maskimgs,path-to-your-jsonfiles) \n\n '
logger.info('currently, only *.jpg supported')
if os.path.isfile(imgPath):
getMultiShapes.getMultiShapes(imgPath, maskPath, savePath, yamlPath)
elif os.path.isdir(imgPath):
oriImgs = glob.glob(((imgPath + os.sep) + '*.jpg'))
maskImgs = glob.glob(((maskPath + os.sep) + '*.jpg'))
for i in tqdm(oriImgs):
i_mask = i.replace(imgPath, maskPath)
if os.path.exists(i_mask):
getMultiShapes.getMultiShapes(i, i_mask, savePath, yamlPath)
else:
logger.warning('corresponding mask image not found!')
continue
else:
logger.error('input error. got [{},{},{},{}]. file maybe missing.'.format(imgPath, maskPath, savePath, yamlPath))
logger.info('Done! See here. {}'.format(savePath)) |
def create_vote(vote_dict, cutoff):
'\n changes the vote to the [-1, 1] range\n '
modified_vote = (1 if (float(vote_dict['vote']) > cutoff) else (- 1))
return Vote(user=str(vote_dict['user']), post=str(vote_dict['post']), vote=modified_vote) | -3,061,405,477,472,610,000 | changes the vote to the [-1, 1] range | kiwi-content/kiwi/TransferTypes.py | create_vote | bubblegumsoldier/kiwi | python | def create_vote(vote_dict, cutoff):
'\n \n '
modified_vote = (1 if (float(vote_dict['vote']) > cutoff) else (- 1))
return Vote(user=str(vote_dict['user']), post=str(vote_dict['post']), vote=modified_vote) |
def test_transcriptmapper_TranscriptMapper_LCE3C_uncertain(self):
'Use NM_178434.2 tests to test mapping with uncertain positions'
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('(152573138)'), 'r': parser.parse_r_interval('(1)'), 'c': parser.parse_c_interval('(-70)')}, {'g': parser.parse_g_interval('(152573138_152573139)'), 'r': parser.parse_r_interval('(1_2)'), 'c': parser.parse_c_interval('(-70_-69)')}]
self.run_cases(tm, test_cases) | -8,786,582,584,565,190,000 | Use NM_178434.2 tests to test mapping with uncertain positions | tests/test_hgvs_transcriptmapper.py | test_transcriptmapper_TranscriptMapper_LCE3C_uncertain | jmuhlich/hgvs | python | def test_transcriptmapper_TranscriptMapper_LCE3C_uncertain(self):
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('(152573138)'), 'r': parser.parse_r_interval('(1)'), 'c': parser.parse_c_interval('(-70)')}, {'g': parser.parse_g_interval('(152573138_152573139)'), 'r': parser.parse_r_interval('(1_2)'), 'c': parser.parse_c_interval('(-70_-69)')}]
self.run_cases(tm, test_cases) |
def test_transcriptmapper_TranscriptMapper_LCE3C(self):
'NM_178434.2: LCE3C single exon, strand = +1, all coordinate input/output are in HGVS'
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('152573138'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-70')}, {'g': parser.parse_g_interval('152573140'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-68')}, {'g': parser.parse_g_interval('152573207'), 'r': parser.parse_r_interval('70'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('152573208'), 'r': parser.parse_r_interval('71'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('152573492'), 'r': parser.parse_r_interval('355'), 'c': parser.parse_c_interval('285')}, {'g': parser.parse_g_interval('152573493'), 'r': parser.parse_r_interval('356'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('152573560'), 'r': parser.parse_r_interval('423'), 'c': parser.parse_c_interval('*68')}, {'g': parser.parse_g_interval('152573562'), 'r': parser.parse_r_interval('425'), 'c': parser.parse_c_interval('*70')}]
self.run_cases(tm, test_cases) | -2,397,615,263,211,383,000 | NM_178434.2: LCE3C single exon, strand = +1, all coordinate input/output are in HGVS | tests/test_hgvs_transcriptmapper.py | test_transcriptmapper_TranscriptMapper_LCE3C | jmuhlich/hgvs | python | def test_transcriptmapper_TranscriptMapper_LCE3C(self):
tx_ac = 'NM_178434.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('152573138'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-70')}, {'g': parser.parse_g_interval('152573140'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-68')}, {'g': parser.parse_g_interval('152573207'), 'r': parser.parse_r_interval('70'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('152573208'), 'r': parser.parse_r_interval('71'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('152573492'), 'r': parser.parse_r_interval('355'), 'c': parser.parse_c_interval('285')}, {'g': parser.parse_g_interval('152573493'), 'r': parser.parse_r_interval('356'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('152573560'), 'r': parser.parse_r_interval('423'), 'c': parser.parse_c_interval('*68')}, {'g': parser.parse_g_interval('152573562'), 'r': parser.parse_r_interval('425'), 'c': parser.parse_c_interval('*70')}]
self.run_cases(tm, test_cases) |
def test_transcriptmapper_TranscriptMapper_HIST3H2A(self):
'NM_033445.2: LCE3C single exon, strand = -1, all coordinate input/output are in HGVS'
tx_ac = 'NM_033445.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('228645560'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-42')}, {'g': parser.parse_g_interval('228645558'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-40')}, {'g': parser.parse_g_interval('228645519'), 'r': parser.parse_r_interval('42'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('228645518'), 'r': parser.parse_r_interval('43'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('228645126'), 'r': parser.parse_r_interval('435'), 'c': parser.parse_c_interval('393')}, {'g': parser.parse_g_interval('228645125'), 'r': parser.parse_r_interval('436'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('228645124'), 'r': parser.parse_r_interval('437'), 'c': parser.parse_c_interval('*2')}, {'g': parser.parse_g_interval('228645065'), 'r': parser.parse_r_interval('496'), 'c': parser.parse_c_interval('*61')}]
self.run_cases(tm, test_cases) | -7,917,196,163,994,230,000 | NM_033445.2: LCE3C single exon, strand = -1, all coordinate input/output are in HGVS | tests/test_hgvs_transcriptmapper.py | test_transcriptmapper_TranscriptMapper_HIST3H2A | jmuhlich/hgvs | python | def test_transcriptmapper_TranscriptMapper_HIST3H2A(self):
tx_ac = 'NM_033445.2'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('228645560'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-42')}, {'g': parser.parse_g_interval('228645558'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-40')}, {'g': parser.parse_g_interval('228645519'), 'r': parser.parse_r_interval('42'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('228645518'), 'r': parser.parse_r_interval('43'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('228645126'), 'r': parser.parse_r_interval('435'), 'c': parser.parse_c_interval('393')}, {'g': parser.parse_g_interval('228645125'), 'r': parser.parse_r_interval('436'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('228645124'), 'r': parser.parse_r_interval('437'), 'c': parser.parse_c_interval('*2')}, {'g': parser.parse_g_interval('228645065'), 'r': parser.parse_r_interval('496'), 'c': parser.parse_c_interval('*61')}]
self.run_cases(tm, test_cases) |
def test_transcriptmapper_TranscriptMapper_LCE2B(self):
'NM_014357.4: LCE2B, two exons, strand = +1, all coordinate input/output are in HGVS'
tx_ac = 'NM_014357.4'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('152658599'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-54')}, {'g': parser.parse_g_interval('152658601'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-52')}, {'g': parser.parse_g_interval('152659319'), 'r': parser.parse_r_interval('54'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('152659320'), 'r': parser.parse_r_interval('55'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('152658632'), 'r': parser.parse_r_interval('34'), 'c': parser.parse_c_interval('-21')}, {'g': parser.parse_g_interval('152658633'), 'r': parser.parse_r_interval('34+1'), 'c': parser.parse_c_interval('-21+1')}, {'g': parser.parse_g_interval('152658633_152659299'), 'r': parser.parse_r_interval('34+1_35-1'), 'c': parser.parse_c_interval('-21+1_-20-1')}, {'g': parser.parse_g_interval('152659300'), 'r': parser.parse_r_interval('35'), 'c': parser.parse_c_interval('-20')}, {'g': parser.parse_g_interval('152659299'), 'r': parser.parse_r_interval('35-1'), 'c': parser.parse_c_interval('-20-1')}, {'g': parser.parse_g_interval('152659652'), 'r': parser.parse_r_interval('387'), 'c': parser.parse_c_interval('333')}, {'g': parser.parse_g_interval('152659653'), 'r': parser.parse_r_interval('388'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('152659651_152659654'), 'r': parser.parse_r_interval('386_389'), 'c': parser.parse_c_interval('332_*2')}, {'g': parser.parse_g_interval('152659877'), 'r': parser.parse_r_interval('612'), 'c': parser.parse_c_interval('*225')}]
self.run_cases(tm, test_cases) | -9,154,633,420,330,855,000 | NM_014357.4: LCE2B, two exons, strand = +1, all coordinate input/output are in HGVS | tests/test_hgvs_transcriptmapper.py | test_transcriptmapper_TranscriptMapper_LCE2B | jmuhlich/hgvs | python | def test_transcriptmapper_TranscriptMapper_LCE2B(self):
tx_ac = 'NM_014357.4'
alt_ac = 'NC_000001.10'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('152658599'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-54')}, {'g': parser.parse_g_interval('152658601'), 'r': parser.parse_r_interval('3'), 'c': parser.parse_c_interval('-52')}, {'g': parser.parse_g_interval('152659319'), 'r': parser.parse_r_interval('54'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('152659320'), 'r': parser.parse_r_interval('55'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('152658632'), 'r': parser.parse_r_interval('34'), 'c': parser.parse_c_interval('-21')}, {'g': parser.parse_g_interval('152658633'), 'r': parser.parse_r_interval('34+1'), 'c': parser.parse_c_interval('-21+1')}, {'g': parser.parse_g_interval('152658633_152659299'), 'r': parser.parse_r_interval('34+1_35-1'), 'c': parser.parse_c_interval('-21+1_-20-1')}, {'g': parser.parse_g_interval('152659300'), 'r': parser.parse_r_interval('35'), 'c': parser.parse_c_interval('-20')}, {'g': parser.parse_g_interval('152659299'), 'r': parser.parse_r_interval('35-1'), 'c': parser.parse_c_interval('-20-1')}, {'g': parser.parse_g_interval('152659652'), 'r': parser.parse_r_interval('387'), 'c': parser.parse_c_interval('333')}, {'g': parser.parse_g_interval('152659653'), 'r': parser.parse_r_interval('388'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('152659651_152659654'), 'r': parser.parse_r_interval('386_389'), 'c': parser.parse_c_interval('332_*2')}, {'g': parser.parse_g_interval('152659877'), 'r': parser.parse_r_interval('612'), 'c': parser.parse_c_interval('*225')}]
self.run_cases(tm, test_cases) |
def test_transcriptmapper_TranscriptMapper_PTH2(self):
'NM_178449.3: PTH2, two exons, strand = -1, all coordinate input/output are in HGVS'
tx_ac = 'NM_178449.3'
alt_ac = 'NC_000019.9'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('49926698'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-102')}, {'g': parser.parse_g_interval('49926597'), 'r': parser.parse_r_interval('102'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('49926596'), 'r': parser.parse_r_interval('103'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('49926469'), 'r': parser.parse_r_interval('230'), 'c': parser.parse_c_interval('128')}, {'g': parser.parse_g_interval('49926468'), 'r': parser.parse_r_interval('230+1'), 'c': parser.parse_c_interval('128+1')}, {'g': parser.parse_g_interval('49925901_49926467'), 'r': parser.parse_r_interval('230+2_231-2'), 'c': parser.parse_c_interval('128+2_129-2')}, {'g': parser.parse_g_interval('49925900'), 'r': parser.parse_r_interval('231-1'), 'c': parser.parse_c_interval('129-1')}, {'g': parser.parse_g_interval('49925899'), 'r': parser.parse_r_interval('231'), 'c': parser.parse_c_interval('129')}, {'g': parser.parse_g_interval('49925725'), 'r': parser.parse_r_interval('405'), 'c': parser.parse_c_interval('303')}, {'g': parser.parse_g_interval('49925724'), 'r': parser.parse_r_interval('406'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('49925671'), 'r': parser.parse_r_interval('459'), 'c': parser.parse_c_interval('*54')}]
self.run_cases(tm, test_cases) | 3,569,334,816,543,326,700 | NM_178449.3: PTH2, two exons, strand = -1, all coordinate input/output are in HGVS | tests/test_hgvs_transcriptmapper.py | test_transcriptmapper_TranscriptMapper_PTH2 | jmuhlich/hgvs | python | def test_transcriptmapper_TranscriptMapper_PTH2(self):
tx_ac = 'NM_178449.3'
alt_ac = 'NC_000019.9'
tm = TranscriptMapper(self.hdp, tx_ac, alt_ac, alt_aln_method='splign')
parser = hgvs.parser.Parser()
test_cases = [{'g': parser.parse_g_interval('49926698'), 'r': parser.parse_r_interval('1'), 'c': parser.parse_c_interval('-102')}, {'g': parser.parse_g_interval('49926597'), 'r': parser.parse_r_interval('102'), 'c': parser.parse_c_interval('-1')}, {'g': parser.parse_g_interval('49926596'), 'r': parser.parse_r_interval('103'), 'c': parser.parse_c_interval('1')}, {'g': parser.parse_g_interval('49926469'), 'r': parser.parse_r_interval('230'), 'c': parser.parse_c_interval('128')}, {'g': parser.parse_g_interval('49926468'), 'r': parser.parse_r_interval('230+1'), 'c': parser.parse_c_interval('128+1')}, {'g': parser.parse_g_interval('49925901_49926467'), 'r': parser.parse_r_interval('230+2_231-2'), 'c': parser.parse_c_interval('128+2_129-2')}, {'g': parser.parse_g_interval('49925900'), 'r': parser.parse_r_interval('231-1'), 'c': parser.parse_c_interval('129-1')}, {'g': parser.parse_g_interval('49925899'), 'r': parser.parse_r_interval('231'), 'c': parser.parse_c_interval('129')}, {'g': parser.parse_g_interval('49925725'), 'r': parser.parse_r_interval('405'), 'c': parser.parse_c_interval('303')}, {'g': parser.parse_g_interval('49925724'), 'r': parser.parse_r_interval('406'), 'c': parser.parse_c_interval('*1')}, {'g': parser.parse_g_interval('49925671'), 'r': parser.parse_r_interval('459'), 'c': parser.parse_c_interval('*54')}]
self.run_cases(tm, test_cases) |
def setUp(self):
'\n Create two example sites that we can use to test what gets displayed\n where.\n '
super(SitesTest, self).setUp()
(self.site1, created1) = Site.objects.get_or_create(domain='example.com', name='example.com')
(self.site2, created2) = Site.objects.get_or_create(domain='example.org', name='example.org')
with self.settings(PHOTOLOGUE_MULTISITE=True):
self.gallery1 = GalleryFactory(slug='test-gallery', sites=[self.site1])
self.gallery2 = GalleryFactory(slug='not-on-site-gallery')
self.photo1 = PhotoFactory(slug='test-photo', sites=[self.site1])
self.photo2 = PhotoFactory(slug='not-on-site-photo')
self.gallery1.photos.add(self.photo1, self.photo2)
self.photo2.sites.clear() | -5,771,233,725,206,190,000 | Create two example sites that we can use to test what gets displayed
where. | photologue/tests/test_sites.py | setUp | elena/django-photologue | python | def setUp(self):
'\n Create two example sites that we can use to test what gets displayed\n where.\n '
super(SitesTest, self).setUp()
(self.site1, created1) = Site.objects.get_or_create(domain='example.com', name='example.com')
(self.site2, created2) = Site.objects.get_or_create(domain='example.org', name='example.org')
with self.settings(PHOTOLOGUE_MULTISITE=True):
self.gallery1 = GalleryFactory(slug='test-gallery', sites=[self.site1])
self.gallery2 = GalleryFactory(slug='not-on-site-gallery')
self.photo1 = PhotoFactory(slug='test-photo', sites=[self.site1])
self.photo2 = PhotoFactory(slug='not-on-site-photo')
self.gallery1.photos.add(self.photo1, self.photo2)
self.photo2.sites.clear() |
def test_basics(self):
' See if objects were added automatically (by the factory) to the current site. '
self.assertEqual(list(self.gallery1.sites.all()), [self.site1])
self.assertEqual(list(self.photo1.sites.all()), [self.site1]) | 5,815,624,118,007,133,000 | See if objects were added automatically (by the factory) to the current site. | photologue/tests/test_sites.py | test_basics | elena/django-photologue | python | def test_basics(self):
' '
self.assertEqual(list(self.gallery1.sites.all()), [self.site1])
self.assertEqual(list(self.photo1.sites.all()), [self.site1]) |
def test_auto_add_sites(self):
'\n Objects should not be automatically associated with a particular site when\n ``PHOTOLOGUE_MULTISITE`` is ``True``.\n '
with self.settings(PHOTOLOGUE_MULTISITE=False):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [self.site1])
self.assertEqual(list(photo.sites.all()), [self.site1])
photo.delete()
with self.settings(PHOTOLOGUE_MULTISITE=True):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [])
self.assertEqual(list(photo.sites.all()), [])
photo.delete() | 2,680,923,825,896,937,000 | Objects should not be automatically associated with a particular site when
``PHOTOLOGUE_MULTISITE`` is ``True``. | photologue/tests/test_sites.py | test_auto_add_sites | elena/django-photologue | python | def test_auto_add_sites(self):
'\n Objects should not be automatically associated with a particular site when\n ``PHOTOLOGUE_MULTISITE`` is ``True``.\n '
with self.settings(PHOTOLOGUE_MULTISITE=False):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [self.site1])
self.assertEqual(list(photo.sites.all()), [self.site1])
photo.delete()
with self.settings(PHOTOLOGUE_MULTISITE=True):
gallery = GalleryFactory()
photo = PhotoFactory()
self.assertEqual(list(gallery.sites.all()), [])
self.assertEqual(list(photo.sites.all()), [])
photo.delete() |
def test_photos_in_gallery(self):
'\n Only those photos are supposed to be shown in a gallery that are\n also associated with the current site.\n '
response = self.client.get('/ptests/gallery/test-gallery/')
self.assertEqual(list(response.context['object'].public()), [self.photo1]) | 1,634,909,017,167,998,000 | Only those photos are supposed to be shown in a gallery that are
also associated with the current site. | photologue/tests/test_sites.py | test_photos_in_gallery | elena/django-photologue | python | def test_photos_in_gallery(self):
'\n Only those photos are supposed to be shown in a gallery that are\n also associated with the current site.\n '
response = self.client.get('/ptests/gallery/test-gallery/')
self.assertEqual(list(response.context['object'].public()), [self.photo1]) |
@unittest.skipUnless(('django.contrib.sitemaps' in settings.INSTALLED_APPS), 'Sitemaps not installed in this project, nothing to test.')
def test_sitemap(self):
'A sitemap should only show objects associated with the current site.'
response = self.client.get('/sitemap.xml')
self.assertContains(response, '<url><loc>http://example.com/ptests/photo/test-photo/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response, '<url><loc>http://example.com/ptests/photo/not-on-site-photo/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertContains(response, '<url><loc>http://example.com/ptests/gallery/test-gallery/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response, '<url><loc>http://example.com/ptests/gallery/not-on-site-gallery/</loc><lastmod>2011-12-23</lastmod></url>') | -3,910,695,803,669,627,000 | A sitemap should only show objects associated with the current site. | photologue/tests/test_sites.py | test_sitemap | elena/django-photologue | python | @unittest.skipUnless(('django.contrib.sitemaps' in settings.INSTALLED_APPS), 'Sitemaps not installed in this project, nothing to test.')
def test_sitemap(self):
response = self.client.get('/sitemap.xml')
self.assertContains(response, '<url><loc>http://example.com/ptests/photo/test-photo/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response, '<url><loc>http://example.com/ptests/photo/not-on-site-photo/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertContains(response, '<url><loc>http://example.com/ptests/gallery/test-gallery/</loc><lastmod>2011-12-23</lastmod></url>')
self.assertNotContains(response, '<url><loc>http://example.com/ptests/gallery/not-on-site-gallery/</loc><lastmod>2011-12-23</lastmod></url>') |
def test_basic(self):
'Test decompose a single H into u2.\n '
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, 'u2') | -8,106,845,320,404,883,000 | Test decompose a single H into u2. | test/python/transpiler/test_decompose.py | test_basic | dominik-steenken/qiskit-terra | python | def test_basic(self):
'\n '
qr = QuantumRegister(1, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 1)
self.assertEqual(op_nodes[0].name, 'u2') |
def test_decompose_only_h(self):
'Test to decompose a single H, without the rest\n '
qr = QuantumRegister(2, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ['cx', 'u2']) | 6,406,512,899,642,825,000 | Test to decompose a single H, without the rest | test/python/transpiler/test_decompose.py | test_decompose_only_h | dominik-steenken/qiskit-terra | python | def test_decompose_only_h(self):
'\n '
qr = QuantumRegister(2, 'qr')
circuit = QuantumCircuit(qr)
circuit.h(qr[0])
circuit.cx(qr[0], qr[1])
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 2)
for node in op_nodes:
self.assertIn(node.name, ['cx', 'u2']) |
def test_decompose_toffoli(self):
'Test decompose CCX.\n '
qr1 = QuantumRegister(2, 'qr1')
qr2 = QuantumRegister(1, 'qr2')
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(ToffoliGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ['h', 't', 'tdg', 'cx']) | 4,077,511,452,411,139,000 | Test decompose CCX. | test/python/transpiler/test_decompose.py | test_decompose_toffoli | dominik-steenken/qiskit-terra | python | def test_decompose_toffoli(self):
'\n '
qr1 = QuantumRegister(2, 'qr1')
qr2 = QuantumRegister(1, 'qr2')
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Decompose(ToffoliGate)
after_dag = pass_.run(dag)
op_nodes = after_dag.op_nodes()
self.assertEqual(len(op_nodes), 15)
for node in op_nodes:
self.assertIn(node.name, ['h', 't', 'tdg', 'cx']) |
def test_decompose_conditional(self):
'Test decompose a 1-qubit gates with a conditional.\n '
qr = QuantumRegister(1, 'qr')
cr = ClassicalRegister(1, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.u2(0, pi, qr[0]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag) | 8,697,716,771,767,612,000 | Test decompose a 1-qubit gates with a conditional. | test/python/transpiler/test_decompose.py | test_decompose_conditional | dominik-steenken/qiskit-terra | python | def test_decompose_conditional(self):
'\n '
qr = QuantumRegister(1, 'qr')
cr = ClassicalRegister(1, 'cr')
circuit = QuantumCircuit(qr, cr)
circuit.h(qr).c_if(cr, 1)
circuit.x(qr).c_if(cr, 1)
dag = circuit_to_dag(circuit)
pass_ = Decompose(HGate)
after_dag = pass_.run(dag)
ref_circuit = QuantumCircuit(qr, cr)
ref_circuit.u2(0, pi, qr[0]).c_if(cr, 1)
ref_circuit.x(qr).c_if(cr, 1)
ref_dag = circuit_to_dag(ref_circuit)
self.assertEqual(after_dag, ref_dag) |
def get_nodes(self, gid, sid, did, scid, doid):
'\n Generate the Check Constraint collection node.\n '
(yield self.generate_browser_collection_node(doid)) | -2,100,387,297,712,318,200 | Generate the Check Constraint collection node. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | get_nodes | jhkuang11/UniTrade | python | def get_nodes(self, gid, sid, did, scid, doid):
'\n \n '
(yield self.generate_browser_collection_node(doid)) |
@property
def node_inode(self):
'\n Returns Check Constraint node as leaf node.\n '
return False | 2,246,541,425,044,905,200 | Returns Check Constraint node as leaf node. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | node_inode | jhkuang11/UniTrade | python | @property
def node_inode(self):
'\n \n '
return False |
@property
def script_load(self):
'\n Load the module script for the Check Constraint, when any of the\n Check node is initialized.\n '
return database.DatabaseModule.NODE_TYPE | -1,586,024,280,889,844,000 | Load the module script for the Check Constraint, when any of the
Check node is initialized. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | script_load | jhkuang11/UniTrade | python | @property
def script_load(self):
'\n Load the module script for the Check Constraint, when any of the\n Check node is initialized.\n '
return database.DatabaseModule.NODE_TYPE |
@property
def module_use_template_javascript(self):
'\n Returns whether Jinja2 template is used for generating the javascript\n module.\n '
return False | 6,463,411,142,113,810,000 | Returns whether Jinja2 template is used for generating the javascript
module. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | module_use_template_javascript | jhkuang11/UniTrade | python | @property
def module_use_template_javascript(self):
'\n Returns whether Jinja2 template is used for generating the javascript\n module.\n '
return False |
@property
def csssnippets(self):
'\n Returns a snippet of css to include in the page\n '
return [render_template('check_constraint/css/check_constraint.css', node_type=self.node_type)] | 2,008,301,717,462,353,000 | Returns a snippet of css to include in the page | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | csssnippets | jhkuang11/UniTrade | python | @property
def csssnippets(self):
'\n \n '
return [render_template('check_constraint/css/check_constraint.css', node_type=self.node_type)] |
def module_js(self):
'\n Load JS file (check_constraint.js) for this module.\n '
return make_response(render_template('check_constraint/js/check_constraint.js', _=_), 200, {'Content-Type': 'application/x-javascript'}) | -8,185,117,777,359,820,000 | Load JS file (check_constraint.js) for this module. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | module_js | jhkuang11/UniTrade | python | def module_js(self):
'\n \n '
return make_response(render_template('check_constraint/js/check_constraint.js', _=_), 200, {'Content-Type': 'application/x-javascript'}) |
def check_precondition(f):
'\n Works as a decorator.\n Checks database connection status.\n Attach connection object and template path.\n '
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=kwargs['tid'])
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
return f(*args, **kwargs)
return wrap | -1,662,070,888,570,002,400 | Works as a decorator.
Checks database connection status.
Attach connection object and template path. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | check_precondition | jhkuang11/UniTrade | python | def check_precondition(f):
'\n Works as a decorator.\n Checks database connection status.\n Attach connection object and template path.\n '
@wraps(f)
def wrap(*args, **kwargs):
self = args[0]
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(kwargs['sid'])
self.conn = self.manager.connection(did=kwargs['did'])
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=kwargs['tid'])
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
return f(*args, **kwargs)
return wrap |
def end_transaction(self):
'\n End database transaction.\n Returns:\n\n '
SQL = 'END;'
self.conn.execute_scalar(SQL) | -6,065,021,381,072,232,000 | End database transaction.
Returns: | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | end_transaction | jhkuang11/UniTrade | python | def end_transaction(self):
'\n End database transaction.\n Returns:\n\n '
SQL = 'END;'
self.conn.execute_scalar(SQL) |
@check_precondition
def list(self, gid, sid, did, scid, tid, cid=None):
'\n List the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Id\n '
try:
res = self.get_node_list(gid, sid, did, scid, tid, cid)
return ajax_response(response=res, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e)) | 3,641,996,271,668,683,300 | List the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | list | jhkuang11/UniTrade | python | @check_precondition
def list(self, gid, sid, did, scid, tid, cid=None):
'\n List the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Id\n '
try:
res = self.get_node_list(gid, sid, did, scid, tid, cid)
return ajax_response(response=res, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e)) |
def get_node_list(self, gid, sid, did, scid, tid, cid=None):
'\n This function returns all check constraints\n nodes within that collection as a list.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Cehck constraint ID\n\n Returns:\n\n '
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid)
(status, res) = self.conn.execute_dict(SQL)
return res['rows'] | -901,582,869,631,029,800 | This function returns all check constraints
nodes within that collection as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Cehck constraint ID
Returns: | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | get_node_list | jhkuang11/UniTrade | python | def get_node_list(self, gid, sid, did, scid, tid, cid=None):
'\n This function returns all check constraints\n nodes within that collection as a list.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Cehck constraint ID\n\n Returns:\n\n '
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid)
(status, res) = self.conn.execute_dict(SQL)
return res['rows'] |
@check_precondition
def node(self, gid, sid, did, scid, tid, cid):
'\n Returns all the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check constraint Id.\n '
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), cid=cid)
(status, rset) = self.conn.execute_2darray(SQL)
if (len(rset['rows']) == 0):
return gone(_('Could not find the check constraint.'))
if (('convalidated' in rset['rows'][0]) and rset['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res = self.blueprint.generate_browser_node(rset['rows'][0]['oid'], tid, rset['rows'][0]['name'], icon=icon, valid=valid)
return make_json_response(data=res, status=200) | -8,474,499,497,717,976,000 | Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | node | jhkuang11/UniTrade | python | @check_precondition
def node(self, gid, sid, did, scid, tid, cid):
'\n Returns all the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check constraint Id.\n '
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), cid=cid)
(status, rset) = self.conn.execute_2darray(SQL)
if (len(rset['rows']) == 0):
return gone(_('Could not find the check constraint.'))
if (('convalidated' in rset['rows'][0]) and rset['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res = self.blueprint.generate_browser_node(rset['rows'][0]['oid'], tid, rset['rows'][0]['name'], icon=icon, valid=valid)
return make_json_response(data=res, status=200) |
@check_precondition
def nodes(self, gid, sid, did, scid, tid):
'\n Returns all the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check constraint Id.\n '
res = []
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if (('convalidated' in row) and row['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res.append(self.blueprint.generate_browser_node(row['oid'], tid, row['name'], icon=icon, valid=valid))
return make_json_response(data=res, status=200) | -2,540,133,028,761,386,000 | Returns all the Check Constraints.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check constraint Id. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | nodes | jhkuang11/UniTrade | python | @check_precondition
def nodes(self, gid, sid, did, scid, tid):
'\n Returns all the Check Constraints.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check constraint Id.\n '
res = []
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if (('convalidated' in row) and row['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res.append(self.blueprint.generate_browser_node(row['oid'], tid, row['name'], icon=icon, valid=valid))
return make_json_response(data=res, status=200) |
def get_nodes(self, gid, sid, did, scid, tid, cid=None):
'\n This function returns all event check constraint as a list.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Check constraint ID\n\n Returns:\n\n '
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
res = []
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if (('convalidated' in row) and row['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res.append(self.blueprint.generate_browser_node(row['oid'], tid, row['name'], icon=icon, valid=valid))
return res | 5,346,953,289,429,174,000 | This function returns all event check constraint as a list.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns: | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | get_nodes | jhkuang11/UniTrade | python | def get_nodes(self, gid, sid, did, scid, tid, cid=None):
'\n This function returns all event check constraint as a list.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Check constraint ID\n\n Returns:\n\n '
driver = get_driver(PG_DEFAULT_DRIVER)
self.manager = driver.connection_manager(sid)
self.conn = self.manager.connection(did=did)
self.qtIdent = driver.qtIdent
self.template_path = 'check_constraint/sql/#{0}#'.format(self.manager.version)
SQL = render_template('/'.join([self.template_path, 'get_parent.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
if (not status):
return internal_server_error(errormsg=rset)
self.schema = rset['rows'][0]['schema']
self.table = rset['rows'][0]['table']
res = []
SQL = render_template('/'.join([self.template_path, 'nodes.sql']), tid=tid)
(status, rset) = self.conn.execute_2darray(SQL)
for row in rset['rows']:
if (('convalidated' in row) and row['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
res.append(self.blueprint.generate_browser_node(row['oid'], tid, row['name'], icon=icon, valid=valid))
return res |
@check_precondition
def properties(self, gid, sid, did, scid, tid, cid):
'\n Returns the Check Constraints property.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Check Id\n cid: Check Constraint Id\n '
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(_('Could not find the object on the server.'))
data = res['rows'][0]
return ajax_response(response=data, status=200) | -8,792,875,693,216,955,000 | Returns the Check Constraints property.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | properties | jhkuang11/UniTrade | python | @check_precondition
def properties(self, gid, sid, did, scid, tid, cid):
'\n Returns the Check Constraints property.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Check Id\n cid: Check Constraint Id\n '
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(_('Could not find the object on the server.'))
data = res['rows'][0]
return ajax_response(response=data, status=200) |
@check_precondition
def create(self, gid, sid, did, scid, tid, cid=None):
'\n This function will create a primary key.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Check constraint ID\n\n Returns:\n\n '
required_args = ['consrc']
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
for (k, v) in data.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except (ValueError, TypeError, KeyError):
data[k] = v
for arg in required_args:
if ((arg not in data) or (data[arg] == '')):
return make_json_response(status=400, success=0, errormsg=_(('Could not find the required parameter (%s).' % arg)))
data['schema'] = self.schema
data['table'] = self.table
try:
if (('name' not in data) or (data['name'] == '')):
SQL = 'BEGIN;'
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
(status, msg) = self.conn.execute_scalar(SQL)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=msg)
if (('name' not in data) or (data['name'] == '')):
sql = render_template('/'.join([self.template_path, 'get_oid_with_transaction.sql']), tid=tid)
(status, res) = self.conn.execute_dict(sql)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
self.end_transaction()
data['name'] = res['rows'][0]['name']
else:
sql = render_template('/'.join([self.template_path, 'get_oid.sql']), tid=tid, name=data['name'])
(status, res) = self.conn.execute_dict(sql)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
if (('convalidated' in res['rows'][0]) and res['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
return jsonify(node=self.blueprint.generate_browser_node(res['rows'][0]['oid'], tid, data['name'], icon=icon, valid=valid))
except Exception as e:
self.end_transaction()
return make_json_response(status=400, success=0, errormsg=e) | -8,490,392,163,302,637,000 | This function will create a primary key.
Args:
gid: Server Group ID
sid: Server ID
did: Database ID
scid: Schema ID
tid: Table ID
cid: Check constraint ID
Returns: | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | create | jhkuang11/UniTrade | python | @check_precondition
def create(self, gid, sid, did, scid, tid, cid=None):
'\n This function will create a primary key.\n\n Args:\n gid: Server Group ID\n sid: Server ID\n did: Database ID\n scid: Schema ID\n tid: Table ID\n cid: Check constraint ID\n\n Returns:\n\n '
required_args = ['consrc']
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
for (k, v) in data.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except (ValueError, TypeError, KeyError):
data[k] = v
for arg in required_args:
if ((arg not in data) or (data[arg] == )):
return make_json_response(status=400, success=0, errormsg=_(('Could not find the required parameter (%s).' % arg)))
data['schema'] = self.schema
data['table'] = self.table
try:
if (('name' not in data) or (data['name'] == )):
SQL = 'BEGIN;'
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
(status, msg) = self.conn.execute_scalar(SQL)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=msg)
if (('name' not in data) or (data['name'] == )):
sql = render_template('/'.join([self.template_path, 'get_oid_with_transaction.sql']), tid=tid)
(status, res) = self.conn.execute_dict(sql)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
self.end_transaction()
data['name'] = res['rows'][0]['name']
else:
sql = render_template('/'.join([self.template_path, 'get_oid.sql']), tid=tid, name=data['name'])
(status, res) = self.conn.execute_dict(sql)
if (not status):
self.end_transaction()
return internal_server_error(errormsg=res)
if (('convalidated' in res['rows'][0]) and res['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
return jsonify(node=self.blueprint.generate_browser_node(res['rows'][0]['oid'], tid, data['name'], icon=icon, valid=valid))
except Exception as e:
self.end_transaction()
return make_json_response(status=400, success=0, errormsg=e) |
@check_precondition
def delete(self, gid, sid, did, scid, tid, cid):
'\n Drops the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Check Id\n cid: Check Constraint Id\n '
try:
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (not res['rows']):
return make_json_response(success=0, errormsg=_('Error: Object not found.'), info=_('The specified check constraint could not be found.\n'))
data = res['rows'][0]
SQL = render_template('/'.join([self.template_path, 'delete.sql']), data=data)
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=_('Check Constraint dropped.'), data={'id': tid, 'scid': scid, 'sid': sid, 'gid': gid, 'did': did})
except Exception as e:
return internal_server_error(errormsg=str(e)) | -1,481,032,813,985,460,000 | Drops the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Check Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | delete | jhkuang11/UniTrade | python | @check_precondition
def delete(self, gid, sid, did, scid, tid, cid):
'\n Drops the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Check Id\n cid: Check Constraint Id\n '
try:
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (not res['rows']):
return make_json_response(success=0, errormsg=_('Error: Object not found.'), info=_('The specified check constraint could not be found.\n'))
data = res['rows'][0]
SQL = render_template('/'.join([self.template_path, 'delete.sql']), data=data)
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=_('Check Constraint dropped.'), data={'id': tid, 'scid': scid, 'sid': sid, 'gid': gid, 'did': did})
except Exception as e:
return internal_server_error(errormsg=str(e)) |
@check_precondition
def update(self, gid, sid, did, scid, tid, cid):
'\n Updates the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
try:
data['schema'] = self.schema
data['table'] = self.table
(SQL, name) = self.get_sql(gid, sid, data, scid, tid, cid)
if (not SQL):
return name
SQL = SQL.strip('\n').strip(' ')
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
return internal_server_error(errormsg=res)
sql = render_template('/'.join([self.template_path, 'get_name.sql']), cid=cid)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (('convalidated' in res['rows'][0]) and res['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
return jsonify(node=self.blueprint.generate_browser_node(cid, tid, name, icon=icon, valid=valid))
except Exception as e:
return internal_server_error(errormsg=str(e)) | 2,486,437,542,261,388,300 | Updates the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | update | jhkuang11/UniTrade | python | @check_precondition
def update(self, gid, sid, did, scid, tid, cid):
'\n Updates the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
data = (request.form if request.form else json.loads(request.data, encoding='utf-8'))
try:
data['schema'] = self.schema
data['table'] = self.table
(SQL, name) = self.get_sql(gid, sid, data, scid, tid, cid)
if (not SQL):
return name
SQL = SQL.strip('\n').strip(' ')
(status, res) = self.conn.execute_scalar(SQL)
if (not status):
return internal_server_error(errormsg=res)
sql = render_template('/'.join([self.template_path, 'get_name.sql']), cid=cid)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
if (('convalidated' in res['rows'][0]) and res['rows'][0]['convalidated']):
icon = 'icon-check_constraints_bad'
valid = False
else:
icon = 'icon-check_constraints'
valid = True
return jsonify(node=self.blueprint.generate_browser_node(cid, tid, name, icon=icon, valid=valid))
except Exception as e:
return internal_server_error(errormsg=str(e)) |
@check_precondition
def sql(self, gid, sid, did, scid, tid, cid=None):
'\n Returns the SQL for the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(_('Could not find the object on the server.'))
data = res['rows'][0]
data['schema'] = self.schema
data['table'] = self.table
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
sql_header = u'-- Constraint: {0}\n\n-- '.format(data['name'])
sql_header += render_template('/'.join([self.template_path, 'delete.sql']), data=data)
sql_header += '\n'
SQL = (sql_header + SQL)
return ajax_response(response=SQL) | -2,459,164,446,102,590,000 | Returns the SQL for the Check Constraint object.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | sql | jhkuang11/UniTrade | python | @check_precondition
def sql(self, gid, sid, did, scid, tid, cid=None):
'\n Returns the SQL for the Check Constraint object.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return internal_server_error(errormsg=res)
if (len(res['rows']) == 0):
return gone(_('Could not find the object on the server.'))
data = res['rows'][0]
data['schema'] = self.schema
data['table'] = self.table
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
sql_header = u'-- Constraint: {0}\n\n-- '.format(data['name'])
sql_header += render_template('/'.join([self.template_path, 'delete.sql']), data=data)
sql_header += '\n'
SQL = (sql_header + SQL)
return ajax_response(response=SQL) |
@check_precondition
def msql(self, gid, sid, did, scid, tid, cid=None):
'\n Returns the modified SQL.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n\n Returns:\n Check Constraint object in json format.\n '
data = {}
for (k, v) in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
data['schema'] = self.schema
data['table'] = self.table
try:
(sql, name) = self.get_sql(gid, sid, data, scid, tid, cid)
if (not sql):
return name
sql = sql.strip('\n').strip(' ')
if (sql == ''):
sql = '--modified SQL'
return make_json_response(data=sql, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e)) | -8,169,333,509,492,578,000 | Returns the modified SQL.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns:
Check Constraint object in json format. | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | msql | jhkuang11/UniTrade | python | @check_precondition
def msql(self, gid, sid, did, scid, tid, cid=None):
'\n Returns the modified SQL.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n\n Returns:\n Check Constraint object in json format.\n '
data = {}
for (k, v) in request.args.items():
try:
data[k] = json.loads(v, encoding='utf-8')
except ValueError:
data[k] = v
data['schema'] = self.schema
data['table'] = self.table
try:
(sql, name) = self.get_sql(gid, sid, data, scid, tid, cid)
if (not sql):
return name
sql = sql.strip('\n').strip(' ')
if (sql == ):
sql = '--modified SQL'
return make_json_response(data=sql, status=200)
except Exception as e:
return internal_server_error(errormsg=str(e)) |
def get_sql(self, gid, sid, data, scid, tid, cid=None):
'\n Generates the SQL statements to create/update the Check Constraint.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
if (cid is not None):
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return (False, internal_server_error(errormsg=res))
if (len(res['rows']) == 0):
return (False, gone(_('Could not find the object on the server.')))
old_data = res['rows'][0]
required_args = ['name']
for arg in required_args:
if (arg not in data):
data[arg] = old_data[arg]
SQL = render_template('/'.join([self.template_path, 'update.sql']), data=data, o_data=old_data, conn=self.conn)
else:
required_args = ['consrc']
for arg in required_args:
if (arg not in data):
return _('-- definition incomplete')
elif (isinstance(data[arg], list) and (len(data[arg]) < 1)):
return _('-- definition incomplete')
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
return (SQL, (data['name'] if ('name' in data) else old_data['name'])) | 7,280,083,442,559,355,000 | Generates the SQL statements to create/update the Check Constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | get_sql | jhkuang11/UniTrade | python | def get_sql(self, gid, sid, data, scid, tid, cid=None):
'\n Generates the SQL statements to create/update the Check Constraint.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
if (cid is not None):
SQL = render_template('/'.join([self.template_path, 'properties.sql']), tid=tid, cid=cid)
(status, res) = self.conn.execute_dict(SQL)
if (not status):
return (False, internal_server_error(errormsg=res))
if (len(res['rows']) == 0):
return (False, gone(_('Could not find the object on the server.')))
old_data = res['rows'][0]
required_args = ['name']
for arg in required_args:
if (arg not in data):
data[arg] = old_data[arg]
SQL = render_template('/'.join([self.template_path, 'update.sql']), data=data, o_data=old_data, conn=self.conn)
else:
required_args = ['consrc']
for arg in required_args:
if (arg not in data):
return _('-- definition incomplete')
elif (isinstance(data[arg], list) and (len(data[arg]) < 1)):
return _('-- definition incomplete')
SQL = render_template('/'.join([self.template_path, 'create.sql']), data=data)
return (SQL, (data['name'] if ('name' in data) else old_data['name'])) |
@check_precondition
def dependents(self, gid, sid, did, scid, tid, cid):
'\n This function get the dependents and return ajax response\n for the Check Constraint node.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
dependents_result = self.get_dependents(self.conn, cid)
return ajax_response(response=dependents_result, status=200) | 8,944,948,045,789,013,000 | This function get the dependents and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | dependents | jhkuang11/UniTrade | python | @check_precondition
def dependents(self, gid, sid, did, scid, tid, cid):
'\n This function get the dependents and return ajax response\n for the Check Constraint node.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
dependents_result = self.get_dependents(self.conn, cid)
return ajax_response(response=dependents_result, status=200) |
@check_precondition
def dependencies(self, gid, sid, did, scid, tid, cid):
'\n This function get the dependencies and return ajax response\n for the Check Constraint node.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
dependencies_result = self.get_dependencies(self.conn, cid)
return ajax_response(response=dependencies_result, status=200) | 1,714,487,567,196,472,300 | This function get the dependencies and return ajax response
for the Check Constraint node.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | dependencies | jhkuang11/UniTrade | python | @check_precondition
def dependencies(self, gid, sid, did, scid, tid, cid):
'\n This function get the dependencies and return ajax response\n for the Check Constraint node.\n\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n '
dependencies_result = self.get_dependencies(self.conn, cid)
return ajax_response(response=dependencies_result, status=200) |
@check_precondition
def validate_check_constraint(self, gid, sid, did, scid, tid, cid):
'\n Validate check constraint.\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n\n Returns:\n\n '
data = {}
try:
data['schema'] = self.schema
data['table'] = self.table
sql = render_template('/'.join([self.template_path, 'get_name.sql']), cid=cid)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
data['name'] = res
sql = render_template('/'.join([self.template_path, 'validate.sql']), data=data)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=_('Check constraint updated.'), data={'id': cid, 'tid': tid, 'scid': scid, 'did': did})
except Exception as e:
return internal_server_error(errormsg=str(e)) | -5,572,943,996,713,023,000 | Validate check constraint.
Args:
gid: Server Group Id
sid: Server Id
did: Database Id
scid: Schema Id
tid: Table Id
cid: Check Constraint Id
Returns: | code/venv/lib/python3.6/site-packages/pgadmin4/pgadmin/browser/server_groups/servers/databases/schemas/tables/constraints/check_constraint/__init__.py | validate_check_constraint | jhkuang11/UniTrade | python | @check_precondition
def validate_check_constraint(self, gid, sid, did, scid, tid, cid):
'\n Validate check constraint.\n Args:\n gid: Server Group Id\n sid: Server Id\n did: Database Id\n scid: Schema Id\n tid: Table Id\n cid: Check Constraint Id\n\n Returns:\n\n '
data = {}
try:
data['schema'] = self.schema
data['table'] = self.table
sql = render_template('/'.join([self.template_path, 'get_name.sql']), cid=cid)
(status, res) = self.conn.execute_scalar(sql)
if (not status):
return internal_server_error(errormsg=res)
data['name'] = res
sql = render_template('/'.join([self.template_path, 'validate.sql']), data=data)
(status, res) = self.conn.execute_dict(sql)
if (not status):
return internal_server_error(errormsg=res)
return make_json_response(success=1, info=_('Check constraint updated.'), data={'id': cid, 'tid': tid, 'scid': scid, 'did': did})
except Exception as e:
return internal_server_error(errormsg=str(e)) |
@pytest.fixture
def add_network(host):
'Adds a network to the stacki db. For historical reasons the first test network this creates is pxe=False.'
def _inner(name, address, pxe=False):
result = host.run(f'stack add network {name} address={address} mask=255.255.255.0 pxe={pxe}')
if (result.rc != 0):
pytest.fail(f'unable to add dummy network "{name}"')
_inner('test', '192.168.0.0')
return _inner | 8,484,405,872,898,039,000 | Adds a network to the stacki db. For historical reasons the first test network this creates is pxe=False. | test-framework/test-suites/integration/tests/fixtures/add_data.py | add_network | anooprajendra/stacki | python | @pytest.fixture
def add_network(host):
def _inner(name, address, pxe=False):
result = host.run(f'stack add network {name} address={address} mask=255.255.255.0 pxe={pxe}')
if (result.rc != 0):
pytest.fail(f'unable to add dummy network "{name}"')
_inner('test', '192.168.0.0')
return _inner |
@pytest.fixture
def add_host_with_net(host, add_host_with_interface, add_network):
'Adds a host with a network. The first network this adds defaults to pxe=True.'
def _inner(hostname, rack, rank, appliance, interface, ip, network, address, pxe):
add_host_with_interface(hostname=hostname, rack=rack, rank=rank, appliance=appliance, interface=interface)
add_network(name=network, address=address, pxe=pxe)
result = host.run(f'stack set host interface network {hostname} network={network} interface={interface}')
assert (result.rc == 0)
result = host.run(f'stack set host interface ip {hostname} ip={ip} network={network}')
assert (result.rc == 0)
result = host.run('stack list host interface a:frontend output-format=json')
assert (result.rc == 0)
interface_on_network = False
for frontend_interface in json.loads(result.stdout):
if (frontend_interface['network'] == network):
interface_on_network = True
break
if interface_on_network:
return
latest_interface = max((frontend_interface['interface'] for frontend_interface in json.loads(result.stdout)))
new_interface = list(latest_interface)
new_interface[(- 1)] = str((int(new_interface[(- 1)]) + 1))
new_interface = ''.join(new_interface)
result = host.run(f'stack add host interface a:frontend interface={new_interface} network={network} ip={(ipaddress.ip_address(ip) + 1)}')
assert (result.rc == 0)
result = host.run(f'stack remove network test')
assert (result.rc == 0)
add_network(name='test', address='192.168.0.0', pxe=True)
result = host.run(f'stack set host interface network backend-0-0 network=test interface=eth0 ip=192.168.0.3')
assert (result.rc == 0)
result = host.run(f'stack add host interface a:frontend interface=eth2 network=test ip=192.168.0.2')
assert (result.rc == 0)
return _inner | -5,918,668,350,231,279,000 | Adds a host with a network. The first network this adds defaults to pxe=True. | test-framework/test-suites/integration/tests/fixtures/add_data.py | add_host_with_net | anooprajendra/stacki | python | @pytest.fixture
def add_host_with_net(host, add_host_with_interface, add_network):
def _inner(hostname, rack, rank, appliance, interface, ip, network, address, pxe):
add_host_with_interface(hostname=hostname, rack=rack, rank=rank, appliance=appliance, interface=interface)
add_network(name=network, address=address, pxe=pxe)
result = host.run(f'stack set host interface network {hostname} network={network} interface={interface}')
assert (result.rc == 0)
result = host.run(f'stack set host interface ip {hostname} ip={ip} network={network}')
assert (result.rc == 0)
result = host.run('stack list host interface a:frontend output-format=json')
assert (result.rc == 0)
interface_on_network = False
for frontend_interface in json.loads(result.stdout):
if (frontend_interface['network'] == network):
interface_on_network = True
break
if interface_on_network:
return
latest_interface = max((frontend_interface['interface'] for frontend_interface in json.loads(result.stdout)))
new_interface = list(latest_interface)
new_interface[(- 1)] = str((int(new_interface[(- 1)]) + 1))
new_interface = .join(new_interface)
result = host.run(f'stack add host interface a:frontend interface={new_interface} network={network} ip={(ipaddress.ip_address(ip) + 1)}')
assert (result.rc == 0)
result = host.run(f'stack remove network test')
assert (result.rc == 0)
add_network(name='test', address='192.168.0.0', pxe=True)
result = host.run(f'stack set host interface network backend-0-0 network=test interface=eth0 ip=192.168.0.3')
assert (result.rc == 0)
result = host.run(f'stack add host interface a:frontend interface=eth2 network=test ip=192.168.0.2')
assert (result.rc == 0)
return _inner |
@pytest.fixture(params=(('', 'exec=True'), ('', '| bash -x'), ('document=', 'exec=True'), ('document=', '| bash -x')), ids=('stack_load_exec', 'stack_load_bash', 'stack_load_document_exec', 'stack_load_document_bash'))
def stack_load(request, host):
'This fixture is used to run `stack load` on the host during integration tests.\n\n\tThere are 4 essentially equivalent ways of loading and running a dump.json. Using\n\tthis test fixture ensures that all 4 are tested. I.E:\n\n\tstack load dump_file exec=True\n\tstack load document=dump_file exec=True\n\tstack load dump_file | bash -x\n\tstack load document=dump_file | bash -x\n\t'
(param_string, exec_string) = request.param
def _load(dump_file, **kwargs):
if ('exec' in kwargs):
raise ValueError('Cannot pass exec param to this fixture. It handles it for you.')
if ('document' in kwargs):
raise ValueError('Cannot pass document param to this fixture. It handles it for you.')
kwargs_string = ' '.join((f'{key}={value}' for (key, value) in kwargs.items()))
return host.run(f'stack load {param_string}{dump_file} {exec_string} {kwargs_string}')
return _load | -8,641,065,466,918,791,000 | This fixture is used to run `stack load` on the host during integration tests.
There are 4 essentially equivalent ways of loading and running a dump.json. Using
this test fixture ensures that all 4 are tested. I.E:
stack load dump_file exec=True
stack load document=dump_file exec=True
stack load dump_file | bash -x
stack load document=dump_file | bash -x | test-framework/test-suites/integration/tests/fixtures/add_data.py | stack_load | anooprajendra/stacki | python | @pytest.fixture(params=((, 'exec=True'), (, '| bash -x'), ('document=', 'exec=True'), ('document=', '| bash -x')), ids=('stack_load_exec', 'stack_load_bash', 'stack_load_document_exec', 'stack_load_document_bash'))
def stack_load(request, host):
'This fixture is used to run `stack load` on the host during integration tests.\n\n\tThere are 4 essentially equivalent ways of loading and running a dump.json. Using\n\tthis test fixture ensures that all 4 are tested. I.E:\n\n\tstack load dump_file exec=True\n\tstack load document=dump_file exec=True\n\tstack load dump_file | bash -x\n\tstack load document=dump_file | bash -x\n\t'
(param_string, exec_string) = request.param
def _load(dump_file, **kwargs):
if ('exec' in kwargs):
raise ValueError('Cannot pass exec param to this fixture. It handles it for you.')
if ('document' in kwargs):
raise ValueError('Cannot pass document param to this fixture. It handles it for you.')
kwargs_string = ' '.join((f'{key}={value}' for (key, value) in kwargs.items()))
return host.run(f'stack load {param_string}{dump_file} {exec_string} {kwargs_string}')
return _load |
@pytest.fixture
def fake_local_firmware_file(tmp_path_factory):
'Creates a fake local firmware file and returns a pathlib.Path object that points to it.'
fake_firmware_file = (tmp_path_factory.mktemp('fake_firmware') / 'foo.img')
fake_firmware_file.write_text('foofakefirmware')
return fake_firmware_file | 8,963,504,310,616,549,000 | Creates a fake local firmware file and returns a pathlib.Path object that points to it. | test-framework/test-suites/integration/tests/fixtures/add_data.py | fake_local_firmware_file | anooprajendra/stacki | python | @pytest.fixture
def fake_local_firmware_file(tmp_path_factory):
fake_firmware_file = (tmp_path_factory.mktemp('fake_firmware') / 'foo.img')
fake_firmware_file.write_text('foofakefirmware')
return fake_firmware_file |
def _sample_pair(self):
'Sample a pair of two windows.\n '
(win_ind1, rec_ind1) = self.sample_window()
ts1 = self.metadata.iloc[win_ind1]['i_start_in_trial']
ts = self.info.iloc[rec_ind1]['i_start_in_trial']
pair_type = self.rng.binomial(1, 0.5)
win_ind2 = None
if (pair_type == 0):
if self.same_rec_neg:
mask = (((ts <= (ts1 - self.tau_neg)) & (ts >= (ts1 - self.tau_max))) | ((ts >= (ts1 + self.tau_neg)) & (ts <= (ts1 + self.tau_max))))
else:
rec_ind2 = rec_ind1
while (rec_ind2 == rec_ind1):
(win_ind2, rec_ind2) = self.sample_window()
elif (pair_type == 1):
mask = ((ts >= (ts1 - self.tau_pos)) & (ts <= (ts1 + self.tau_pos)))
if (win_ind2 is None):
mask[(ts == ts1)] = False
if (sum(mask) == 0):
raise NotImplementedError
win_ind2 = self.rng.choice(self.info.iloc[rec_ind1]['index'][mask])
return (win_ind1, win_ind2, float(pair_type)) | -7,632,719,765,910,472,000 | Sample a pair of two windows. | braindecode/samplers/ssl.py | _sample_pair | Div12345/braindecode | python | def _sample_pair(self):
'\n '
(win_ind1, rec_ind1) = self.sample_window()
ts1 = self.metadata.iloc[win_ind1]['i_start_in_trial']
ts = self.info.iloc[rec_ind1]['i_start_in_trial']
pair_type = self.rng.binomial(1, 0.5)
win_ind2 = None
if (pair_type == 0):
if self.same_rec_neg:
mask = (((ts <= (ts1 - self.tau_neg)) & (ts >= (ts1 - self.tau_max))) | ((ts >= (ts1 + self.tau_neg)) & (ts <= (ts1 + self.tau_max))))
else:
rec_ind2 = rec_ind1
while (rec_ind2 == rec_ind1):
(win_ind2, rec_ind2) = self.sample_window()
elif (pair_type == 1):
mask = ((ts >= (ts1 - self.tau_pos)) & (ts <= (ts1 + self.tau_pos)))
if (win_ind2 is None):
mask[(ts == ts1)] = False
if (sum(mask) == 0):
raise NotImplementedError
win_ind2 = self.rng.choice(self.info.iloc[rec_ind1]['index'][mask])
return (win_ind1, win_ind2, float(pair_type)) |
def presample(self):
'Presample examples.\n\n Once presampled, the examples are the same from one epoch to another.\n '
self.examples = [self._sample_pair() for _ in range(self.n_examples)]
return self | 1,304,268,887,128,117,200 | Presample examples.
Once presampled, the examples are the same from one epoch to another. | braindecode/samplers/ssl.py | presample | Div12345/braindecode | python | def presample(self):
'Presample examples.\n\n Once presampled, the examples are the same from one epoch to another.\n '
self.examples = [self._sample_pair() for _ in range(self.n_examples)]
return self |
def __iter__(self):
'Iterate over pairs.\n\n Yields\n ------\n (int): position of the first window in the dataset.\n (int): position of the second window in the dataset.\n (float): 0 for negative pair, 1 for positive pair.\n '
for i in range(self.n_examples):
if hasattr(self, 'examples'):
(yield self.examples[i])
else:
(yield self._sample_pair()) | -1,480,063,355,216,798,500 | Iterate over pairs.
Yields
------
(int): position of the first window in the dataset.
(int): position of the second window in the dataset.
(float): 0 for negative pair, 1 for positive pair. | braindecode/samplers/ssl.py | __iter__ | Div12345/braindecode | python | def __iter__(self):
'Iterate over pairs.\n\n Yields\n ------\n (int): position of the first window in the dataset.\n (int): position of the second window in the dataset.\n (float): 0 for negative pair, 1 for positive pair.\n '
for i in range(self.n_examples):
if hasattr(self, 'examples'):
(yield self.examples[i])
else:
(yield self._sample_pair()) |
def setup_run_environment(self, env):
'Set up the compile and runtime environments for a package.'
env.prepend_path('LD_LIBRARY_PATH', (self.spec['cuda'].prefix + '/extras/CUPTI/lib64')) | -4,009,019,514,122,506,000 | Set up the compile and runtime environments for a package. | var/spack/repos/builtin/packages/cbtf-argonavis/package.py | setup_run_environment | CreRecombinase/spack | python | def setup_run_environment(self, env):
env.prepend_path('LD_LIBRARY_PATH', (self.spec['cuda'].prefix + '/extras/CUPTI/lib64')) |
def setup_build_environment(self, env):
'Set up the compile and runtime environments for a package.'
env.prepend_path('LD_LIBRARY_PATH', (self.spec['cuda'].prefix + '/extras/CUPTI/lib64')) | 2,743,965,887,238,356,500 | Set up the compile and runtime environments for a package. | var/spack/repos/builtin/packages/cbtf-argonavis/package.py | setup_build_environment | CreRecombinase/spack | python | def setup_build_environment(self, env):
env.prepend_path('LD_LIBRARY_PATH', (self.spec['cuda'].prefix + '/extras/CUPTI/lib64')) |
def _is_token(pieces: list, special_symbol: str='▁') -> List[str]:
'\n Check for stopwords and actual words in word pieces\n\n Args:\n pieces (list): word pieces returned by sentencepiece model\n special_symbol (str): spm prefix special symbol for space\n Returns:\n List of decoded words\n '
decoded = []
for piece in pieces:
if (special_symbol not in piece):
if ((piece in STOP_WORDS) or (len(piece) > 3)):
piece = (special_symbol + piece)
decoded.append(piece)
else:
decoded.append(piece)
else:
decoded.append(piece)
return decoded | -3,571,330,227,367,067,600 | Check for stopwords and actual words in word pieces
Args:
pieces (list): word pieces returned by sentencepiece model
special_symbol (str): spm prefix special symbol for space
Returns:
List of decoded words | urduhack/tokenization/wtk.py | _is_token | cinfotech94/urduhackk | python | def _is_token(pieces: list, special_symbol: str='▁') -> List[str]:
'\n Check for stopwords and actual words in word pieces\n\n Args:\n pieces (list): word pieces returned by sentencepiece model\n special_symbol (str): spm prefix special symbol for space\n Returns:\n List of decoded words\n '
decoded = []
for piece in pieces:
if (special_symbol not in piece):
if ((piece in STOP_WORDS) or (len(piece) > 3)):
piece = (special_symbol + piece)
decoded.append(piece)
else:
decoded.append(piece)
else:
decoded.append(piece)
return decoded |
def _load_model(model_path: str) -> spm.SentencePieceProcessor:
'\n Loads pre_trained keras model and vocab file\n\n Args:\n model_path (str): Path to the spm model file\n Returns:\n spm model class instance\n '
spm_model = spm.SentencePieceProcessor()
spm_model.Load(model_file=model_path)
return spm_model | 5,117,550,707,783,732,000 | Loads pre_trained keras model and vocab file
Args:
model_path (str): Path to the spm model file
Returns:
spm model class instance | urduhack/tokenization/wtk.py | _load_model | cinfotech94/urduhackk | python | def _load_model(model_path: str) -> spm.SentencePieceProcessor:
'\n Loads pre_trained keras model and vocab file\n\n Args:\n model_path (str): Path to the spm model file\n Returns:\n spm model class instance\n '
spm_model = spm.SentencePieceProcessor()
spm_model.Load(model_file=model_path)
return spm_model |
def _is_model_available(model_path: str) -> None:
'\n Check if the models file exist.\n\n Args:\n model_path (str): path to the tokenizer model file\n Raises:\n FileNotFoundError: If model_path does not exist\n Returns: None\n '
if (not Path(model_path).exists()):
_error = "Word tokenizer Model not found!Please run 'urduhack download' in terminal.Doc: https://urduhack.readthedocs.io/en/stable/installation.html#downloading-models"
raise FileNotFoundError(_error) | 7,883,573,858,682,982,000 | Check if the models file exist.
Args:
model_path (str): path to the tokenizer model file
Raises:
FileNotFoundError: If model_path does not exist
Returns: None | urduhack/tokenization/wtk.py | _is_model_available | cinfotech94/urduhackk | python | def _is_model_available(model_path: str) -> None:
'\n Check if the models file exist.\n\n Args:\n model_path (str): path to the tokenizer model file\n Raises:\n FileNotFoundError: If model_path does not exist\n Returns: None\n '
if (not Path(model_path).exists()):
_error = "Word tokenizer Model not found!Please run 'urduhack download' in terminal.Doc: https://urduhack.readthedocs.io/en/stable/installation.html#downloading-models"
raise FileNotFoundError(_error) |
@click.group()
def main():
'mutori -- for building and applying classifiers of mutation origin'
pass | 2,046,043,796,722,569,700 | mutori -- for building and applying classifiers of mutation origin | mutation_origin/cli.py | main | HuttleyLab/mutationorigin | python | @click.group()
def main():
pass |
@main.command()
@_seed
@_enu_path
@_germline_path
@_output_path
@_train_size
@_enu_ratio
@_numreps
@_overwrite
def sample_data(enu_path, germline_path, output_path, seed, train_size, enu_ratio, numreps, overwrite):
'creates train/test sample data'
if (seed is None):
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
np_seed(seed)
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path, 'logs/data_sampling.log')
if (os.path.exists(logfile_path) and (not overwrite)):
click.secho(f'Exists: {logfile_path}! use overwrite to force.', fg='red')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(enu_path)
LOGGER.input_file(germline_path)
enu = pandas.read_csv(enu_path, sep='\t', header=0)
germline = pandas.read_csv(germline_path, sep='\t', header=0)
train_size = (train_size // 2)
test_size = train_size
(train_enu_ratio, test_enu_ratio) = enu_ratio
(enu_train_size, germ_train_size) = get_enu_germline_sizes(train_size, train_enu_ratio)
(enu_test_size, germ_test_size) = get_enu_germline_sizes(test_size, test_enu_ratio)
assert (min(enu_train_size, germ_train_size, enu_test_size, germ_test_size) > 0)
if (((2 * train_size) > enu.shape[0]) or ((2 * train_size) > germline.shape[0])):
print(f'ENU data set size: {enu.shape[0]}')
print(f'Germline data set size: {germline.shape[0]}')
print(f'Train set size: {train_size}')
raise ValueError('2 x train size exceeds size of training data source(s)')
for rep in range(numreps):
test_outpath = os.path.join(output_path, f'test-{rep}.tsv.gz')
train_outpath = os.path.join(output_path, f'train-{rep}.tsv.gz')
(enu_training, enu_testing) = train_test_split(enu, test_size=enu_test_size, train_size=enu_train_size)
(germ_training, germ_testing) = train_test_split(germline, test_size=germ_test_size, train_size=germ_train_size)
if any(map((lambda x: (x.shape[0] == 0)), [enu_training, enu_testing, germ_training, germ_testing])):
raise RuntimeError('screw up in creating test/train set')
testing = pandas.concat([enu_testing, germ_testing])
training = pandas.concat([enu_training, germ_training])
testing.to_csv(test_outpath, index=False, sep='\t', compression='gzip')
training.to_csv(train_outpath, index=False, sep='\t', compression='gzip')
LOGGER.output_file(test_outpath)
LOGGER.output_file(train_outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 2,462,059,754,860,692,000 | creates train/test sample data | mutation_origin/cli.py | sample_data | HuttleyLab/mutationorigin | python | @main.command()
@_seed
@_enu_path
@_germline_path
@_output_path
@_train_size
@_enu_ratio
@_numreps
@_overwrite
def sample_data(enu_path, germline_path, output_path, seed, train_size, enu_ratio, numreps, overwrite):
if (seed is None):
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
np_seed(seed)
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path, 'logs/data_sampling.log')
if (os.path.exists(logfile_path) and (not overwrite)):
click.secho(f'Exists: {logfile_path}! use overwrite to force.', fg='red')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(enu_path)
LOGGER.input_file(germline_path)
enu = pandas.read_csv(enu_path, sep='\t', header=0)
germline = pandas.read_csv(germline_path, sep='\t', header=0)
train_size = (train_size // 2)
test_size = train_size
(train_enu_ratio, test_enu_ratio) = enu_ratio
(enu_train_size, germ_train_size) = get_enu_germline_sizes(train_size, train_enu_ratio)
(enu_test_size, germ_test_size) = get_enu_germline_sizes(test_size, test_enu_ratio)
assert (min(enu_train_size, germ_train_size, enu_test_size, germ_test_size) > 0)
if (((2 * train_size) > enu.shape[0]) or ((2 * train_size) > germline.shape[0])):
print(f'ENU data set size: {enu.shape[0]}')
print(f'Germline data set size: {germline.shape[0]}')
print(f'Train set size: {train_size}')
raise ValueError('2 x train size exceeds size of training data source(s)')
for rep in range(numreps):
test_outpath = os.path.join(output_path, f'test-{rep}.tsv.gz')
train_outpath = os.path.join(output_path, f'train-{rep}.tsv.gz')
(enu_training, enu_testing) = train_test_split(enu, test_size=enu_test_size, train_size=enu_train_size)
(germ_training, germ_testing) = train_test_split(germline, test_size=germ_test_size, train_size=germ_train_size)
if any(map((lambda x: (x.shape[0] == 0)), [enu_training, enu_testing, germ_training, germ_testing])):
raise RuntimeError('screw up in creating test/train set')
testing = pandas.concat([enu_testing, germ_testing])
training = pandas.concat([enu_training, germ_training])
testing.to_csv(test_outpath, index=False, sep='\t', compression='gzip')
training.to_csv(train_outpath, index=False, sep='\t', compression='gzip')
LOGGER.output_file(test_outpath)
LOGGER.output_file(train_outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_c_values
@_penalty_options
@_n_jobs
@_overwrite
@_verbose
def lr_train(training_path, output_path, label_col, seed, scoring, flank_size, feature_dim, proximal, usegc, c_values, penalty_options, n_jobs, overwrite, verbose):
'logistic regression training, validation, dumps optimal model'
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-lr.pkl.gz')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
logfile_path = os.path.join(output_path, f'logs/{basename}-training-lr.log')
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = logistic_regression(feat, resp, seed, scoring, c_values, penalty_options.split(','), n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas, scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 2,206,609,258,705,900,500 | logistic regression training, validation, dumps optimal model | mutation_origin/cli.py | lr_train | HuttleyLab/mutationorigin | python | @main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_c_values
@_penalty_options
@_n_jobs
@_overwrite
@_verbose
def lr_train(training_path, output_path, label_col, seed, scoring, flank_size, feature_dim, proximal, usegc, c_values, penalty_options, n_jobs, overwrite, verbose):
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-lr.pkl.gz')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
logfile_path = os.path.join(output_path, f'logs/{basename}-training-lr.log')
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = logistic_regression(feat, resp, seed, scoring, c_values, penalty_options.split(','), n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas, scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_alpha_options
@_class_prior
@_n_jobs
@_overwrite
@_verbose
def nb_train(training_path, output_path, label_col, seed, scoring, flank_size, feature_dim, proximal, usegc, alpha_options, class_prior, n_jobs, overwrite, verbose):
'Naive Bayes training, validation, dumps optimal model'
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-nb.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-nb.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
if (class_prior is not None):
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
class_prior = [class_prior[l] for (_, l) in ordered]
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = naive_bayes(feat, resp, seed, alpha_options, scoring, class_prior=class_prior, n_jobs=n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas, scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open_(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 7,332,786,271,015,682,000 | Naive Bayes training, validation, dumps optimal model | mutation_origin/cli.py | nb_train | HuttleyLab/mutationorigin | python | @main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_score
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_alpha_options
@_class_prior
@_n_jobs
@_overwrite
@_verbose
def nb_train(training_path, output_path, label_col, seed, scoring, flank_size, feature_dim, proximal, usegc, alpha_options, class_prior, n_jobs, overwrite, verbose):
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-nb.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-nb.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
if (class_prior is not None):
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
class_prior = [class_prior[l] for (_, l) in ordered]
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = naive_bayes(feat, resp, seed, alpha_options, scoring, class_prior=class_prior, n_jobs=n_jobs)
betas = dict(zip(names, classifier.best_estimator_.coef_.tolist()[0]))
result = dict(classifier=classifier.best_estimator_, betas=betas, scoring=scoring)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open_(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_strategy
@_n_jobs
@_overwrite
@_verbose
def xgboost_train(training_path, output_path, label_col, seed, flank_size, feature_dim, proximal, usegc, strategy, n_jobs, overwrite, verbose):
'Naive Bayes training, validation, dumps optimal model'
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-xgb.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-xgb.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
resp = [(v if (v > 0) else 0) for v in resp]
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = xgboost(feat, resp, seed, strategy, n_jobs, verbose)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 1,488,352,229,197,225,200 | Naive Bayes training, validation, dumps optimal model | mutation_origin/cli.py | xgboost_train | HuttleyLab/mutationorigin | python | @main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_strategy
@_n_jobs
@_overwrite
@_verbose
def xgboost_train(training_path, output_path, label_col, seed, flank_size, feature_dim, proximal, usegc, strategy, n_jobs, overwrite, verbose):
if (not seed):
seed = int(time.time())
np_seed(seed)
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-xgb.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-xgb.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, resp, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc)
resp = [(v if (v > 0) else 0) for v in resp]
if usegc:
scaler = get_scaler(feat)
feat = scaler.transform(feat)
classifier = xgboost(feat, resp, seed, strategy, n_jobs, verbose)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
if usegc:
result['scaler'] = scaler
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_overwrite
@_verbose
def ocs_train(training_path, output_path, label_col, seed, flank_size, feature_dim, proximal, usegc, overwrite, verbose):
'one-class svm training for outlier detection'
if (seed is None):
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-ocs.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-ocs.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, _, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc=usegc, one_class='g')
classifier = one_class_svm(feat, seed)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 223,836,685,097,591,780 | one-class svm training for outlier detection | mutation_origin/cli.py | ocs_train | HuttleyLab/mutationorigin | python | @main.command()
@_training_path
@_output_path
@_label_col
@_seed
@_flank_size
@_feature_dim
@_proximal
@_usegc
@_overwrite
@_verbose
def ocs_train(training_path, output_path, label_col, seed, flank_size, feature_dim, proximal, usegc, overwrite, verbose):
if (seed is None):
seed = int(time.time())
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
start_time = time.time()
os.makedirs(output_path, exist_ok=True)
basename = get_basename(training_path)
outpath = os.path.join(output_path, f'{basename}-classifier-ocs.pkl.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-training-ocs.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(training_path)
start_time = time.time()
(_, _, feat, n_dims, names) = data_to_numeric(training_path, label_col, flank_size, feature_dim, proximal, usegc=usegc, one_class='g')
classifier = one_class_svm(feat, seed)
result = dict(classifier=classifier)
result['feature_params'] = dict(feature_dim=feature_dim, flank_size=flank_size, proximal=proximal, usegc=usegc)
with open(outpath, 'wb') as clf_file:
pickle.dump(result, clf_file)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_classifier_path
@_data_path
@_output_path
@_label_col
@_class_prior
@_overwrite
@_verbose
def predict(classifier_path, data_path, output_path, label_col, class_prior, overwrite, verbose):
'predict labels for data'
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
(classifier, feature_params, scaler) = load_classifier(classifier_path)
class_label = get_classifier_label(classifier)
if ((class_prior is not None) and (class_label == 'lr')):
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
if ('e' in ordered[0]):
adj = log((class_prior['g'] / class_prior['e']))
else:
adj = log((class_prior['e'] / class_prior['g']))
classifier.intercept_ += adj
basename_class = get_basename(classifier_path)
basename_data = get_basename(data_path)
basename = f'{basename_class}-{basename_data}'
outpath = os.path.join(output_path, f'{basename}-predicted-{class_label}.json.gz')
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path, f'logs/{basename}-predict-{class_label}.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(classifier_path)
LOGGER.input_file(data_path)
start_time = time.time()
if (class_label in ('nb', 'xgb')):
classifier.decision_function = classifier.predict_proba
fulldata = pandas.read_csv(data_path, sep='\t')
result = {}
result['feature_params'] = feature_params
result['classifier_label'] = class_label
result['classifier_path'] = classifier_path
result['predictions'] = defaultdict(list)
total = (fulldata.shape[0] // 2000)
pbar = tqdm(iter_indices(fulldata.shape[0], block_size=2000), ncols=80, total=total)
for indices in pbar:
data = fulldata.iloc[indices]
(ids, resp, feat, n_dims, names) = data_to_numeric(data, label_col=label_col, **feature_params)
if scaler:
feat = scaler.transform(feat)
(predictions, scores) = predict_origin(classifier, feat)
if (class_label in ('nb', 'xgb')):
scores = scores[:, 1].tolist()
elif (class_label == 'ocs'):
scores = scores[:, 0].tolist()
predictions = inverse_transform_response(predictions)
result['predictions']['varid'].extend(list(ids))
result['predictions']['predicted'].extend(list(predictions))
result['predictions']['scores'].extend(list(scores))
dump_json(outpath, result)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() | 6,324,410,792,706,579,000 | predict labels for data | mutation_origin/cli.py | predict | HuttleyLab/mutationorigin | python | @main.command()
@_classifier_path
@_data_path
@_output_path
@_label_col
@_class_prior
@_overwrite
@_verbose
def predict(classifier_path, data_path, output_path, label_col, class_prior, overwrite, verbose):
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
(classifier, feature_params, scaler) = load_classifier(classifier_path)
class_label = get_classifier_label(classifier)
if ((class_prior is not None) and (class_label == 'lr')):
class_labels = list(class_prior)
encoded = transform_response(class_labels)
ordered = sorted(zip(encoded, class_labels))
if ('e' in ordered[0]):
adj = log((class_prior['g'] / class_prior['e']))
else:
adj = log((class_prior['e'] / class_prior['g']))
classifier.intercept_ += adj
basename_class = get_basename(classifier_path)
basename_data = get_basename(data_path)
basename = f'{basename_class}-{basename_data}'
outpath = os.path.join(output_path, f'{basename}-predicted-{class_label}.json.gz')
os.makedirs(output_path, exist_ok=True)
logfile_path = os.path.join(output_path, f'logs/{basename}-predict-{class_label}.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(classifier_path)
LOGGER.input_file(data_path)
start_time = time.time()
if (class_label in ('nb', 'xgb')):
classifier.decision_function = classifier.predict_proba
fulldata = pandas.read_csv(data_path, sep='\t')
result = {}
result['feature_params'] = feature_params
result['classifier_label'] = class_label
result['classifier_path'] = classifier_path
result['predictions'] = defaultdict(list)
total = (fulldata.shape[0] // 2000)
pbar = tqdm(iter_indices(fulldata.shape[0], block_size=2000), ncols=80, total=total)
for indices in pbar:
data = fulldata.iloc[indices]
(ids, resp, feat, n_dims, names) = data_to_numeric(data, label_col=label_col, **feature_params)
if scaler:
feat = scaler.transform(feat)
(predictions, scores) = predict_origin(classifier, feat)
if (class_label in ('nb', 'xgb')):
scores = scores[:, 1].tolist()
elif (class_label == 'ocs'):
scores = scores[:, 0].tolist()
predictions = inverse_transform_response(predictions)
result['predictions']['varid'].extend(list(ids))
result['predictions']['predicted'].extend(list(predictions))
result['predictions']['scores'].extend(list(scores))
dump_json(outpath, result)
LOGGER.output_file(outpath)
duration = (time.time() - start_time)
LOGGER.log_message(('%.2f' % (duration / 60.0)), label='run duration (minutes)')
LOGGER.shutdown() |
@main.command()
@_data_path
@_predictions_path
@_output_path
@_label_col
@_overwrite
@_verbose
def performance(data_path, predictions_path, output_path, label_col, overwrite, verbose):
'produce measures of classifier performance'
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
if (not (data_path or predictions_path)):
click.secho('Need data sets!', fg='red')
exit()
basename_train = get_basename(data_path)
basename_pred = get_basename(predictions_path)
basename = f'{basename_train}-{basename_pred}'
outpath = os.path.join(output_path, f'{basename}-performance.json.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-performance.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. Use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(data_path)
LOGGER.input_file(predictions_path)
orig = pandas.read_csv(data_path, sep='\t')
(predicted, feature_params, classifier_path, label) = load_predictions(predictions_path)
result = measure_performance(orig, predicted, label_col)
result['feature_params'] = feature_params
result['classifier_path'] = classifier_path
result['classifier_label'] = label
dump_json(outpath, result)
LOGGER.shutdown() | -2,990,725,081,721,783,300 | produce measures of classifier performance | mutation_origin/cli.py | performance | HuttleyLab/mutationorigin | python | @main.command()
@_data_path
@_predictions_path
@_output_path
@_label_col
@_overwrite
@_verbose
def performance(data_path, predictions_path, output_path, label_col, overwrite, verbose):
LOGGER.log_args()
LOGGER.log_versions(['sklearn', 'numpy'])
if (not (data_path or predictions_path)):
click.secho('Need data sets!', fg='red')
exit()
basename_train = get_basename(data_path)
basename_pred = get_basename(predictions_path)
basename = f'{basename_train}-{basename_pred}'
outpath = os.path.join(output_path, f'{basename}-performance.json.gz')
logfile_path = os.path.join(output_path, f'logs/{basename}-performance.log')
if (os.path.exists(outpath) and (not overwrite)):
if (verbose > 1):
click.secho(f'Skipping. {outpath} exists. Use overwrite to force.', fg='green')
return
LOGGER.log_file_path = logfile_path
LOGGER.input_file(data_path)
LOGGER.input_file(predictions_path)
orig = pandas.read_csv(data_path, sep='\t')
(predicted, feature_params, classifier_path, label) = load_predictions(predictions_path)
result = measure_performance(orig, predicted, label_col)
result['feature_params'] = feature_params
result['classifier_path'] = classifier_path
result['classifier_label'] = label
dump_json(outpath, result)
LOGGER.shutdown() |
def startup(self):
'\n Construct and show the Toga application.\n\n Usually, you would add your application to a main content box.\n We then create a main window (with a name matching the app), and\n show the main window.\n '
main_box = toga.Box(style=Pack(direction=COLUMN))
name_label = toga.Label('Your name: ', style=Pack(padding=(0, 5)))
self.name_input = toga.TextInput(style=Pack(flex=1))
name_box = toga.Box(style=Pack(direction=ROW, padding=5))
name_box.add(name_label)
name_box.add(self.name_input)
button = toga.Button('Say Hello!', on_press=self.say_hello, style=Pack(padding=5))
main_box.add(name_box)
main_box.add(button)
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show() | -7,820,798,773,575,304,000 | Construct and show the Toga application.
Usually, you would add your application to a main content box.
We then create a main window (with a name matching the app), and
show the main window. | src/helloworld/app.py | startup | The-Heyman/helloworld | python | def startup(self):
'\n Construct and show the Toga application.\n\n Usually, you would add your application to a main content box.\n We then create a main window (with a name matching the app), and\n show the main window.\n '
main_box = toga.Box(style=Pack(direction=COLUMN))
name_label = toga.Label('Your name: ', style=Pack(padding=(0, 5)))
self.name_input = toga.TextInput(style=Pack(flex=1))
name_box = toga.Box(style=Pack(direction=ROW, padding=5))
name_box.add(name_label)
name_box.add(self.name_input)
button = toga.Button('Say Hello!', on_press=self.say_hello, style=Pack(padding=5))
main_box.add(name_box)
main_box.add(button)
self.main_window = toga.MainWindow(title=self.formal_name)
self.main_window.content = main_box
self.main_window.show() |
def report_following_redirect(self, new_url):
'Report information extraction.'
self._downloader.to_screen(('[redirect] Following redirect to %s' % new_url)) | -5,159,658,233,100,727,000 | Report information extraction. | yt_dlp/extractor/generic.py | report_following_redirect | king-millez/yt-dlp | python | def report_following_redirect(self, new_url):
self._downloader.to_screen(('[redirect] Following redirect to %s' % new_url)) |
def _extract_camtasia(self, url, video_id, webpage):
' Returns None if no camtasia video can be found. '
camtasia_cfg = self._search_regex('fo\\.addVariable\\(\\s*"csConfigFile",\\s*"([^"]+)"\\s*\\);', webpage, 'camtasia configuration file', default=None)
if (camtasia_cfg is None):
return None
title = self._html_search_meta('DC.title', webpage, fatal=True)
camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
camtasia_cfg = self._download_xml(camtasia_url, video_id, note='Downloading camtasia configuration', errnote='Failed to download camtasia configuration')
fileset_node = camtasia_cfg.find('./playlist/array/fileset')
entries = []
for n in fileset_node.getchildren():
url_n = n.find('./uri')
if (url_n is None):
continue
entries.append({'id': os.path.splitext(url_n.text.rpartition('/')[2])[0], 'title': ('%s - %s' % (title, n.tag)), 'url': compat_urlparse.urljoin(url, url_n.text), 'duration': float_or_none(n.find('./duration').text)})
return {'_type': 'playlist', 'entries': entries, 'title': title} | 293,797,661,186,300,600 | Returns None if no camtasia video can be found. | yt_dlp/extractor/generic.py | _extract_camtasia | king-millez/yt-dlp | python | def _extract_camtasia(self, url, video_id, webpage):
' '
camtasia_cfg = self._search_regex('fo\\.addVariable\\(\\s*"csConfigFile",\\s*"([^"]+)"\\s*\\);', webpage, 'camtasia configuration file', default=None)
if (camtasia_cfg is None):
return None
title = self._html_search_meta('DC.title', webpage, fatal=True)
camtasia_url = compat_urlparse.urljoin(url, camtasia_cfg)
camtasia_cfg = self._download_xml(camtasia_url, video_id, note='Downloading camtasia configuration', errnote='Failed to download camtasia configuration')
fileset_node = camtasia_cfg.find('./playlist/array/fileset')
entries = []
for n in fileset_node.getchildren():
url_n = n.find('./uri')
if (url_n is None):
continue
entries.append({'id': os.path.splitext(url_n.text.rpartition('/')[2])[0], 'title': ('%s - %s' % (title, n.tag)), 'url': compat_urlparse.urljoin(url, url_n.text), 'duration': float_or_none(n.find('./duration').text)})
return {'_type': 'playlist', 'entries': entries, 'title': title} |
def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, api_id: Optional[pulumi.Input[str]]=None, description: Optional[pulumi.Input[str]]=None, display_name: Optional[pulumi.Input[str]]=None, method: Optional[pulumi.Input[str]]=None, operation_id: Optional[pulumi.Input[str]]=None, policies: Optional[pulumi.Input[str]]=None, request: Optional[pulumi.Input[pulumi.InputType['RequestContractArgs']]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, responses: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]]]=None, service_name: Optional[pulumi.Input[str]]=None, template_parameters: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]]]=None, url_template: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None):
"\n Api Operation details.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.\n :param pulumi.Input[str] description: Description of the operation. May include HTML formatting tags.\n :param pulumi.Input[str] display_name: Operation Name.\n :param pulumi.Input[str] method: A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.\n :param pulumi.Input[str] operation_id: Operation identifier within an API. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] policies: Operation Policies\n :param pulumi.Input[pulumi.InputType['RequestContractArgs']] request: An entity containing request details.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]] responses: Array of Operation responses.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]] template_parameters: Collection of URL template parameters.\n :param pulumi.Input[str] url_template: Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}\n "
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (opts is None):
opts = pulumi.ResourceOptions()
if (not isinstance(opts, pulumi.ResourceOptions)):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if (opts.version is None):
opts.version = _utilities.get_version()
if (opts.id is None):
if (__props__ is not None):
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if ((api_id is None) and (not opts.urn)):
raise TypeError("Missing required property 'api_id'")
__props__['api_id'] = api_id
__props__['description'] = description
if ((display_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'display_name'")
__props__['display_name'] = display_name
if ((method is None) and (not opts.urn)):
raise TypeError("Missing required property 'method'")
__props__['method'] = method
__props__['operation_id'] = operation_id
__props__['policies'] = policies
__props__['request'] = request
if ((resource_group_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['responses'] = responses
if ((service_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'service_name'")
__props__['service_name'] = service_name
__props__['template_parameters'] = template_parameters
if ((url_template is None) and (not opts.urn)):
raise TypeError("Missing required property 'url_template'")
__props__['url_template'] = url_template
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:apimanagement:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/latest:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20160707:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20161010:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20170301:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20180101:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20180601preview:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20190101:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20191201:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20191201preview:ApiOperation')])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ApiOperation, __self__).__init__('azure-nextgen:apimanagement/v20200601preview:ApiOperation', resource_name, __props__, opts) | 5,588,701,446,771,875,000 | Api Operation details.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.
:param pulumi.Input[str] description: Description of the operation. May include HTML formatting tags.
:param pulumi.Input[str] display_name: Operation Name.
:param pulumi.Input[str] method: A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.
:param pulumi.Input[str] operation_id: Operation identifier within an API. Must be unique in the current API Management service instance.
:param pulumi.Input[str] policies: Operation Policies
:param pulumi.Input[pulumi.InputType['RequestContractArgs']] request: An entity containing request details.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]] responses: Array of Operation responses.
:param pulumi.Input[str] service_name: The name of the API Management service.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]] template_parameters: Collection of URL template parameters.
:param pulumi.Input[str] url_template: Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date} | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | __init__ | pulumi/pulumi-azure-nextgen | python | def __init__(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions]=None, api_id: Optional[pulumi.Input[str]]=None, description: Optional[pulumi.Input[str]]=None, display_name: Optional[pulumi.Input[str]]=None, method: Optional[pulumi.Input[str]]=None, operation_id: Optional[pulumi.Input[str]]=None, policies: Optional[pulumi.Input[str]]=None, request: Optional[pulumi.Input[pulumi.InputType['RequestContractArgs']]]=None, resource_group_name: Optional[pulumi.Input[str]]=None, responses: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]]]=None, service_name: Optional[pulumi.Input[str]]=None, template_parameters: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]]]=None, url_template: Optional[pulumi.Input[str]]=None, __props__=None, __name__=None, __opts__=None):
"\n Api Operation details.\n\n :param str resource_name: The name of the resource.\n :param pulumi.ResourceOptions opts: Options for the resource.\n :param pulumi.Input[str] api_id: API revision identifier. Must be unique in the current API Management service instance. Non-current revision has ;rev=n as a suffix where n is the revision number.\n :param pulumi.Input[str] description: Description of the operation. May include HTML formatting tags.\n :param pulumi.Input[str] display_name: Operation Name.\n :param pulumi.Input[str] method: A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.\n :param pulumi.Input[str] operation_id: Operation identifier within an API. Must be unique in the current API Management service instance.\n :param pulumi.Input[str] policies: Operation Policies\n :param pulumi.Input[pulumi.InputType['RequestContractArgs']] request: An entity containing request details.\n :param pulumi.Input[str] resource_group_name: The name of the resource group.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ResponseContractArgs']]]] responses: Array of Operation responses.\n :param pulumi.Input[str] service_name: The name of the API Management service.\n :param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ParameterContractArgs']]]] template_parameters: Collection of URL template parameters.\n :param pulumi.Input[str] url_template: Relative URL template identifying the target resource for this operation. May include parameters. Example: /customers/{cid}/orders/{oid}/?date={date}\n "
if (__name__ is not None):
warnings.warn('explicit use of __name__ is deprecated', DeprecationWarning)
resource_name = __name__
if (__opts__ is not None):
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if (opts is None):
opts = pulumi.ResourceOptions()
if (not isinstance(opts, pulumi.ResourceOptions)):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if (opts.version is None):
opts.version = _utilities.get_version()
if (opts.id is None):
if (__props__ is not None):
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
if ((api_id is None) and (not opts.urn)):
raise TypeError("Missing required property 'api_id'")
__props__['api_id'] = api_id
__props__['description'] = description
if ((display_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'display_name'")
__props__['display_name'] = display_name
if ((method is None) and (not opts.urn)):
raise TypeError("Missing required property 'method'")
__props__['method'] = method
__props__['operation_id'] = operation_id
__props__['policies'] = policies
__props__['request'] = request
if ((resource_group_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['responses'] = responses
if ((service_name is None) and (not opts.urn)):
raise TypeError("Missing required property 'service_name'")
__props__['service_name'] = service_name
__props__['template_parameters'] = template_parameters
if ((url_template is None) and (not opts.urn)):
raise TypeError("Missing required property 'url_template'")
__props__['url_template'] = url_template
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_='azure-nextgen:apimanagement:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/latest:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20160707:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20161010:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20170301:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20180101:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20180601preview:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20190101:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20191201:ApiOperation'), pulumi.Alias(type_='azure-nextgen:apimanagement/v20191201preview:ApiOperation')])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(ApiOperation, __self__).__init__('azure-nextgen:apimanagement/v20200601preview:ApiOperation', resource_name, __props__, opts) |
@staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'ApiOperation':
"\n Get an existing ApiOperation resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return ApiOperation(resource_name, opts=opts, __props__=__props__) | -5,423,887,866,892,393,000 | Get an existing ApiOperation resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource. | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | get | pulumi/pulumi-azure-nextgen | python | @staticmethod
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions]=None) -> 'ApiOperation':
"\n Get an existing ApiOperation resource's state with the given name, id, and optional extra\n properties used to qualify the lookup.\n\n :param str resource_name: The unique name of the resulting resource.\n :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.\n :param pulumi.ResourceOptions opts: Options for the resource.\n "
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return ApiOperation(resource_name, opts=opts, __props__=__props__) |
@property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
'\n Description of the operation. May include HTML formatting tags.\n '
return pulumi.get(self, 'description') | 427,557,619,421,051,900 | Description of the operation. May include HTML formatting tags. | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | description | pulumi/pulumi-azure-nextgen | python | @property
@pulumi.getter
def description(self) -> pulumi.Output[Optional[str]]:
'\n \n '
return pulumi.get(self, 'description') |
@property
@pulumi.getter(name='displayName')
def display_name(self) -> pulumi.Output[str]:
'\n Operation Name.\n '
return pulumi.get(self, 'display_name') | 3,246,000,777,289,042,000 | Operation Name. | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | display_name | pulumi/pulumi-azure-nextgen | python | @property
@pulumi.getter(name='displayName')
def display_name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'display_name') |
@property
@pulumi.getter
def method(self) -> pulumi.Output[str]:
'\n A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them.\n '
return pulumi.get(self, 'method') | -9,205,044,597,593,766,000 | A Valid HTTP Operation Method. Typical Http Methods like GET, PUT, POST but not limited by only them. | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | method | pulumi/pulumi-azure-nextgen | python | @property
@pulumi.getter
def method(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'method') |
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n Resource name.\n '
return pulumi.get(self, 'name') | 4,695,236,134,441,039,000 | Resource name. | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | name | pulumi/pulumi-azure-nextgen | python | @property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
'\n \n '
return pulumi.get(self, 'name') |
@property
@pulumi.getter
def policies(self) -> pulumi.Output[Optional[str]]:
'\n Operation Policies\n '
return pulumi.get(self, 'policies') | -8,272,438,894,036,339,000 | Operation Policies | sdk/python/pulumi_azure_nextgen/apimanagement/v20200601preview/api_operation.py | policies | pulumi/pulumi-azure-nextgen | python | @property
@pulumi.getter
def policies(self) -> pulumi.Output[Optional[str]]:
'\n \n '
return pulumi.get(self, 'policies') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.