2017-03-21 52 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

謝謝現在很清楚:) –

相關問題