不知道批量大小的 3-D 批量矩阵乘法

3-D batch matrix multiplication without knowing batch size

我目前正在编写一个 tensorflow 程序,该程序需要将一批 2-D 张量(形状 [None,...] 的 3-D 张量)与 2-D 矩阵 W 相乘。这需要将 W 转换为 3-D 矩阵,这需要知道批量大小。

我没能做到这一点; tf.batch_matmul不再可用,x.get_shape().as_list()[0]returnsNone,对reshaping/tiling操作无效。有什么建议么?我看到有人用 config.cfg.batch_size,但我不知道那是什么。

解决方案是使用 tf.shape (which returns the shape at runtime) and tf.tile 的组合(接受 dynamic 形状)。

x = tf.placeholder(shape=[None, 2, 3], dtype=tf.float32)
W = tf.Variable(initial_value=np.ones([3, 4]), dtype=tf.float32)
print(x.shape)                # Dynamic shape: (?, 2, 3)

batch_size = tf.shape(x)[0]   # A tensor that gets the batch size at runtime
W_expand = tf.expand_dims(W, axis=0)
W_tile = tf.tile(W_expand, multiples=[batch_size, 1, 1])
result = tf.matmul(x, W_tile) # Can multiply now!

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  feed_dict = {x: np.ones([10, 2, 3])}
  print(sess.run(batch_size, feed_dict=feed_dict))    # 10
  print(sess.run(result, feed_dict=feed_dict).shape)  # (10, 2, 4)