1# Copyright 2020 Huawei Technologies Co., Ltd 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================ 15import numpy as np 16import pytest 17 18import mindspore.context as context 19import mindspore.nn as nn 20from mindspore import Tensor 21from mindspore.ops import operations as P 22from mindspore.ops.operations import _grad_ops as G 23 24context.set_context(mode=context.GRAPH_MODE, device_target='CPU') 25 26 27class NetSigmoidGrad(nn.Cell): 28 def __init__(self): 29 super(NetSigmoidGrad, self).__init__() 30 self.sigmoid_grad = G.SigmoidGrad() 31 32 def construct(self, y, dy): 33 return self.sigmoid_grad(y, dy) 34 35 36class Net(nn.Cell): 37 def __init__(self): 38 super(Net, self).__init__() 39 self.ops = P.Sigmoid() 40 41 def construct(self, x): 42 return self.ops(x) 43 44@pytest.mark.level0 45@pytest.mark.platform_x86_cpu 46@pytest.mark.env_onecard 47def test_net(): 48 x = np.random.randn(2, 3, 3, 4).astype(np.float32) 49 y_expect = 1 / (1 + np.exp(-x)) 50 net = Net() 51 out = net(Tensor(x)) 52 diff = out.asnumpy() - y_expect 53 err = np.ones(shape=y_expect.shape) * 1.0e-5 54 assert np.all(diff < err) 55 assert out.shape == y_expect.shape 56 57 58@pytest.mark.level0 59@pytest.mark.platform_x86_cpu 60@pytest.mark.env_onecard 61def test_sigmoid_grad(): 62 y = Tensor(np.array([[[[-1, 1, 2], 63 [1, -1, 1], 64 [2, 1, -1]]]]).astype(np.float32)) 65 dy = Tensor(np.array([[[[-11, 2, 4], 66 [-1, 1, -1], 67 [-4, 4, -4]]]]).astype(np.float32)) 68 69 expect = np.array([[[[22, 0, -8], 70 [0, -2, 0], 71 [8, 0, 8]]]]).astype(np.float32) 72 73 error = np.ones(shape=[1, 1, 3, 3]) * 1.0e-6 74 75 sigmoid_grad = NetSigmoidGrad() 76 output = sigmoid_grad(y, dy) 77 diff = np.abs(output.asnumpy() - expect) 78 assert np.all(abs(diff) < error) 79