Tensorflow - 按批量索引对占位符进行分组

Tensorflow - Grouping placeholders by batch index

给定一个网络,其中包含两个或多个不同维度的占位符,例如

x1 = tf.placeholder(tf.int32, [None, seq_len])
x2 = tf.placeholder(tf.int32, [None, seq_len])
xn = tf.placeholder(tf.int32, [None, None, seq_len]

每个占位符中的第一个维度对应于小批量大小。 seq_len 是输入的长度。第二个维度就像一个输入列表,我需要与小批量中每个索引的 x1x2 一起处理。我如何将这些张量分组以按批量索引对它们进行操作?

例如

x1 = [[1, 2, 3], [4, 5, 6]]
x2 = [[7, 8, 9], [8, 7, 6]]
xn = [[[1, 5, 2], [7, 2, 8], [3, 2, 5]], [[8, 9, 8]]]

我需要将x1[0] i.e. [1, 2, 3]x2[0] i.e. [7, 8, 9]xn[0] i.e. [[1, 5, 2], [7, 2, 8], [3, 2, 5]]放在一起,因为我需要在x1[i]和[=19=中的每个元素之间进行矩阵运算] 所有 i.

请注意 xn 的维数是 锯齿状的。

还是不确定我是否理解你的问题。如果我理解正确的话,你的挑战来自 xn 维数的参差不齐的本质。我有以下方法 "unrolling" 沿批次索引。结果是一个大小为batch_size的数组;数组中的每个元素都是一个张量。当然,您可以在评估所有这些单独的张量之前对它们执行其他操作。

我必须使用tf.scanxn[i]的每个元素执行操作,因为它的第一个维度是动态的。不过可能存在更好的解决方案。

x1 = np.array([[1, 2, 3]])
xn = np.array([[[1, 5, 2], [7, 2, 8], [3, 2, 5]]])

batch_size = x1.shape[0]

result = []
for batch_idx in range(batch_size):
  x1_i = x1[batch_idx]
  xn_i = xn[batch_idx]
  result.append(tf.scan(fn=lambda a, x: x * x1_i, elems=xn_i, initializer=x1_i))
with tf.Session() as sess:
  print sess.run([result[0]])

# result, this is x1[0] multiply each element in xn[0] for all i (element-wise). 
# free free to plug in your own matrix operations in the `fn` arg of `tf.scan`.
  [array([[ 1,  10, 6],
          [ 7,  4, 24],
          [ 3,  4, 15]])]