Search code examples
arraystensorflowmasking

Binary mask in Tensorflow


I would like to mask every other value along a particular dimension of a Tensor but don't see a good way to generate such a mask. For example

#Masking on the 2nd dimension
a = [[1,2,3,4,5],[6,7,8,9,0]
mask = [[1,0,1,0,1],[1,1,1,1,1]]
b = a * mask #would return [[1,0,3,0,5],[6,0,8,0,0]]

Is there an easy way to generate such a mask?

Ideally I would like to do something like the following:

mask = tf.ones_like(input_tensor)
mask[:,::2] = 0
mask * input_tensor

But slice assigning doesn't seem to be as simple as in Numpy.


Solution

  • You can easily programmatically create such a tensor mask using python. Then convert it to a tensor. There's no such support in the TensorFlow API. tf.tile([1,0], num_of_repeats) might be a fast way to create such mask but not that great either if you have odd number of columns.

    (Btw, if you end up creating a boolean mask, use tf.boolean_mask())