【问题标题】:Tensorflow: Selecting items from one tensor by another tensorTensorflow:通过另一个张量从一个张量中选择项目
【发布时间】:2017-12-23 06:01:52
【问题描述】:

我有一个值张量和一个重新排序张量。重新排序张量为值张量中的每一行提供排序。如何使用这个重排序张量对值张量中的值进行实际重排序。

这会在 numpy (Indexing one array by another in numpy) 中给出所需的结果:

import numpy as np
values = np.array([
    [5,4,100],
    [10,20,500]
])
reorder_rows = np.array([
    [1,2,0],
    [0,2,1]
])


result = values[np.arange(values.shape[0])[:,None],reorder_rows]
print(result)

# [[  4 100   5]
#  [ 10 500  20]]

我怎样才能在 tf 中做同样的事情?

我尝试过使用切片和 tf.gather_nd 但无法成功。

谢谢。

【问题讨论】:

    标签: python tensorflow slice


    【解决方案1】:

    尝试以下方法:

    import numpy as np
    values = np.array([
        [5,4,100],
        [10,20,500]
    ])
    reorder_rows = np.array([
        [1,2,0],
        [0,2,1]
    ])
    
    import tensorflow as tf
    
    values = tf.constant(values)
    reorder_rows = tf.constant(reorder_rows, dtype=tf.int32)
    x = tf.tile(tf.range(tf.shape(values)[0])[:,tf.newaxis], [1,tf.shape(values)[1]])
    res = tf.gather_nd(values, tf.stack([x, reorder_rows], axis=-1))
    sess = tf.InteractiveSession()
    res.eval()
    

    【讨论】:

      【解决方案2】:

      以下tf code 应该给出相同的结果:

      values = tf.constant([
       [5,4,100],
       [10,20,500]
      ])
      reorder_rows = tf.constant([
         [[0,1],[0,2],[0,0]],
         [[1,0],[1,2],[1,1]]
      ])
      result = tf.gather_nd(values, reorder_rows)
      sess = tf.InteractiveSession()
      tf.global_variables_initializer().run()
      result.eval()
      
      #Result
      #[[  4, 100,   5],
      #[ 10, 500,  20]]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-20
        • 1970-01-01
        • 1970-01-01
        • 2019-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多