Filter nonzero values ​​in the tensor

Suppose I have an array: input = np.array([[1,0,3,5,0,8,6]]) and I want to filter out [1,3,5,8,6] .

I know that you can use tf.where with a condition, but the return value still has 0. Output of the next fragment [[[1 0 3 5 0 8 6]]] . I also don't understand why tf.where needed for both x and y .

In any case, can I get rid of 0 in the resulting tensor?

 import numpy as np import tensorflow as tf input = np.array([[1,0,3,5,0,8,6]]) X = tf.placeholder(tf.int32,[None,7]) zeros = tf.zeros_like(X) index = tf.not_equal(X,zeros) loc = tf.where(index,x=X,y=X) with tf.Session() as sess: out = sess.run([loc],feed_dict={X:input}) print np.array(out) 
+5
source share
1 answer

First create a boolean mask to determine where your condition is true; then apply the mask to your tensor as shown below. You can, if you want to use the tf.where index for indexing - however, it returns the tensor using x & y with the same rank as the input, so without further work, the best you could achieve would be like [[[ 1 -1 3 5 - 1 8 6]]] by changing -1 with what you would later identify. Just using where (without x & y) will give you an index of all the values ​​where your condition is true, so a solution can be created using indexes if that is what you prefer. My recommendation is below for clarity.

 import numpy as np import tensorflow as tf input = np.array([[1,0,3,5,0,8,6]]) X = tf.placeholder(tf.int32,[None,7]) zeros = tf.cast(tf.zeros_like(X),dtype=tf.bool) ones = tf.cast(tf.ones_like(X),dtype=tf.bool) loc = tf.where(input!=0,ones,zeros) result=tf.boolean_mask(input,loc) with tf.Session() as sess: out = sess.run([result],feed_dict={X:input}) print (np.array(out)) 
+3
source

Source: https://habr.com/ru/post/1264138/


All Articles