Masking a 3D Placeholder Tensor with a 2D Placeholder in Tensorflow

Viewed 355

I have a placeholder with dynamic size A( batch size, sequence size, 5) and another placeholder with zero and one values and dynamic size B( batch size, sequence size). I want to use the second 2D placeholder for masking the first placeholders as if the value of tensor B[0][0]=0 then A[0][0][0:5] will be set to zero and if it was equal to B[0][0]=1 then A[0][0][0:5] won't change.

palceholder A:(shape=(2,2,5))    
   [[[ 1,  2,  3,  1,  4],
    [ 2,  3,  5,  2,  4]],
   [[ 2,  7,  5,  8,  1],
    [ 4,  5,  1,  3,  9]]] 

palceholder B:(shape=(2,2))
  [[ 1,  0],
   [ 0,  1]]

Tensor C= Mask(A,B)    
   [[[ 1,  2,  3,  1,  4],
    [ 0,  0,  0,  0,  0]],
   [[ 0,  0,  0,  0,  0],
    [ 4,  5,  1,  3,  9]]]

I have tried tf.boolean_mask but it doesn't work for dynamic size masks.

1 Answers

How about

import numpy as np
import tensorflow as tf

a = tf.placeholder(tf.int32, [None, None, 5])
b = tf.placeholder(tf.int32, [None, None])
c = tf.multiply(a, tf.expand_dims(b, -1))

with tf.Session() as sess:
    in_a = np.reshape(np.arange(20, dtype=np.int32), [2, 2, 5])
    in_b = np.eye(2)
    print("A: {}".format(in_a))
    print("B: {}".format(in_b))
    out_c = sess.run(c, feed_dict={a: in_a, b: in_b})
    print("C: {}".format(out_c))

which prints

A: [[[ 0  1  2  3  4]
  [ 5  6  7  8  9]]

 [[10 11 12 13 14]
  [15 16 17 18 19]]]
B: [[1. 0.]
 [0. 1.]]
C: [[[ 0  1  2  3  4]
  [ 0  0  0  0  0]]

 [[ 0  0  0  0  0]
  [15 16 17 18 19]]]
Related