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

15 16
from __future__ import print_function

Z
zyfncg 已提交
17
import paddle
W
wanghaox 已提交
18 19 20 21
import unittest
import numpy as np
import math
import sys
M
minqiyang 已提交
22
import paddle.compat as cpt
23
from op_test import OpTest
24
import paddle.fluid as fluid
W
wanghaox 已提交
25

26

W
wanghaox 已提交
27
class TestROIPoolOp(OpTest):
W
wanghaox 已提交
28 29 30 31 32
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.calc_roi_pool()

F
FDInSky 已提交
33 34 35
        self.inputs = {
            'X': self.x,
            'ROIs': (self.rois[:, 1:5], self.rois_lod),
Z
zyfncg 已提交
36
            'RoisNum': self.boxes_num
F
FDInSky 已提交
37
        }
38

W
wanghaox 已提交
39 40 41
        self.attrs = {
            'spatial_scale': self.spatial_scale,
            'pooled_height': self.pooled_height,
42 43
            'pooled_width': self.pooled_width
        }
W
wanghaox 已提交
44

45
        self.outputs = {'Out': self.outs, 'Argmax': self.argmaxes}
W
wanghaox 已提交
46 47

    def init_test_case(self):
48
        self.batch_size = 3
W
wanghaox 已提交
49 50 51 52 53
        self.channels = 3
        self.height = 6
        self.width = 4

        # n, c, h, w
54
        self.x_dim = (self.batch_size, self.channels, self.height, self.width)
W
wanghaox 已提交
55

56
        self.spatial_scale = 1.0 / 4.0
W
wanghaox 已提交
57 58 59
        self.pooled_height = 2
        self.pooled_width = 2

60
        self.x = np.random.random(self.x_dim).astype('float64')
W
wanghaox 已提交
61 62

    def calc_roi_pool(self):
63 64 65 66 67
        out_data = np.zeros((self.rois_num, self.channels, self.pooled_height,
                             self.pooled_width))
        argmax_data = np.zeros((self.rois_num, self.channels,
                                self.pooled_height, self.pooled_width))

W
wanghaox 已提交
68 69
        for i in range(self.rois_num):
            roi = self.rois[i]
70
            roi_batch_id = int(roi[0])
M
minqiyang 已提交
71 72 73 74
            roi_start_w = int(cpt.round(roi[1] * self.spatial_scale))
            roi_start_h = int(cpt.round(roi[2] * self.spatial_scale))
            roi_end_w = int(cpt.round(roi[3] * self.spatial_scale))
            roi_end_h = int(cpt.round(roi[4] * self.spatial_scale))
W
wanghaox 已提交
75

76 77
            roi_height = int(max(roi_end_h - roi_start_h + 1, 1))
            roi_width = int(max(roi_end_w - roi_start_w + 1, 1))
W
wanghaox 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

            x_i = self.x[roi_batch_id]

            bin_size_h = float(roi_height) / float(self.pooled_height)
            bin_size_w = float(roi_width) / float(self.pooled_width)

            for c in range(self.channels):
                for ph in range(self.pooled_height):
                    for pw in range(self.pooled_width):
                        hstart = int(math.floor(ph * bin_size_h))
                        wstart = int(math.floor(pw * bin_size_w))
                        hend = int(math.ceil((ph + 1) * bin_size_h))
                        wend = int(math.ceil((pw + 1) * bin_size_w))

                        hstart = min(max(hstart + roi_start_h, 0), self.height)
                        hend = min(max(hend + roi_start_h, 0), self.height)
                        wstart = min(max(wstart + roi_start_w, 0), self.width)
                        wend = min(max(wend + roi_start_w, 0), self.width)

W
wanghaox 已提交
97 98 99 100 101 102
                        is_empty = (hend <= hstart) or (wend <= wstart)
                        if is_empty:
                            out_data[i, c, ph, pw] = 0
                        else:
                            out_data[i, c, ph, pw] = -sys.float_info.max

W
wanghaox 已提交
103
                        argmax_data[i, c, ph, pw] = -1
104

W
wanghaox 已提交
105 106 107 108
                        for h in range(hstart, hend):
                            for w in range(wstart, wend):
                                if x_i[c, h, w] > out_data[i, c, ph, pw]:
                                    out_data[i, c, ph, pw] = x_i[c, h, w]
M
minqiyang 已提交
109 110
                                    argmax_data[i, c, ph,
                                                pw] = h * self.width + w
W
wanghaox 已提交
111

112
        self.outs = out_data.astype('float64')
W
wanghaox 已提交
113 114 115 116
        self.argmaxes = argmax_data.astype('int64')

    def make_rois(self):
        rois = []
117 118
        self.rois_lod = [[]]
        for bno in range(self.batch_size):
119
            self.rois_lod[0].append(bno + 1)
120
            for i in range(bno + 1):
121
                x1 = np.random.randint(
M
minqiyang 已提交
122
                    0, self.width // self.spatial_scale - self.pooled_width)
123
                y1 = np.random.randint(
M
minqiyang 已提交
124
                    0, self.height // self.spatial_scale - self.pooled_height)
125

126 127 128 129
                x2 = np.random.randint(x1 + self.pooled_width,
                                       self.width // self.spatial_scale)
                y2 = np.random.randint(y1 + self.pooled_height,
                                       self.height // self.spatial_scale)
130 131 132 133

                roi = [bno, x1, y1, x2, y2]
                rois.append(roi)
        self.rois_num = len(rois)
134
        self.rois = np.array(rois).astype("float64")
Z
zyfncg 已提交
135 136
        self.boxes_num = np.array(
            [bno + 1 for bno in range(self.batch_size)]).astype('int32')
W
wanghaox 已提交
137 138 139

    def setUp(self):
        self.op_type = "roi_pool"
Z
zyfncg 已提交
140 141
        self.python_api = lambda x, boxes, boxes_num, pooled_height, pooled_width, spatial_scale: paddle.vision.ops.roi_pool(x, boxes, boxes_num, (pooled_height, pooled_width), spatial_scale)
        self.python_out_sig = ["Out"]
W
wanghaox 已提交
142 143 144
        self.set_data()

    def test_check_output(self):
Z
zyfncg 已提交
145
        self.check_output(check_eager=True)
W
wanghaox 已提交
146 147

    def test_check_grad(self):
Z
zyfncg 已提交
148
        self.check_grad(['X'], 'Out', check_eager=True)
W
wanghaox 已提交
149

150

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
class BadInputTestRoiPool(unittest.TestCase):
    def test_error(self):
        with fluid.program_guard(fluid.Program()):

            def test_bad_x():
                x = fluid.layers.data(
                    name='data1', shape=[2, 1, 4, 4], dtype='int64')
                label = fluid.layers.data(
                    name='label', shape=[2, 4], dtype='float32', lod_level=1)
                output = fluid.layers.roi_pool(x, label, 1, 1, 1.0)

            self.assertRaises(TypeError, test_bad_x)

            def test_bad_y():
                x = fluid.layers.data(
                    name='data2',
                    shape=[2, 1, 4, 4],
                    dtype='float32',
                    append_batch_size=False)
                label = [[1, 2, 3, 4], [2, 3, 4, 5]]
                output = fluid.layers.roi_pool(x, label, 1, 1, 1.0)

            self.assertRaises(TypeError, test_bad_y)


F
FDInSky 已提交
176 177 178 179 180 181 182 183 184 185 186
class TestROIPoolInLodOp(TestROIPoolOp):
    def set_data(self):
        self.init_test_case()
        self.make_rois()
        self.calc_roi_pool()

        seq_len = self.rois_lod[0]

        self.inputs = {
            'X': self.x,
            'ROIs': (self.rois[:, 1:5], self.rois_lod),
187
            'RoisNum': np.asarray(seq_len).astype('int32')
F
FDInSky 已提交
188 189 190 191 192 193 194 195 196 197 198
        }

        self.attrs = {
            'spatial_scale': self.spatial_scale,
            'pooled_height': self.pooled_height,
            'pooled_width': self.pooled_width
        }

        self.outputs = {'Out': self.outs, 'Argmax': self.argmaxes}


W
wanghaox 已提交
199 200
if __name__ == '__main__':
    unittest.main()