TensorFlow使用向量连接一个可变大小的占位符

bxs*_*shi 14 concat tensorflow

假设我有一个占位符

ph_input = tf.placeholder(dtype=tf.int32, [None, 1])

和一个矢量

h = tf.zeros([1,2], dtype=tf.int32)

在这个例子h中为了简单起见用零填充,但在实际情况下,它将被其他变量改变,并且将具有不同的值.

我想有效地做一个concaton ph_inputand hon维度1并获得一个新的张量形状[None, 1+2].不幸的是,concat除了concat_dim我的例子不符合之外,所有输入张量都需要具有相同的形状.

我正在考虑扩展h到与提供的数据相同的形状,ph_input但我不确定如何使用占位符本身.如果我直接从输入数据中获取形状,那么我想没有必要使用占位符.

mrr*_*rry 16

最通用的解决方案是使用tf.shape()op获取占位符的运行时大小,并将tf.tile()op扩展h为适当的大小:

ph_input = tf.placeholder(dtype=tf.int32, shape=[None, 1])
h = tf.zeros([1, 2], dtype=tf.int32)  # ...or some other tensor of shape [1, 2]

# Get the number of rows in the fed value at run-time.
ph_num_rows = tf.shape(ph_input)[0]

# Makes a `ph_num_rows x 2` matrix, by tiling `h` along the row dimension.
h_tiled = tf.tile(h, tf.pack([ph_num_rows, 1]))

result = tf.concat(1, [ph_input, h_tiled])
Run Code Online (Sandbox Code Playgroud)

  • pack已重命名为stack! (3认同)