gpt4 book ai didi

python - 强制依赖变量更新

转载 作者:太空宇宙 更新时间:2023-11-04 03:17:41 25 4
gpt4 key购买 nike

假设我有一些变量 x 的函数 f:

x = tf.Variable(1.0)
fx = x*x

和更新 x 的操作:

new_x = x.assign(2.0)

并且我想从更新后的 x 中获取 f 的值。我本来以为

with tf.control_dependencies([new_x,]):
new_fx = tf.identity(fx)

会强制 new_fx 依赖于更新 new_x,但情况似乎并非如此:

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

# prints 1.0, expected 4.0
print "new fx", sess.run(new_fx)

是否有其他方法来定义 fx 的更新值?

显然,我可以通过编写类似 new_fx = new_x * new_x 的内容来创建一个新的独立副本,但这会增大图形大小,并且还需要访问 fx 的定义>,我更愿意将其视为黑匣子。

编辑:为了激发这一点,这是我要编写的代码草图:

# Hamiltonian Monte Carlo update, simplified
def hmc_step(x, momentum, logpdf, n_steps=50):
# x and momentum are Variables
# logpdf is a Tensor with potentially complicated dependence on x

grad = tf.gradients(logpdf, x)[0]

# initial position
new_x = x

for i in range(n_steps):
# update position
new_x = x.assign(new_x + momentum)

# update momentum using gradient at *current* position
with tf.control_dependencies([new_x]):
momentum = momentum + grad # DOESN'T WORK

# DOES WORK BUT IS UGLY
# new_logpdf = define_logpdf(new_x)
# new_grad = tf.gradients(new_logpdf, new_x)[0]
# momentum = momentum + new_grad

# (do some stuff to accept/reject the new x)
# ....

return new_x

每次通过循环定义一个新的 logpdf 副本并重新导出梯度感觉真的很不优雅:它需要访问 define_logpdf() 并将图形大小放大 50 倍。有没有更好的方法来做到这一点(除非有一些等同的 theano.scan)?

最佳答案

with tf.control_dependencies([op]) block 将对 op 的控制依赖性强加给 with block 内 创建 的其他操作。在您的情况下, x*x 是在外部创建的,而 tf.identity 只是获取旧值。这是你想要的:

with tf.control_dependencies([new_x,]):
new_fx = x*x

关于python - 强制依赖变量更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35693687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com