TensorFlow 用向量连接一个可变大小的占位符
TensorFlow concat a variable-sized placeholder with a vector
假设我有一个占位符
ph_input = tf.placeholder(dtype=tf.int32, [None, 1])
和一个向量
h = tf.zeros([1,2], dtype=tf.int32)
在此示例中,为简单起见,h
填充为零,但在实际情况下,它会被其他变量更改并具有不同的值。
我想高效地在 ph_input
上执行 concat
并在维度 1
上执行 h
并获得形状为 [None, 1+2]
的新张量。不幸的是 concat
需要所有输入张量具有相同的形状,除了 concat_dim
,我的示例不满足。
我正在考虑将 h
扩展为与提供给 ph_input
的数据相同的形状,但我不确定如何使用占位符本身来实现。如果我直接从输入数据中获取形状,那么我想没有必要使用占位符。
最通用的解决方案是使用 tf.shape()
op to get the run-time size of the placeholder, and the tf.tile()
操作将 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])
假设我有一个占位符
ph_input = tf.placeholder(dtype=tf.int32, [None, 1])
和一个向量
h = tf.zeros([1,2], dtype=tf.int32)
在此示例中,为简单起见,h
填充为零,但在实际情况下,它会被其他变量更改并具有不同的值。
我想高效地在 ph_input
上执行 concat
并在维度 1
上执行 h
并获得形状为 [None, 1+2]
的新张量。不幸的是 concat
需要所有输入张量具有相同的形状,除了 concat_dim
,我的示例不满足。
我正在考虑将 h
扩展为与提供给 ph_input
的数据相同的形状,但我不确定如何使用占位符本身来实现。如果我直接从输入数据中获取形状,那么我想没有必要使用占位符。
最通用的解决方案是使用 tf.shape()
op to get the run-time size of the placeholder, and the tf.tile()
操作将 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])