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.

Tanh.py 1.2 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 tanh as cpu_tanh
  6. from ..gpu_links import tanh
  7. class TanhOp(Op):
  8. def __init__(self, node_A, ctx=None):
  9. super().__init__(TanhOp, [node_A], ctx)
  10. def compute(self, input_vals, output_val, stream_handle=None):
  11. if self.on_cpu:
  12. if DNNL_LIB['DnnlTanh']:
  13. cpu_tanh(input_vals[0], output_val)
  14. else:
  15. output_val[:] = np.tanh(input_vals[0].asnumpy())
  16. else:
  17. tanh(input_vals[0], output_val, stream_handle)
  18. def gradient(self, output_grad):
  19. grad_A = 1 + -1 * \
  20. tanh_op(self.inputs[0], ctx=self.raw_ctx) * \
  21. tanh_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 tanh_op(node, ctx=None):
  27. """Calculate tanh 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 TanhOp(node, ctx=ctx)