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.

Where.py 1.5 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from __future__ import absolute_import
  2. import numpy as np
  3. from .Node import Op
  4. from ..gpu_links import where
  5. class WhereOp(Op):
  6. def __init__(self, cond, node_A, node_B, ctx=None):
  7. super().__init__(WhereOp, [cond, node_A, node_B], ctx)
  8. def compute(self, input_vals, output_val, stream_handle=None):
  9. if self.on_cpu:
  10. output_val[:] = np.where(input_vals[0].asnumpy(
  11. ), input_vals[1].asnumpy(), input_vals[2].asnumpy())
  12. else:
  13. where(input_vals[0], input_vals[1],
  14. input_vals[2], output_val, stream_handle)
  15. def gradient(self, output_grad):
  16. from .ZerosLike import zeroslike_op
  17. zeros = zeroslike_op(self.inputs[0], ctx=self.raw_ctx)
  18. grad_A = where_op(self.inputs[0], output_grad, zeros, ctx=self.raw_ctx)
  19. grad_B = where_op(self.inputs[0], zeros, output_grad, ctx=self.raw_ctx)
  20. return [None, grad_A, grad_B]
  21. def infer_shape(self, input_shapes):
  22. assert len(input_shapes) == 3
  23. assert tuple(input_shapes[0]) == tuple(
  24. input_shapes[1]) == tuple(input_shapes[2])
  25. return input_shapes[0]
  26. def where_op(cond, node_A, node_B, ctx=None):
  27. """Creates a node that represents np.where.
  28. Parameters:
  29. ----
  30. cond : Node of a condition array
  31. node_A : Node, output if cond
  32. node_B : Node, output if not cond
  33. Returns:
  34. ----
  35. A new Node instance created by Op.
  36. """
  37. return WhereOp(cond, node_A, node_B, ctx=ctx)