【问题标题】:How to find the top k values in a 2-D tensor in tensorflow如何在张量流中找到二维张量中的前 k 个值
【发布时间】:2018-06-11 12:31:08
【问题描述】:

有没有办法在 Tensorflow 的二维张量中找到最高的 k 值?

我可以将tf.nn.top_k 用于一维张量,但它不能用于二维张量。我有一个大小未知的二维张量,有没有办法找到最高的 k 值及其索引?

非常感谢。

【问题讨论】:

    标签: tensorflow matrix tensor


    【解决方案1】:

    您可以在tf.nn.top_k() 之前将矩阵重塑为一维张量,然后根据一维索引计算二维索引:

    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]]
    

    【讨论】:

      【解决方案2】:

      您可以做到这一点的一种方法是重塑整个事物,例如 xx= np.reshape(x,(-1,)),然后像 x[:k] 之类的东西可以吗?

      【讨论】:

        猜你喜欢
        • 2022-09-29
        • 1970-01-01
        • 2017-10-12
        • 2021-01-22
        • 1970-01-01
        • 2019-05-30
        • 1970-01-01
        • 1970-01-01
        • 2016-04-17
        相关资源
        最近更新 更多