TensorF中的控制依赖关系

2024-10-05 13:45:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解以下行为:当我运行代码时

import tensorflow as tf

x = tf.Variable(1.0)
y = tf.Variable(0.0)
f = x*x

op0 = tf.assign_add(x, 1.0)
with tf.control_dependencies([op0]):
  op1 = tf.assign(y, f)

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  sess.run(tf.local_variables_initializer())
  sess.run(op1)
  print(y.eval())

结果有时是4.0,但有时是{}。1.0的结果表明依赖项{}被忽略。但是,由于我有时得到4.0op0一定是经过计算的,据我所知,这可能是由依赖关系触发的。在

如果我做类似的事情,但是没有张量f,例如

^{pr2}$

结果总是2.0如预期。在

有人能解释一下为什么第二种情况下的行为是不同的,以及在第一种情况下,x更新后,我如何执行f的评估?在


Tags: run代码importtftensorflowaswith情况
2条回答

您必须确保在第一个赋值发生后计算f。所以:

import tensorflow as tf

x = tf.Variable(1.0)
y = tf.Variable(0.0)

op0 = tf.assign_add(x, 1.0)
with tf.control_dependencies([op0]):
  f = x * x 
op1 = tf.assign(y, f)

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  sess.run(tf.local_variables_initializer())
  sess.run(op1)
  print(y.eval())
  # 4.0

我想我找到了解决办法。在我的应用程序中,我实际计算的是f的梯度,而不是{}本身,因此下面的方法似乎有效:

import tensorflow as tf

x = tf.Variable(1.0)
y = tf.Variable(0.0)
f = x*x
df = tf.gradients(f, x)[0]

op0 = tf.assign_add(x, 1.0)
with tf.control_dependencies([op0]):
  #op1 = tf.assign(y, df) < - does not work
  df_new = tf.gradients(f, x)[0]
  op1 = tf.assign(y, df_new) # < - seems to work

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  sess.run(tf.local_variables_initializer())
  sess.run(op1)
  print(y.eval())

相关问题 更多 >

    热门问题