I have a tensor that I split up depending on a boolean_mask:
with tf.Session() as sess:
boolean_mask = tf.constant([True, False, True, False])
foo = tf.constant([[1,2],[3,4],[5,6],[7,8]])
true_foo = tf.boolean_mask(foo, boolean_mask, axis=0)
false_foo = tf.boolean_mask(foo, tf.logical_not(boolean_mask), axis=0)
print(sess.run((true_foo, false_foo)))
Outputs:
(array([[1, 2],
[5, 6]], dtype=int32),
array([[3, 4],
[7, 8]], dtype=int32))
I do some operations to true_foo and false_foo, and then I want to put them back together in the original order:
true_bar = 2*true_foo
false_bar = 3*false_foo
bar = tf.boolean_mask_inverse(boolean_mask, true_bar, false_bar)
print(sess.run(bar))
Should output:
array([[ 2, 4],
[ 9,12],
[10,12],
[21,24]], dtype=int32)
Similar to your own solution but with tf.scatter_nd.
true_mask = tf.cast(tf.where(boolean_mask), tf.int32)
false_mask = tf.cast(tf.where(~boolean_mask), tf.int32)
t_foo = tf.scatter_nd(true_mask, true_bar, shape=tf.shape(foo))
f_foo = tf.scatter_nd(false_mask, false_bar, shape=tf.shape(foo))
res = t_foo + f_foo
# array([[ 2, 4],
# [ 9, 12],
# [10, 12],
# [21, 24]], dtype=int32)
Basically, you can scatter the true_bar and false_bar to two different tensors, and add them together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With