Get the mask of a given tensor

Viewed 69

I have a tensor and I want to get the masked values in it to have the corresponding mask.

input: x1 = [[[0 0 0] [0 0 0] [1 1 1] [-1 -1 0]]]

output mask of x1: mask_1 = [[0 0 1 1]]

I want to do that in a few lines in Keras, what I have done so far is:

mask_3 = K.cast(tf.equal(x1, 0), 'float32')
mask_4 = K.sum(K.ones_like(x1), axis=-1)        
mask_5 = K.sum(mask_3, axis=-1)
mask_6 = mask_5 < mask_4

Is there a more efficient way?

1 Answers

with this condition, you get the rows, on the last dimension, which are all 0 (and reverse them)

x1 = tf.constant([[[0, 0, 0], [0, 0, 0], [1, 1, 1], [-1, -1, 0]]])

tf.logical_not(tf.reduce_all(x1 == 0, axis=-1))
# [[False, False,  True,  True]]

apply a cast if u want numbers

tf.cast(tf.logical_not(tf.reduce_all(x1 == 0, axis=-1)), 'float32')
# [[0., 0., 1., 1.]]
Related