test_crop_op.py 2.3 KB
Newer Older
W
wanghaoshuang 已提交
1 2 3 4 5 6 7
import unittest
import numpy as np
from paddle.v2.framework.op import Operator
from gradient_checker import GradientChecker
from op_test_util import OpTestMeta


8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
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)


29
class TCropOp(OpTest):
W
wanghaoshuang 已提交
30
    def setUp(self):
31
        self.initTestCase()
W
wanghaoshuang 已提交
32
        self.type = "crop"
33
        self.inputs = {'X': np.random.random(self.shape).astype("float32"), }
W
wanghaoshuang 已提交
34
        self.attrs = {}
35 36 37 38 39 40
        self.attrs['offsets'] = self.offsets
        self.attrs['shape'] = self.crop_shape
        self.outputs = {
            'Out': crop(self.inputs['X'], self.offsets, self.crop_shape)
        }
        print "input=%s" % self.inputs['X']
W
wanghaoshuang 已提交
41

42 43 44 45
    def initTestCase(self):
        self.shape = (8, 8, 8)
        self.crop_shape = [2, 2, 2]
        self.offsets = [0, 0, 0]
W
wanghaoshuang 已提交
46 47


48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
#class TCase1(TCropOp):
#    def initTestCase(self):
#        self.shape = (16, 16, 16)
#        self.crop_shape = [2, 2, 3]
#        self.offsets = [1, 5, 3]

#class TCropGradOp(GradientChecker):

#    def initTestCase(self):
#        self.shape = (4, 4)
#        self.crop_shape = [2, 2]
#        self.offsets = [0, 0]

#    def setUp(self):
#        self.initTestCase()
#        self.op = Operator(
#            type="crop", X="X", Out="Out", offsets=self.offsets, shape=self.crop_shape)
#        self.inputs = {'X': np.random.random(self.shape).astype("float32"), }
#
#    def test_normal(self):
#        self.check_grad(
#            self.op, self.inputs, set(["X"]), "Out", max_relative_error=0.5)

#def test_cpu_gpu_compare(self):
#    self.compare_grad(self.op, self.inputs)
W
wanghaoshuang 已提交
73

74
#class TestGradCase1(TestCropGradOp):
W
wanghaoshuang 已提交
75

76 77 78 79
#    def initTestCase(self):
#        self.shape = (16, 16)
#        self.crop_shape = [8, 8]
#        self.offsets = [1, 1]
W
wanghaoshuang 已提交
80 81 82

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