rahulk64
rahulk64

Reputation: 69

Equivalent for setting Numpy-like mask values in Tensorflow?

In numpy I know you can do something like this:

array[mask] = -1

where, given a mask (an array of booleans or 0/1), for every index in the mask where its value is True, you set the associated index in array to the value (in this case, -1).

I'm wondering if there's an equivalent operation in Tensorflow to do the same as the example above (setting values in a tensor based on a mask).

Thanks in advance!

Upvotes: 1

Views: 114

Answers (1)

thushv89
thushv89

Reputation: 11333

You can do the following. It's a bit cluttery than numpy though.

Option 1

import tensorflow as tf

m = tf.constant([[True, False],[False, True]])
a = tf.constant([[2.,3.],[1.,2.]])
val = 5
b = a * tf.cast(tf.logical_not(m), tf.float32) + val * tf.cast(m, tf.float32)

with tf.Session() as sess:
  print(sess.run(b))

Option 2

m = tf.constant([[True, False],[False, True]])
a = tf.constant([[2.,3.],[1.,2.]])
val = 5
val_arr = tf.ones_like(a)*val

c = tf.where(tf.equal(m,False), a, val_arr)

Upvotes: 1

Related Questions