如何在张量流中沿轴排列二维张量?

How to rank a 2-d tensor along an axis in tensorflow?

我正在尝试在 Tensorflow 中获取二维张量的等级。我可以在 numpy 中使用类似的东西来做到这一点:

import numpy as np
from scipy.stats import rankdata

a = np.array([[0,3,2], [6,5,4]])
ranks = np.apply_along_axis(rankdata, 1, a)

ranks是:

array([[ 1.,  3.,  2.],
       [ 3.,  2.,  1.]])

我的问题是如何在 tensorflow 中执行此操作?

import tensorflow as tf
a = tf.constant([[0,3,2], [6,5,4]])
sess = tf.InteractiveSession()
ranks = magic_function(a)
ranks.eval()

tf.nn.top_k 对你有用,尽管它的语义略有不同。请阅读文档以了解如何将其用于您的案例。但这里是解决你的例子的片段:

sess = tf.InteractiveSession()
a = tf.constant(np.array([[0,3,2], [6,5,4]]))
# tf.nn.top_k sorts in ascending order, so negate to switch the sense
_, ranks = tf.nn.top_k(-a, 3)
# top_k outputs 0 based indices, so add 1 to get the same
# effect as rankdata
ranks = ranks + 1
sess.run(ranks)

# output :
# array([[1, 3, 2],
#        [3, 2, 1]], dtype=int32)