2017-03-21 51 views
1

喂我在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,是我的错路或者有另一种方式来添加。

回答

0

这听起来像你可能会想连击两个张量,所以tf.concat()运可能是你想要的内容:

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个元素的向量)。

1

从文档浏览:https://www.tensorflow.org/api_docs/python/tf/add

tf.add(X,Y,名=无)

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

谢谢现在很清楚:) –

相关问题