【问题标题】:How to use a tensor for indexing another tensor in tensorflow如何使用张量在张量流中索引另一个张量
【发布时间】:2017-08-06 09:57:14
【问题描述】:

我有一个维度为[B X N X 3] 的data 张量,我有一个维度为[B X M] 的indices 张量。我希望使用indices 张量从data 张量中提取[B X M X 3] 张量。

我有这个有效的代码:

new_data= []    
for i in range(B):
        new_data.append(tf.gather(data[i], indices[i]))
new_data= tf.stack(new_data) 

但是,我确信这样做不是正确的方法。有谁知道更好的方法? (我想我应该以某种方式使用tf.gather_nd(),但我不知道如何使用)

我已经看过几个类似问题的答案here。但是我找不到我的问题的解决方案。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以将tf.gather_nd() 与如下代码一起使用:

    import tensorflow as tf
    
    # B = 3
    # N = 4
    # M = 2
    # [B x N x 3]
    data = tf.constant([
        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]],
        [[100, 101, 102], [103, 104, 105], [106, 107, 108], [109, 110, 111]],
        [[200, 201, 202], [203, 204, 205], [206, 207, 208], [209, 210, 211]],
        ])
    
    # [B x M]
    indices = tf.constant([
        [0, 2],
        [1, 3],
        [3, 2],
        ])
    
    indices_shape = tf.shape(indices)
    
    indices_help = tf.tile(tf.reshape(tf.range(indices_shape[0]), [indices_shape[0], 1]) ,[1, indices_shape[1]]);
    indices_ext = tf.concat([tf.expand_dims(indices_help, 2), tf.expand_dims(indices, 2)], axis = 2)
    new_data = tf.gather_nd(data, indices_ext)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print('data')
        print(sess.run(data))
        print('\nindices')
        print(sess.run(indices))
        print('\nnew_data')
        print(sess.run(new_data))
    

    new_data 将是:

    [[[  0   1   2]
      [  6   7   8]]
    
     [[103 104 105]
      [109 110 111]]
    
     [[209 210 211]
      [206 207 208]]]
    

    【讨论】:

    • 有效!但是你能解释一下这三行代码背后的逻辑(indices_help、indices_ext 、new_data )吗?
    • tf.gather_nd 需要切片索引(两个坐标<b,n>),但我们只有一个坐标<n>,在indices 数组中隐含坐标b。因此,我们应该通过添加 batch 的索引来扩展indices 的每个元素。就是这个。首先我们用批处理索引制作indices_help,然后将它与源indices连接起来
    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多