首页 文章

Tensorflow(Python):如何将标量附加到张量中的每一行

提问于
浏览
0

如果我有一个二维张量,第一个维度是动态的,我怎样才能在每一行的末尾附加一个标量值?

因此,如果我将[[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)

这给了我:ValueError:不能用输入形状连接'concat_3'(op:'ConcatV2')的标量(使用tf.stack代替):[],[?,2],[] .

我认为这需要tf.stack,tf.tile和tf.shape的某种组合,但我似乎无法做到正确 .

1 回答

  • 0

    这是一种方法:

    • 展开要追加的标量张量上的尺寸,使其等级为2 .

    • 使用tf.tile重复行 .

    • 沿最后一个轴连接两个张量 .

    例如:

    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]]}))
    

相关问题