Python 在tensorflow中添加两个形状为一维的张量

Python 在tensorflow中添加两个形状为一维的张量,python,tensorflow,Python,Tensorflow,你好,我是tensorflow的新手,我正在尝试添加两个一维形状的张量,实际上,当我打印出来时,没有添加任何内容,例如: num_classes = 11 v1 = tf.Variable(tf.constant(1.0, shape=[num_classes])) v2 = tf.Variable(tf.constant(1.0, shape=[1])) result = tf.add(v1 , v2) 这就是我打印出来的结果 result Tensor("Add:0", shape=

你好,我是tensorflow的新手,我正在尝试添加两个一维形状的张量,实际上,当我打印出来时,没有添加任何内容,例如:

num_classes = 11

v1 = tf.Variable(tf.constant(1.0, shape=[num_classes]))
v2 = tf.Variable(tf.constant(1.0, shape=[1]))

result = tf.add(v1 ,  v2)
这就是我打印出来的结果

result Tensor("Add:0", shape=(11,), dtype=float32)

所以结果仍然是11而不是12。是我的方法错了,还是有其他方法可以添加它们。

来自此处的文档:

tf.add(x,y,name=None)

这意味着您正在调用的add函数将迭代v1中的每一行,并在其上广播v2。它不会像您期望的那样附加列表,相反,可能发生的情况是v2的值将被添加到v1的每一行

因此Tensorflow正在这样做:

sess = tf.Session()
c1 = tf.constant(1.0, shape=[1])
c2 = tf.constant(1.0, shape=[11])
result = (tf.add(c1, c2))
output = sess.run(result)
print(output) # [ 2.  2.  2.  2.  2.  2.  2.  2.  2.  2.  2.]
如果希望输出形状12,则应使用concat。


听起来您可能想要连接两个张量,因此op可能就是您想要使用的:

num_classes = 11
v1 = tf.Variable(tf.constant(1.0, shape=[num_classes]))
v2 = tf.Variable(tf.constant(1.0, shape=[1]))

result = tf.concat([v1, v2], axis=0)
结果
张量的形状为
[12]
(即一个包含12个元素的向量)

sess = tf.Session()
c1 = tf.constant(1.0, shape=[1])
c2 = tf.constant(1.0, shape=[11])
result = (tf.concat([c1, c2], axis=0))
output = sess.run(result)
print(output) # [ 1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
num_classes = 11
v1 = tf.Variable(tf.constant(1.0, shape=[num_classes]))
v2 = tf.Variable(tf.constant(1.0, shape=[1]))

result = tf.concat([v1, v2], axis=0)