首页 文章

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

提问于
浏览
12

假设我有一个占位符

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

和一个矢量

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

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

我希望在维 1 上有效地对 ph_inputh 进行 concat 并得到一个形状为 [None, 1+2] 的新张量 . 不幸的是 concat 需要所有输入张量具有相同的形状,除了 concat_dim ,我的例子不符合 .

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

1 回答

  • 14

    最通用的解决方案是使用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])
    

相关问题