fastest ways to convert empty tensor to 0

Viewed 314

I have a batch of tensors

tensors = tf.constant([[1,2,3], [2, 4, 5], [1,2,7]], dtype=tf.float32)

And I have a mechanism to select some tensors among them by tf.boolean_mask:

bools = [0, 0, 0]
tensors_sorted = tf.boolean_mask(tensors, mask=bools)

The problem is when all bools are zeros, the tensors_sorted becomes an empty tensor.

tensors_sorted_out = sess.run(tensors_sorted) # array([], shape=(0, 3), dtype=float32)

Now I want tensors to be scalar 0. in this case. I know one way by tf.cond

tensors_sorted = tf.cond(tf.reduce_sum(bools)>0, lambda:tensors_sorted, lambda: 0.)
tensors_sorted_out = sess.run(tensors_sorted) # tensors_sorted_out = 0.

But this one looks quite slow. Would there be any faster way than this?

Note added*: Actually, we might consider an option to change tenosrs_sorted to zero tensor with the same shape.

1 Answers

we might consider an option to change tenosrs_sorted to zero tensor with the same shape. Probably with tf.where:

t = tf.where(tf.equal(bools, 0), tf.zeros_like(tensors), tensors)
t.eval()
#array([[ 0.,  0.,  0.],
#       [ 0.,  0.,  0.],
#       [ 0.,  0.,  0.]], dtype=float32)
Related