简体   繁体   中英

Tensor has shape [?, 0] — how to reshape to [?,]

When src has shape [?] , tf.gather(src, tf.where(src != 0)) returns a tensor with shape [?, 0] . I'm not sure how a dimension can have size 0, and I'm especially unsure how to change the tensor back. I didn't find anything in the documentation to explain this, either.

I tried to tf.transpose(tensor)[0] , but the first dimension of the transposed tensor has size 0 and cannot be accessed! What's wrong?

I think you should use tf.not_equal to perform elementwise comparison on the tensor.

src = tf.constant([0, 1, 1, 0], dtype=tf.int8)
tf.gather(src, tf.where(tf.not_equal(src, 0))).eval(session=tf.Session())

array([[1],
       [1]], dtype=int8)

You can also shorten this a bit and use tf.boolean_mask instead of tf.where and tf.gather :

tf.boolean_mask(src, tf.not_equal(src, 0)).eval(session=tf.Session())
array([1, 1], dtype=int8)

Note the difference in the shape of the outputs.

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