Tensorflow:用tf声明变量有什么区别.变量并直接声明



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

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 语句工作正常,操作正常。但是,如果我省略 tf。来自 x 和 y 声明的变量,事情变得疯狂:

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 语句和操作仍然一致地执行,但答案是错误的。我不明白为什么答案不同?

当您将变量声明为

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

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

最新更新