在 Tensorflow 中,最后一个维度如何使用 tf.gather()?

In Tensorflow, how to use tf.gather() for the last dimension?

我正在尝试根据层之间的部分连接的最后一个维度来收集张量的切片。因为输出张量的shape是[batch_size, h, w, depth],所以我想select根据最后一个维度切片,比如

# L is intermediate tensor
partL = L[:, :, :, [0,2,3,8]]

但是,tf.gather(L, [0, 2,3,8]) 似乎只适用于第一维(对吧?)谁能告诉我该怎么做?

这里有一个支持此用例的跟踪错误:https://github.com/tensorflow/tensorflow/issues/206

现在您可以:

  1. 转置您的矩阵,以便首先收集维度(转置很昂贵)

  2. 将你的张量重塑为 1d(重塑很便宜)并将你的收集列索引转换为线性索引的单个元素索引列表,然后重塑回来

  3. 使用gather_nd。仍然需要将您的列索引转换为单个元素索引的列表。

实施 2. 来自@Yaroslav Bulatov 的:

#Your indices
indices = [0, 2, 3, 8]

#Remember for final reshaping
n_indices = tf.shape(indices)[0]

flattened_L = tf.reshape(L, [-1])

#Walk strided over the flattened array
offset = tf.expand_dims(tf.range(0, tf.reduce_prod(tf.shape(L)), tf.shape(L)[-1]), 1)
flattened_indices = tf.reshape(tf.reshape(indices, [-1])+offset, [-1])
selected_rows = tf.gather(flattened_L, flattened_indices)

#Final reshape
partL = tf.reshape(selected_rows, tf.concat(0, [tf.shape(L)[:-1], [n_indices]]))

归功于

有了 gather_nd,您现在可以按如下方式执行此操作:

cat_idx = tf.concat([tf.range(0, tf.shape(x)[0]), indices_for_dim1], axis=0)
result = tf.gather_nd(matrix, cat_idx)

此外,正如用户 Nova 在@Yaroslav Bulatov 引用的线程中所报告的那样:

x = tf.constant([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
idx = tf.constant([1, 0, 2])
idx_flattened = tf.range(0, x.shape[0]) * x.shape[1] + idx
y = tf.gather(tf.reshape(x, [-1]),  # flatten input
              idx_flattened)  # use flattened indices

with tf.Session(''):
  print y.eval()  # [2 4 9]

要点是展平张量并使用 tf.gather(...) 的跨步一维寻址。

Tensor 没有属性形状,但是 get_shape() 方法。以下可由 Python 2.7

运行
import tensorflow as tf
import numpy as np
x = tf.constant([[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]])
idx = tf.constant([1, 0, 2])
idx_flattened = tf.range(0, x.get_shape()[0]) * x.get_shape()[1] + idx
y = tf.gather(tf.reshape(x, [-1]),  # flatten input
              idx_flattened)  # use flattened indices

with tf.Session(''):
  print y.eval()  # [2 4 9]

另一种使用 tf.unstack(...)、tf.gather(...) 和 tf.stack(..)

的解决方案

代码:

import tensorflow as tf
import numpy as np

shape = [2, 2, 2, 10] 
L = np.arange(np.prod(shape))
L = np.reshape(L, shape)

indices = [0, 2, 3, 8]
axis = -1 # last dimension

def gather_axis(params, indices, axis=0):
    return tf.stack(tf.unstack(tf.gather(tf.unstack(params, axis=axis), indices)), axis=axis)

print(L)
with tf.Session() as sess:
    partL = sess.run(gather_axis(L, indices, axis))
    print(partL)

结果:

L = 
[[[[ 0  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 37 38 39]]]


 [[[40 41 42 43 44 45 46 47 48 49]
   [50 51 52 53 54 55 56 57 58 59]]

  [[60 61 62 63 64 65 66 67 68 69]
   [70 71 72 73 74 75 76 77 78 79]]]]

partL = 
[[[[ 0  2  3  8]
   [10 12 13 18]]

  [[20 22 23 28]
   [30 32 33 38]]]


 [[[40 42 43 48]
   [50 52 53 58]]

  [[60 62 63 68]
   [70 72 73 78]]]]

@Andrei 答案的正确版本应该是

cat_idx = tf.stack([tf.range(0, tf.shape(x)[0]), indices_for_dim1], axis=1)
result = tf.gather_nd(matrix, cat_idx)

你可以这样试试,比如(至少在NLP的大多数情况下),

参数的形状为[batch_size, depth],索引为[i, j, k, n, m],长度为batch_size。那么 gather_nd 可能会有帮助。

parameters = tf.constant([
                          [11, 12, 13], 
                          [21, 22, 23], 
                          [31, 32, 33], 
                          [41, 42, 43]])    
targets = tf.constant([2, 1, 0, 1])    
batch_nums = tf.range(0, limit=parameters.get_shape().as_list()[0])     
indices = tf.stack((batch_nums, targets), axis=1) # the axis is the dimension number   
items = tf.gather_nd(parameters, indices)  
# which is what we want: [13, 22, 31, 42]

此代码段首先通过 batch_num 找到第一个维度,然后按目标编号沿该维度获取项目。

从 TensorFlow 1.3 开始,tf.gather 有一个 axis 参数,因此不再需要此处的各种解决方法。

https://www.tensorflow.org/versions/r1.3/api_docs/python/tf/gather https://github.com/tensorflow/tensorflow/issues/11223