简体   繁体   中英

How can I mask a batch of tensor?

I want to do a negative masking on a batch of tensor.

eg target tensor :

[[1,2,3],
 [4,5,6],
 [7,8,9]] 

mask tensor:

[[1,1,0],
 [0,1,1],
 [1,1,0]] 

expect result:

[[1,2,0],
 [0,5,6],
 [7,8,0]]

How can I do that? have to generate every 3x3 matrices?

You can do the following.

import tensorflow as tf

tf_a = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.float32) 
mask = tf.cast(tf.constant([[1,1,0] , [0,1,1], [1,1,0]]) , tf.bool)

a_masked = tf_a * tf.cast(mask, tf.float32)
with tf.Session() as sess:
  #print(sess.run(tf.math.logical_not(mask)))
  print(sess.run(a_masked))

Another way to do this is using tf.where :

tensor = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.float32) 
mask = tf.cast(tf.constant([[1,1,0] , [0,1,1], [1,1,0]]) , tf.bool)
result = tf.where(mask, tensor, tf.zeros_like(tensor))

if you print the result in eager mode:

<tf.Tensor: id=77, shape=(3, 3), dtype=float32, numpy=
array([[1., 2., 0.],
       [0., 5., 6.],
       [7., 8., 0.]], dtype=float32)>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM