說我有可變x
的一些功能f
:一個變量更新強制依賴
x = tf.Variable(1.0)
fx = x*x
和更新x
運算:
new_x = x.assign(2.0)
,我想帶來的的f
值從更新的x
。我原以爲
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)?
你可以做'sess.run([一個new_x])'之後'sess.run([other_stuff])',它保證'new_x'之前'other_stuff'評估 –
對。這也不是理想的,因爲它將更新邏輯推送到運行時Python代碼中,當我想要在TF操作系統中聲明性地封裝和表示聲音時,但它聽起來像我想要的可能只是不可能,所以這是我的選擇之一會考慮的。謝謝! – davmre