test_crop_op.py 2.4 KB
Newer Older
W
wanghaoshuang 已提交
1 2
import unittest
import numpy as np
3
from op_test import OpTest
W
wanghaoshuang 已提交
4 5


6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
def crop(data, offsets, crop_shape):
    def indexOf(shape, index):
        result = []
        for dim in reversed(shape):
            result.append(index % dim)
            index = index / dim
        return result[::-1]

    result = []
    for i, value in enumerate(data.flatten()):
        index = indexOf(data.shape, i)
        selected = True
        if len(index) == len(offsets):
            for j, offset in enumerate(offsets):
                selected = selected and index[j] >= offset and index[
                    j] < crop_shape[j] + offset
            if selected:
                result.append(value)
    return np.array(result).reshape(crop_shape)


27
class TestCropOp(OpTest):
W
wanghaoshuang 已提交
28
    def setUp(self):
29 30
        self.op_type = "crop"
        self.crop_by_input = False
W
wanghaoshuang 已提交
31
        self.attrs = {}
32
        self.initTestCase()
33
        self.attrs['offsets'] = self.offsets
34 35 36 37 38 39 40 41 42 43
        if self.crop_by_input:
            self.inputs = {
                'X': np.random.random(self.x_shape).astype("float32"),
                'Y': np.random.random(self.crop_shape).astype("float32")
            }
        else:
            self.attrs['shape'] = self.crop_shape
            self.inputs = {
                'X': np.random.random(self.x_shape).astype("float32"),
            }
44 45 46
        self.outputs = {
            'Out': crop(self.inputs['X'], self.offsets, self.crop_shape)
        }
W
wanghaoshuang 已提交
47

48
    def initTestCase(self):
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        self.x_shape = (8, 8)
        self.crop_shape = [2, 2]
        self.offsets = [1, 2]

    def test_check_output(self):
        self.check_output()

    def test_check_grad_normal(self):
        self.check_grad(['X'], 'Out', max_relative_error=0.006)


class TestCase1(TestCropOp):
    def initTestCase(self):
        self.x_shape = (16, 16, 16)
        self.crop_shape = [2, 2, 3]
        self.offsets = [1, 5, 3]


class TestCase2(TestCropOp):
    def initTestCase(self):
        self.x_shape = (4, 4)
        self.crop_shape = [4, 4]
        self.offsets = [0, 0]


class TestCase3(TestCropOp):
    def initTestCase(self):
        self.x_shape = (16, 16, 16)
        self.crop_shape = [2, 2, 3]
        self.offsets = [1, 5, 3]
        self.crop_by_input = True


class TestCase4(TestCropOp):
    def initTestCase(self):
        self.x_shape = (4, 4)
        self.crop_shape = [4, 4]
        self.offsets = [0, 0]
        self.crop_by_input = True

W
wanghaoshuang 已提交
89 90 91

if __name__ == '__main__':
    unittest.main()