我定義了一個涉及變量的簡單計算圖。當我改變變量的值,它的計算圖表的輸出的預期影響(因此,一切工作正常,如預期):在輸入計算圖之前是否允許將值賦給變量?
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.]
因此,Y1
和Y2
之後的值與預期不同,因爲它們使用不同的值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
舊值結果。這是爲什麼?