1import sys
2import unittest
3
4import numpy
5import ideep4py
6from ideep4py import dropout
7
8try:
9    import testing
10except Exception as ex:
11    print('*** testing directory is missing: %s' % ex)
12    sys.exit(-1)
13
14
15def _dropout(x, creator):
16    return x * creator.mask
17
18
19@testing.parameterize(*testing.product({
20    'dropout_ratio': [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
21    'dtype': [numpy.float32, ],
22}))
23@testing.fix_random()
24class TestDropoutF32(unittest.TestCase):
25
26    def setUp(self):
27        self.x = numpy.random.rand(128, 3, 224, 224).astype(self.dtype)
28        self.x_md = ideep4py.mdarray(self.x)
29        self.gy = numpy.random.rand(128, 3, 224, 224).astype(self.dtype)
30
31    def check_forward(self, x, x_md):
32        mask, y = dropout.Forward(x_md, self.dropout_ratio)
33        y = numpy.array(y, dtype=self.dtype)
34        y_expect = x * mask
35        numpy.testing.assert_allclose(y, y_expect)
36
37    def check_backward(self, x_md, gy):
38        mask, y = dropout.Forward(x_md, self.dropout_ratio)
39        gy_md = ideep4py.mdarray(gy)
40        gx = dropout.Backward(mask, gy_md)
41        gx = numpy.array(gx, dtype=self.dtype)
42        gx_expect = gy * mask
43        numpy.testing.assert_allclose(gx, gx_expect)
44
45    def test_forward_cpu(self):
46        self.check_forward(self.x, self.x_md)
47
48    def test_backward_cpu(self):
49        self.check_backward(self.x_md, self.gy)
50
51
52testing.run_module(__name__, __file__)
53