Python 如何在TensorFlow中将值分配给变量和计算图?

Python 如何在TensorFlow中将值分配给变量和计算图?,python,tensorflow,theano,Python,Tensorflow,Theano,我想在TensorFlow中复制以下简单的Theano代码: import theano as th import theano.tensor as T import numpy as np x = T.vector() c = th.shared(np.array([1.0, 2.0])) y1 = x + c c.set_value(np.array([10.0, 20.0])) y2 = x + c c.set_value(np.array([100.0, 200.0])) print

我想在TensorFlow中复制以下简单的Theano代码:

import theano as th
import theano.tensor as T
import numpy as np

x = T.vector()
c = th.shared(np.array([1.0, 2.0]))
y1 = x + c
c.set_value(np.array([10.0, 20.0]))
y2 = x + c
c.set_value(np.array([100.0, 200.0]))
print 'Y1:', th.function([x],y1)([0.0, 0.0])
print 'Y2:', th.function([x],y2)([0.0, 0.0])
import tensorflow as tf

s = tf.Session()
x = tf.placeholder(tf.float32)
c = tf.Variable([1.0, 2.0])
y1 = x + c
c = tf.assign(c, [10.0, 20.0])
s.run(c)
y2 = x + c
c = tf.assign(c, [100.0, 200.0])
s.run(c)
print 'Y1:', s.run(y1, feed_dict = {x : [0.0, 0.0]})
print 'Y2:', s.run(y2, feed_dict = {x : [0.0, 0.0]})
在上面的代码中,我定义了两个符号变量(
y1
y2
),它们以相同的方式依赖于
x
c
)。每个时间点的共享变量
c
都有一个值。每当我计算
y1
y2
时,我总是得到与
c
的当前值对应的相同值

现在我试着在TensorFlow中重现它:

import theano as th
import theano.tensor as T
import numpy as np

x = T.vector()
c = th.shared(np.array([1.0, 2.0]))
y1 = x + c
c.set_value(np.array([10.0, 20.0]))
y2 = x + c
c.set_value(np.array([100.0, 200.0]))
print 'Y1:', th.function([x],y1)([0.0, 0.0])
print 'Y2:', th.function([x],y2)([0.0, 0.0])
import tensorflow as tf

s = tf.Session()
x = tf.placeholder(tf.float32)
c = tf.Variable([1.0, 2.0])
y1 = x + c
c = tf.assign(c, [10.0, 20.0])
s.run(c)
y2 = x + c
c = tf.assign(c, [100.0, 200.0])
s.run(c)
print 'Y1:', s.run(y1, feed_dict = {x : [0.0, 0.0]})
print 'Y2:', s.run(y2, feed_dict = {x : [0.0, 0.0]})
从第一个角度来看,代码的结构是相同的(只是语法不同)。然而,行为是不同的。作为此代码的输出,我得到:

Y1: [ 100.  200.]
Y2: [ 10.  20.]
y1
y2
的不同值的原因我很清楚:对
c
的第一次赋值(
c=tf.assign(c,[10.0,20.0])
)是在定义
y2
之前完成的,因此该赋值成为
y2
计算图的一部分

因此,现在我的问题是,在TensorFlow中,是否有可能在不将赋值作为我稍后定义的所有符号变量的计算图的一部分的情况下,将值设置为
变量


换句话说,我想构建一个计算图(在上面的例子中是用于
y2
)这将获取变量
c
的当前值,并忽略在定义
y2
之前对
c
所做的所有赋值。

您不应该用赋值操作覆盖Python变量c。只需运行如下相应的赋值操作,即可将新值赋值给c:

s = tf.Session()
x = tf.placeholder(tf.float32)
c = tf.Variable([1.0, 2.0])
y1 = x + c
s.run(tf.assign(c, [10.0, 20.0]))
y2 = x + c
s.run(tf.assign(c, [100.0, 200.0]))

print 'Y1:', s.run(y1, feed_dict = {x : [0.0, 0.0]})  # Y1: [ 100.  200.]
print 'Y2:', s.run(y2, feed_dict = {x : [0.0, 0.0]})  # Y2: [ 100.  200.]
如果出于某种原因,您希望将赋值操作存储在变量中,只需给它另一个名称:

s = tf.Session()
x = tf.placeholder(tf.float32)
c = tf.Variable([1.0, 2.0])
y1 = x + c
a = tf.assign(c, [10.0, 20.0])
s.run(a)
y2 = x + c
a = tf.assign(c, [100.0, 200.0])
s.run(a)
print 'Y1:', s.run(y1, feed_dict = {x : [0.0, 0.0]})  # Y1: [ 100.  200.]
print 'Y2:', s.run(y2, feed_dict = {x : [0.0, 0.0]})  # Y2: [ 100.  200.]
请注意,在这两种情况下,
tf.assign(c[10.0,20.0])
都是多余的,因为它将立即被新值覆盖-我不确定我是否正确理解了您的问题,因此请随时进一步阐述您的问题