我正在尝试在张量流中创建迭代,其中" val"在下面的循环的每次迭代之后增加1。但是这个代码将它增加了2.所以我有两个问题:
1。)为什么会这样? 2.)我应该怎么做才能使它在每次迭代中只添加1?
iters = 10
x = tf.constant(1, dtype=tf.float32, name="X")
y = tf.constant(2, dtype=tf.float32, name="y")
val = tf.Variable(y-x, name="val")
assign_op = tf.assign(val, val+1)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print("val_init",val.eval())
for iter in range(iters):
sess.run(assign_op)
print(iter, x.eval(),y.eval(),"val",val.eval(),"assign_op", assign_op.eval())
"""
val_init 1.0
0 1.0 2.0 val 2.0 assign_op 3.0
1 1.0 2.0 val 4.0 assign_op 5.0
2 1.0 2.0 val 6.0 assign_op 7.0
3 1.0 2.0 val 8.0 assign_op 9.0
4 1.0 2.0 val 10.0 assign_op 11.0
5 1.0 2.0 val 12.0 assign_op 13.0
6 1.0 2.0 val 14.0 assign_op 15.0
7 1.0 2.0 val 16.0 assign_op 17.0
8 1.0 2.0 val 18.0 assign_op 19.0
9 1.0 2.0 val 20.0 assign_op 21.0
"""
答案 0 :(得分:1)
你的“assign_op.eval()”也在增加“val”。所以你每次迭代都要增加两次。你在输出中看到它。
“”“val_init 1.0 0 1.0 2.0 val 2.0 assign_op 3.0 1 1.0 2.0 val 4.0 assign_op < strong> 5.0 2 1.0 2.0 val 6.0 assign_op 7.0 3 1.0 2.0 val 8.0 assign_op 9.0 4 1.0 2.0 val 10.0 assign_op 11.0 5 1.0 2.0 val 12.0 assign_op 13.0 6 1.0 2.0 val 14.0 < / strong> assign_op 15.0 7 1.0 2.0 val 16.0 assign_op 17.0 8 1.0 2.0 val 18.0 assign_op 19.0 9 1.0 2.0 val 20.0 assign_op 21.0 “”“