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語句和操作仍然執行一致,但答案是錯的。 我不明白爲什麼答案是不同的?
哇,謝謝。這很好解釋。 –