In TensorFlow, how can I get nonzero values and their indices from a tensor with python?

时光毁灭记忆、已成空白 提交于 2019-12-02 22:15:12

You can achieve same result in Tensorflow using not_equal and where methods.

zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(A, zero)

where is a tensor of the same shape as A holding True or False, in the following case

[[True, False],
 [False, True]]

This would be sufficient to select zero or non-zero elements from A. If you want to obtain indices you can use wheremethod as follows:

indices = tf.where(where)

where tensor has two True values so indices tensor will have two entries. where tensor has rank of two, so entries will have two indices:

[[0, 0],
 [1, 1]]
#assume that an array has 0, 3.069711,  3.167817.
mask = tf.greater(array, 0)
non_zero_array = tf.boolean_mask(array, mask)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!