Skip to content
This repository has been archived by the owner on Nov 17, 2023. It is now read-only.

Commit

Permalink
add coverage for npx.relu and npx.sigmoid
Browse files Browse the repository at this point in the history
  • Loading branch information
haojin2 committed Aug 11, 2019
1 parent 88b1818 commit 1c1cc02
Showing 1 changed file with 74 additions and 0 deletions.
74 changes: 74 additions & 0 deletions tests/python/unittest/test_numpy_op.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,80 @@ def hybrid_forward(self, F, a, *args, **kwargs):
check_unary_func(func, ref_grad, shape, low, high)


@with_seed()
@use_np
def test_npx_relu():
def np_relu(x):
return _np.maximum(x, 0.0)
def np_relu_grad(x):
return 1.0 * (x > 0.0)

class TestReLU(HybridBlock):
def __init__(self):
super(TestReLU, self).__init__()

def hybrid_forward(self, F, a):
return F.npx.relu(a)

shapes = [(), (2, 3, 4), (2, 0, 3), (1, 0, 0)]
for hybridize in [True, False]:
for shape in shapes:
test_relu = TestReLU()
if hybridize:
test_relu.hybridize()
x = rand_ndarray(shape).as_np_ndarray()
x.attach_grad()
np_out = np_relu(x.asnumpy())
with mx.autograd.record():
mx_out = test_relu(x)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
mx_out.backward()
np_backward = np_relu_grad(x.asnumpy())
assert_almost_equal(x.grad.asnumpy(), np_backward, rtol=1e-3, atol=1e-5)

mx_out = npx.relu(x)
np_out = np_relu(x.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)


@with_seed()
@use_np
def test_npx_sigmoid():
def np_sigmoid(x):
return _np.divide(1.0, (1.0 + _np.exp(-x)))
def np_sigmoid_grad(ya):
return ya * (1 - ya)

class TestSigmoid(HybridBlock):
def __init__(self):
super(TestSigmoid, self).__init__()

def hybrid_forward(self, F, a):
return F.npx.sigmoid(a)

shapes = [(), (2, 3, 4), (2, 0, 3), (1, 0, 0)]
for hybridize in [True, False]:
for shape in shapes:
test_sigmoid = TestSigmoid()
if hybridize:
test_sigmoid.hybridize()
x = rand_ndarray(shape).as_np_ndarray()
x.attach_grad()
np_out = np_sigmoid(x.asnumpy())
with mx.autograd.record():
mx_out = test_sigmoid(x)
assert mx_out.shape == np_out.shape
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)
mx_out.backward()
np_backward = np_sigmoid_grad(np_out)
assert_almost_equal(x.grad.asnumpy(), np_backward, rtol=1e-3, atol=1e-5)

mx_out = npx.sigmoid(x)
np_out = np_sigmoid(x.asnumpy())
assert_almost_equal(mx_out.asnumpy(), np_out, rtol=1e-3, atol=1e-5)


if __name__ == '__main__':
import nose
nose.runmodule()

0 comments on commit 1c1cc02

Please sign in to comment.