2017-10-04 51 views
0

我定義了一個涉及變量的簡單計算圖。當我改變變量的值,它的計算圖表的輸出的預期影響(因此,一切工作正常,如預期):在輸入計算圖之前是否允許將值賦給變量?

s = tf.Session() 

x = tf.placeholder(tf.float32) 
c = tf.Variable([1.0, 1.0, 1.0], tf.float32) 

y = x + c 

c = tf.assign(c, [3.0, 3.0, 3.0]) 
s.run(c) 
print 'Y1:', s.run(y, {x : [10.0, 20.0, 30.0]}) 

c = tf.assign(c, [2.0, 2.0, 2.0]) 
s.run(c) 
print 'Y2:', s.run(y, {x : [10.0, 20.0, 30.0]}) 

當我把這個代碼我得到:

Y1: [ 13. 23. 33.] 
Y2: [ 12. 22. 32.] 

因此,Y1Y2之後的值與預期不同,因爲它們使用不同的值c進行計算。

如果我在定義y的計算方式之前如何將變量c賦值給變量,則會出現問題。在這種情況下,我不能分配一個新的值c

s = tf.Session() 

x = tf.placeholder(tf.float32) 
c = tf.Variable([1.0, 1.0, 1.0], tf.float32) 

c = tf.assign(c, [4.0, 4.0, 4.0]) # this is the line that causes problems 
y = x + c 

c = tf.assign(c, [3.0, 3.0, 3.0]) 
s.run(c) 
print 'Y1:', s.run(y, {x : [10.0, 20.0, 30.0]}) 

c = tf.assign(c, [2.0, 2.0, 2.0]) 
s.run(c) 
print 'Y2:', s.run(y, {x : [10.0, 20.0, 30.0]}) 

當輸出我得到:

Y1: [ 14. 24. 34.] 
Y2: [ 14. 24. 34.] 

正如你所看到的,每個我計算y時間,我得到涉及c舊值結果。這是爲什麼?

回答

1

隨着TensorFlow,請始終記住,您正在構建一個computation graph。在你的第一個代碼片段中,你基本上定義了y = tf.placeholder(tf.float32) + tf.Variable([1.0, 1.0, 1.0], tf.float32)。在你的第二個例子中,你定義了y = tf.placeholder(tf.float32) + tf.assign(tf.Variable([1.0, 1.0, 1.0], tf.float32), [4.0, 4.0, 4.0])

所以,不管哪個值分配給ç,計算圖包含分配操作,將計算的總和之前始終分配[4.0,4.0,4.0]它。

1

我想這是因爲你定義權,並添加操作y = x + cc = tf.assign(c, [4.0, 4.0, 4.0]),所以每次運行y出來,這c = tf.assign(c, [4.0, 4.0, 4.0])運算將始終excuted雖然其他分配操作也將excuted但不影響最終的結果。