test_logit_op.py 3.8 KB
Newer Older
W
wangzhen38 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.

import unittest
import numpy as np
from op_test import OpTest
import paddle
19
from paddle.fluid.framework import _test_eager_guard
20

W
wangzhen38 已提交
21 22 23 24
np.random.seed(10)


def logit(x, eps):
25
    x_min = np.minimum(x, 1.0 - eps)
W
wangzhen38 已提交
26
    x_max = np.maximum(x_min, eps)
27
    return np.log(x_max / (1.0 - x_max))
W
wangzhen38 已提交
28 29 30


def logit_grad(x, eps=1e-8):
31 32 33 34
    tmp_x = np.select(
        [x < eps, x > (1.0 - eps)], [x * 0.0, x * 0.0], default=-1.0
    )
    x_1 = 1.0 - x
W
wangzhen38 已提交
35
    _x = np.select([tmp_x == -1.0], [np.reciprocal(x * x_1)], default=0.0)
36
    dout = np.full_like(x, fill_value=1.0 / _x.size)
W
wangzhen38 已提交
37 38 39 40 41 42 43
    dx = dout * _x
    return dx


class TestLogitOp(OpTest):
    def setUp(self):
        self.op_type = 'logit'
44
        self.python_api = paddle.logit
W
wangzhen38 已提交
45 46 47 48
        self.dtype = np.float64
        self.shape = [120]
        self.eps = 1e-8
        self.set_attrs()
49
        x = np.random.uniform(-1.0, 1.0, self.shape).astype(self.dtype)
W
wangzhen38 已提交
50 51 52 53 54 55 56 57 58 59
        out = logit(x, self.eps)
        self.x_grad = logit_grad(x, self.eps)
        self.inputs = {'X': x}
        self.outputs = {'Out': out}
        self.attrs = {'eps': self.eps}

    def set_attrs(self):
        pass

    def test_check_output(self):
60
        self.check_output(check_eager=True)
W
wangzhen38 已提交
61 62

    def test_check_grad(self):
63 64 65
        self.check_grad(
            ['X'], ['Out'], user_defined_grads=[self.x_grad], check_eager=True
        )
W
wangzhen38 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80


class TestLogitShape(TestLogitOp):
    def set_attrs(self):
        self.shape = [2, 60]


class TestLogitEps(TestLogitOp):
    def set_attrs(self):
        self.eps = 1e-8


class TestLogitAPI(unittest.TestCase):
    def setUp(self):
        self.x_shape = [120]
81 82 83 84
        self.x = np.random.uniform(0.0, 1.0, self.x_shape).astype(np.float32)
        self.place = (
            paddle.CUDAPlace(0)
            if paddle.fluid.core.is_compiled_with_cuda()
W
wangzhen38 已提交
85
            else paddle.CPUPlace()
86
        )
W
wangzhen38 已提交
87 88 89 90 91 92 93 94 95

    def check_api(self, eps=1e-8):
        ref_out = logit(self.x, eps)
        # test static api
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data(name='x', shape=self.x_shape)
            y = paddle.logit(x, eps)
            exe = paddle.static.Executor(self.place)
            out = exe.run(feed={'x': self.x}, fetch_list=[y])
96
        np.testing.assert_allclose(out[0], ref_out, rtol=1e-05)
W
wangzhen38 已提交
97 98 99 100
        # test dygrapg api
        paddle.disable_static()
        x = paddle.to_tensor(self.x)
        y = paddle.logit(x, 1e-8)
101
        np.testing.assert_allclose(y.numpy(), ref_out, rtol=1e-05)
W
wangzhen38 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        paddle.enable_static()

    def test_check_api(self):
        paddle.enable_static()
        for eps in [1e-6, 0.0]:
            self.check_api(eps)

    def test_errors(self):
        paddle.enable_static()
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.fluid.data(name='X1', shape=[100], dtype='int32')
            self.assertRaises(TypeError, paddle.logit, x)

            x = paddle.fluid.data(name='X2', shape=[100], dtype='float32')
            self.assertRaises(TypeError, paddle.logit, x, dtype='int32')

118 119 120 121 122
    def test_api_eager_dygraph(self):
        with _test_eager_guard():
            self.test_check_api()
            self.test_errors()

W
wangzhen38 已提交
123 124 125

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