You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Sigmoid.py 1.3 kB

5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. from __future__ import absolute_import
  2. import numpy as np
  3. from .Node import Op
  4. from .._base import DNNL_LIB
  5. from ..cpu_links import sigmoid as cpu_sigmoid
  6. from ..gpu_links import sigmoid
  7. class SigmoidOp(Op):
  8. def __init__(self, node_A, ctx=None):
  9. super().__init__(SigmoidOp, [node_A], ctx)
  10. def compute(self, input_vals, output_val, stream_handle=None):
  11. if self.on_cpu:
  12. if DNNL_LIB['DnnlSigmoid']:
  13. cpu_sigmoid(input_vals[0], output_val)
  14. else:
  15. output_val[:] = 1.0/(1.0+1.0/np.exp(input_vals[0].asnumpy()))
  16. else:
  17. sigmoid(input_vals[0], output_val, stream_handle)
  18. def gradient(self, output_grad):
  19. # ds=s(1-s)
  20. grad_A = sigmoid_op(self.inputs[0], ctx=self.raw_ctx) * \
  21. (1 + -1*sigmoid_op(self.inputs[0], ctx=self.raw_ctx))
  22. return [grad_A*output_grad]
  23. def infer_shape(self, input_shapes):
  24. assert len(input_shapes) == 1
  25. return input_shapes[0]
  26. def sigmoid_op(node, ctx=None):
  27. """Calculate sigmoid of a matrix elementwisely.
  28. Parameters:
  29. ----
  30. node : Node
  31. Input variable.
  32. Returns:
  33. ----
  34. A new Node instance created by Op.
  35. """
  36. return SigmoidOp(node, ctx=ctx)