test_clip_op.py 1.2 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


W
wanghaoshuang 已提交
8
class ClipOp(unittest.TestCase):
W
wanghaoshuang 已提交
9 10 11 12
    __metaclass__ = OpTestMeta

    def setUp(self):
        input = np.random.random((16, 16)).astype("float32")
W
wanghaoshuang 已提交
13 14
        input[np.abs(input - 0.1) < 0.05] = 0.5
        input[np.abs(input - 0.9) < 0.05] = 0.5
W
wanghaoshuang 已提交
15 16 17 18 19 20 21 22 23 24 25 26 27
        self.type = "clip"
        self.inputs = {'X': input, }
        self.attrs = {}
        self.attrs['min'] = 0.1
        self.attrs['max'] = 0.9
        self.outputs = {
            'Out': np.clip(self.inputs['X'], self.attrs['min'],
                           self.attrs['max'])
        }


class TestClipGradOp(GradientChecker):
    def setUp(self):
W
wanghaoshuang 已提交
28 29
        input = np.random.random((8, 8)).astype("float32")
        print "input: %s" % input
W
wanghaoshuang 已提交
30
        self.op = Operator(type="clip", X="X", Out="Out", min=0.1, max=0.9)
W
wanghaoshuang 已提交
31
        self.inputs = {'X': input, }
W
wanghaoshuang 已提交
32 33 34 35 36

    def test_normal(self):
        self.check_grad(
            self.op, self.inputs, set(["X"]), "Out", max_relative_error=0.5)

W
wanghaoshuang 已提交
37
    def t_cpu_gpu_compare(self):
W
wanghaoshuang 已提交
38 39 40 41 42
        self.compare_grad(self.op, self.inputs)


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