我有一个根据 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)))
输出:
(array([[1, 2],
[5, 6]], dtype=int32),
array([[3, 4],
[7, 8]], dtype=int32))
我对 true_foo
和 false_foo
做了一些操作,然后我想将它们按原来的顺序放回去:
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))
应该输出:
array([[ 2, 4],
[ 9,12],
[10,12],
[21,24]], dtype=int32)
最佳答案
类似于您自己的解决方案,但使用 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)
基本上,您可以将 true_bar
和 false_bar
分散到两个不同的张量,然后将它们相加。
关于python - tensorflow boolean_mask 逆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564613/