user9925134
user9925134

Reputation: 33

How to find the top k values in a 2-D tensor in tensorflow

Is there a way to find the top k values in a 2-D tensor in Tensorflow?

I can use tf.nn.top_k for a 1-D tensor but it cannot work with a 2-D tensor. I have a 2-D tensor with unknown size, is there a way to find the top k values and their indices?

Thanks a lot.

Upvotes: 3

Views: 2237

Answers (2)

benjaminplanche
benjaminplanche

Reputation: 15119

You can reshape your matrix to a 1-D tensor before tf.nn.top_k(), then compute the 2-D indices from the 1-D ones:

x = tf.random_uniform((3, 4))
x_shape = tf.shape(x)
k = 3

top_values, top_indices = tf.nn.top_k(tf.reshape(x, (-1,)), k)
top_indices = tf.stack(((top_indices // x_shape[1]), (top_indices % x_shape[1])), -1)

with tf.Session() as sess:
    mat, val, ind = sess.run([x, top_values, top_indices])
    print(mat)
    # [[ 0.2154634   0.52707899  0.29711092  0.74310601]
    #  [ 0.61274767  0.82408106  0.27242708  0.25479805]
    #  [ 0.25863791  0.16790807  0.95585966  0.51889324]]
    print(val)
    # [ 0.95585966  0.82408106  0.74310601]
    print(ind)
    # [[2 2]
    #  [1 1]
    #  [0 3]]

Upvotes: 6

shivam13juna
shivam13juna

Reputation: 347

One way you can do this is reshaping the whole thing like xx= np.reshape(x,(-1,)) and then something like x[:k] will do?

Upvotes: 0

Related Questions