繁体   English   中英

在张量流中添加形状一维的两个张量

[英]add two tensor with shape one dimension in 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=(11,), dtype=float32)

因此结果仍然是11而不是12。是我的方法错误还是要添加它们。

从此处的文档中: https : //www.tensorflow.org/api_docs/python/tf/add

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

Returns x + y element-wise.
NOTE: Add supports broadcasting.

这意味着您正在调用的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。 https://www.tensorflow.org/api_docs/python/tf/concat

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.]

听起来您可能想要串联两个张量,所以tf.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)

result张量将具有[12]的形状(即具有12个元素的向量)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM