Tensorflow:使用tf.Variable声明变量和直接声明之间的区别是什么?

时间:2017-06-08 16:04:04

标签: python tensorflow

我正在编写一个使用Tensorflow添加和减去两个数字的小样本程序。但是,如果我将变量声明为tf.Variable或直接声明它,我收到了不同的结果。所以我想知道两种方式之间有什么区别,因为我觉得有一个关于TF的基本知识,我还不知道是什么驱使我走向这个bug。 以下是代码:

x= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
y= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
#declare 2 tf variables with initial value randomly generated.

# A 'case' statement to perform either addition or subtraction
out = tf.case({tf.less(x, y): lambda: tf.add(x, y), tf.greater(x, y): lambda: tf.subtract(x, y)}, default= lambda: tf.zeros([]), exclusive= True)

#Run the graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    x_value = x.eval()
    y_value = y.eval()
    print("{}\n".format(x_value - y_value))
    out_value, sub_value, add_value = sess.run([out, subtf, addtf])

#Example output: x_value = 0.53607559
                 y_value = -0.63836479
                 add_value = -0.1022892
                 sub_value = 1.1744404
                 out_value = 1.1744404

如您所见,case语句正常,操作正常。 但是,如果我从x和y的声明中省略了tf.Variable,那么事情就变得狂野了:

x= tf.random_uniform([], minval= -1, maxval= 1)
y= tf.random_uniform([], minval= -1, maxval= 1)
.... All the same as above

#Sample answer run on Spyder: x_value = -0.91663623
                              y_value = -0.80014014
                              add_value = 0.26550484 , should be =-1.71677637
                              sub_value = -0.19451094, should be -0.11649609
                              out_value = 0.26550484, , should be =-1.71677637

如您所见,case语句和操作仍然执行一致,但答案是错误的。 我不明白为什么答案不同?

1 个答案:

答案 0 :(得分:2)

中声明变量时
x_var = tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))

随机值存储在变量中,除非通过赋值操作进行更改。

或者,声明

x_op = tf.random_uniform([], minval= -1, maxval= 1)

定义了每次调用时生成新随机数的操作。

例如:

# After calling
sess.run(tf.global_variables_initializer())

sess.run(x_var) # Will return the same randomly generated value every time
sess.run(x_op) # Will return a different random value every time

我希望这有助于解释为什么第二版代码的行为方式不同。