一個詳細介紹
下面程序要做的是,5次循環,每次循環給x加1,賦值給y,然后打印出來,
x = tf.Variable(0.0) #返回一個op,表示給變量x加1的操作 x_plus_1 = tf.assign_add(x, 1) #control_dependencies的意義是,在執行with包含的內容(在這里就是 y = x)前 #先執行control_dependencies中的內容(在這里就是 x_plus_1) with tf.control_dependencies([x_plus_1]): y = x init = tf.initialize_all_variables() with tf.Session() as session: init.run() for i in xrange(5): print(y.eval())
由於control_dependencies的所以執行print前都會先執行x_plus_1。
這個打印的是0,0,0,0,0 ,也就是說沒有達到我們預期的效果,這是因為此時的y是一個復制了x變量的變量,並未和圖上的節點相聯系不接受流程控制函數的調遣,
改成如下,
import tensorflow as tf x = tf.Variable(0.0) print(x) x_plus_1 = tf.assign_add(x, 1) with tf.control_dependencies([x_plus_1]): y = x + 0.0 print(y) #z=tf.identity(x,name='x') init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init) for i in range(5): print(sess.run(y))
<tf.Variable 'Variable:0' shape=() dtype=float32_ref>
Tensor("add:0", shape=(), dtype=float32)
1.0 2.0 3.0 4.0 5.0
可以看到當y定義為節點的輸出后,就可以順利執行操作了,此時y成為節點的輸出,可以被圖識別。
如果改成這樣:
x = tf.Variable(0.0) x_plus_1 = tf.assign_add(x, 1) with tf.control_dependencies([x_plus_1]): y = tf.identity(x)#修改部分 init = tf.initialize_all_variables() with tf.Session() as session: init.run() for i in range(5): print(y.eval()) This works: it prints 1, 2, 3, 4, 5.
這時候打印的是1,2,3,4,5
解釋:
查詢y為:Tensor("Identity_1:0", shape=(), dtype=float32),和節點聯系起來了。
tf.identity是返回了一個一模一樣新的tensor,再control_dependencies的作用塊下,需要增加一個新節點到gragh中。