问题描述
限时送ChatGPT账号..我定义了一个涉及变量的简单计算图.当我更改变量的值时,它会对计算图的输出产生预期的影响(因此,一切正常,正如预期的那样):
I define a simple computational graph involving a variable. When I change a value of the variable it has an expected influence on the output of the computational graph (so, everything works fine, as expected):
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]})
当我调用此代码时,我得到:
When I call this code I get:
Y1: [ 13. 23. 33.]
Y2: [ 12. 22. 32.]
所以,Y1
和 Y2
后面的值是不同的,正如预期的那样,因为它们是用不同的 c
值计算的.
So, the values after the Y1
and Y2
are different, as expected, because they are calculated with different values of c
.
如果我在定义变量 c
的计算方式之前为其赋值,问题就开始了.在这种情况下,我无法分配 c
的新值.
The problems start if I assign a value to the variable c
before I define how it is involved into calculation of y
. In this case I cannot assign a new value of 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
旧值的结果.这是为什么?
As you can see, each time I calculate y
, I get results involving the old values of c
. Why is that?
推荐答案
使用 TensorFlow,请始终牢记您正在构建一个 计算图.在您的第一个代码片段中,您基本上定义了 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])代码>.
With TensorFlow, always keep in mind that you're building a computation graph. In your first code snippet, you basically define y = tf.placeholder(tf.float32) + tf.Variable([1.0, 1.0, 1.0], tf.float32)
. In your second example, you define y = tf.placeholder(tf.float32) + tf.assign(tf.Variable([1.0, 1.0, 1.0], tf.float32), [4.0, 4.0, 4.0])
.
因此,无论您分配给 c 哪个值,计算图都包含 assign 操作,并将始终分配 [4.0, 4.0, 4.0] 在计算总和之前添加它.
So, no matter which value you assign to c, the computation graph contains the assign operation and will always assign [4.0, 4.0, 4.0] to it before computing the sum.
这篇关于是否允许在变量进入计算图之前为其赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论