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

前端 未结 2 1172
花落未央
花落未央 2021-02-03 23:08

I want to do something like this.
Let\'s say we have a tensor A.

A = [[1,0],[0,4]]

And I want to get nonzero values and their indices fro

2条回答
  •  没有蜡笔的小新
    2021-02-03 23:26

    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]]
    

提交回复
热议问题