【问题标题】:Tensorflow: Pick a list of non-overlapping slices from a tensor based on an info from another tensorTensorflow:根据来自另一个张量的信息从一个张量中选择一个不重叠的切片列表
【发布时间】:2019-07-20 23:33:33
【问题描述】:

我有一个形状为 Batch_size x H x W x C 的卷积层 conv 的输出。 我还有另一个形状为 Batch_size x None x 2 的张量。后一个张量为 bach 中的每个示例提供点列表(高度和宽度坐标)(每个示例的列表长度不同)。我想为每个点提取通道维度。

我尝试使用 tf.gather 和 tf.batch_gather,但两者似乎都不适合在这里使用。

基本上我想要的是每个批次 b 循环通过点:对于每个点 i 都有它的 h_i(高度坐标)和 w_i(坐标)并返回conv[b, h_i, w_j, :]。然后堆叠这些结果。

【问题讨论】:

    标签: python tensorflow slice


    【解决方案1】:

    您可以这样做:

    import tensorflow as tf
    
    def pick_points(images, coords):
        coords = tf.convert_to_tensor(coords)
        s = tf.shape(coords)
        batch_size, num_coords = s[0], s[1]
        # Make batch indices
        r = tf.range(batch_size, dtype=coords.dtype)
        idx_batch = tf.tile(tf.expand_dims(r, 1), [1, num_coords])
        # Full index
        idx = tf.concat([tf.expand_dims(idx_batch, 2), coords], axis=2)
        # Gather pixels
        pixels = tf.gather_nd(images, idx)
        # Output has shape [batch_size, num_coords, num_channels]
        return pixels
    
    # Test
    with tf.Graph().as_default(), tf.Session() as sess:
        # 2 x 2 x 3 x 3
        images = [
            [
                [[ 1,  2,  3], [ 4,  5,  6], [ 7,  8,  9]],
                [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
            ],
            [
                [[19, 20, 21], [22, 23, 24], [25, 26, 27]],
                [[28, 29, 30], [31, 32, 33], [34, 35, 36]],
            ],
        ]
        # 2 x 2 x 2
        coords = [
            [[0, 1], [1, 2]],
            [[1, 0], [1, 1]],
        ]
        pixels = pick_points(images, coords)
        print(sess.run(pixels))
        # [[[ 4  5  6]
        #   [16 17 18]]
        #
        #  [[28 29 30]
        #   [31 32 33]]]
    

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 2018-11-22
      • 1970-01-01
      • 1970-01-01
      • 2016-06-20
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      相关资源
      最近更新 更多