2017-06-08 122 views
0

我正在寫一個使用Tensorflow添加和減去兩個數字的小示例程序。但是,如果我將變量聲明爲tf.Variable或直接聲明它,我已經收到了不同的結果。所以我想知道這兩種方法之間有什麼區別,因爲我覺得有一個關於TF的基本知識,我不知道是哪個驅使我發現了這個bug。 這裏是代碼:Tensorflow:聲明一個變量與tf.Variable和直接聲明有什麼區別?

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語句作品的權利,操作都OK。 但是,如果我從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語句和操作仍然執行一致,但答案是錯的。 我不明白爲什麼答案是不同的?

回答

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 

我希望這有助於解釋爲什麼代碼的第二個版本的行爲不同。

+0

哇,謝謝。這很好解釋。 –

相關問題