Skip to content
Advertisement

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

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

JavaScript

And I want to get nonzero values and their indices from it.

JavaScript

There are similar operations in Numpy.
np.flatnonzero(A) return indices that are non-zero in the flattened A.
x.ravel()[np.flatnonzero(x)] extract elements according to non-zero indices.
Here’s a link for these operations.

How can I do somthing like above Numpy operations in Tensorflow with python?
(Whether a matrix is flattened or not doesn’t really matter.)

Advertisement

Answer

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

JavaScript

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

JavaScript

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:

JavaScript

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:

JavaScript
Advertisement