First use () to take out the index of the value that satisfies the condition, in numpy, you can directly use the matrix to refer to the index to take out the value that satisfies the condition, but in tensorflow this is not possible. Fortunately, tensorflow provides () and tf.gather_nd() functions.
Look at the following piece of code:
import tensorflow as tf sess = () def get_tensor(): x = tf.random_uniform((5, 4)) ind = (x>0.5) y = tf.gather_nd(x, ind) return x, ind, y
In the above code, the outputs are the original tensor x, the index of the value in x that satisfies a specific condition (here >0.5), and the value in x that satisfies the specific condition, respectively. Perform the following steps to observe the values corresponding to the three tensors:
x, ind, y = get_tensor() x_, ind_, y_ = ([x, ind, y])
The following results can be obtained:
It can be seen that the values greater than 0.5 in tensor x are taken out of the above result to form a new tensor y.
What happens if we replace tf.gather_nd in the code? Since it is not convenient to show the result, we won't put the result here, it applies to the case where index is one-dimensional, in this case, index is 2-dimensional, and the corresponding dimensions of x, ind, and y are as follows, if chosen:
= (5, 4) = (9, 2) = (9, 2, 4)
Above this tensorflow implementation tensor to meet a certain condition of the value out of the composition of a new tensor is all that I share with you, I hope to give you a reference, and I hope you support me more.