下面的程序想要执行5
次循环,每次循环给x
加1
并赋值给y
,然后打印出来:
import tensorflow as tf
x = tf.Variable(0.0)
x_plus_1 = tf.assign_add(x, 1) # 返回一个op,表示给变量x加1的操作
with tf.control_dependencies([x_plus_1]):
y = x
init = tf.global_variables_initializer()
with tf.Session() as session:
init.run()
for i in range(5):
print(y.eval())
打印出的结果都是0.0
,也就是说没有达到预期的效果。这是因为y
只是复制了x
变量内容,并未和tensorflow
图上的节点相联系,不能执行节点上的操作。进行如下修改就能实现需要的功能:
import tensorflow as tf
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.global_variables_initializer()
with tf.Session() as session:
init.run()
for i in range(5):
print(y.eval())
也就是说,tf.identity
返回了一个和x
相同的的新tensor
。