如果我有一个第一个维度是动态的二维张量,如何将标量值附加到每行的末尾?
因此,如果我将 [[1,2], [3,4]] 提供给张量,我想让它成为 [[1,2,5], [3,4,5]]。
示例(不起作用):
a = tf.placeholder(tf.int32, shape=[None, 2])
b = tf.concat([tf.constant(5), a], axis=1)
Run Code Online (Sandbox Code Playgroud)
这给了我: ValueError: Can't concatenate scalars (use tf.stack 相反) for 'concat_3' (op: 'ConcatV2') with input shape: [], [?,2], [].
我认为这需要 tf.stack、tf.tile 和 tf.shape 的某种组合,但我似乎无法正确理解。
这是一种方法:
例如:
import tensorflow as tf
a = tf.placeholder(tf.int32, shape=[None, 2])
c = tf.constant(5)[None, None] # Expand dims. Shape=(1, 1)
c = tf.tile(c, [tf.shape(a)[0], 1]) # Repeat rows. Shape=(tf.shape(a)[0], 1)
b = tf.concat([a, c], axis=1)
with tf.Session() as sess:
print(sess.run(b, feed_dict={a: [[1, 2], [3, 4]]}))
Run Code Online (Sandbox Code Playgroud)