0

Let me introduce the problem with the example in numpy:

arr  - some numpy array
a, b - constants
arr[arr < a] = b

Now, I would like to implement the same functionality but in Tensorflow where arr would be a tensor. Tensor value is not known before runtime.

As you can see, the answer would yield clarification for both assigning values to specific positions inside tensors, and also performing conditioning on the tensor and retrieving indices which satisfy condition.

makons
  • 522
  • 1
  • 11
  • 27
  • Very similar to [this question](https://stackoverflow.com/questions/39045797/conditional-assignment-of-tensor-values-in-tensorflow) – abhuse May 20 '18 at 15:20
  • 2
    See `tf.where`: https://www.tensorflow.org/api_docs/python/tf/where – xdurch0 May 20 '18 at 15:21
  • Possible duplicate of [Conditional assignment of tensor values in TensorFlow](https://stackoverflow.com/questions/39045797/conditional-assignment-of-tensor-values-in-tensorflow) – buzjwa Oct 23 '18 at 12:38

1 Answers1

1

As mentioned by @xdurch0, tf.where() with proper conditioning and broadcasting should do the trick:

b_broadcast = tf.ones(tf.shape(arr), dtype=arr.dtype) * b
arr = tf.where(tf.less(arr, a), b_broadcast, arr)
benjaminplanche
  • 14,689
  • 5
  • 57
  • 69