Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

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

Nonzero values: [1,4]   Nonzero indices: [[0,0],[1,1]] 

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.)

like image 444
ByungSoo Ko Avatar asked Aug 30 '16 05:08

ByungSoo Ko


People also ask

How do you find the index of a nonzero element NumPy?

nonzero() function is used to Compute the indices of the elements that are non-zero. It returns a tuple of arrays, one for each dimension of arr, containing the indices of the non-zero elements in that dimension. The corresponding non-zero values in the array can be obtained with arr[nonzero(arr)] .

What are three parameters that define tensors in TensorFlow?

Each tensor object is defined with tensor attributes like a unique label (name), a dimension (shape) and TensorFlow data types (dtype). You can define a tensor with decimal values or with a string by changing the type of data.


2 Answers

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]] 
like image 152
Sergii Gryshkevych Avatar answered Sep 20 '22 14:09

Sergii Gryshkevych


#assume that an array has 0, 3.069711,  3.167817. mask = tf.greater(array, 0) non_zero_array = tf.boolean_mask(array, mask) 
like image 32
user1098761 Avatar answered Sep 17 '22 14:09

user1098761