在TensorFlow Distributions(现称为Probability)的论文中提到,可以使用TensorFlow的Variable
来构建Bijector
和TransformedDistribution
对象,例如:
import tensorflow as tfimport tensorflow_probability as tfptfd = tfp.distributionstf.enable_eager_execution()shift = tf.Variable(1., dtype=tf.float32)myBij = tfp.bijectors.Affine(shift=shift)# 以零为中心的正态分布,然后使用双射将其移到1myDistr = tfd.TransformedDistribution( distribution=tfd.Normal(loc=0., scale=1.), bijector=myBij, name="test")# 以1为中心的正态分布的2个样本:y = myDistr.sample(2)# 通过myBij的逆变换获得以0为中心的正态分布的2个样本:x = myBij.inverse(y)
现在我想修改shift变量(例如,我可能会计算某个似然函数关于shift的梯度并更新其值),所以我做了以下操作:
shift.assign(2.)gx = myBij.forward(x)
我期望gx=y+1
,但我看到gx=y
… 实际上,myBij.shift
仍然等于1
。
如果我尝试直接修改双射器,即:
myBij.shift.assign(2.)
我会得到
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
计算梯度也未按预期工作:
with tf.GradientTape() as tape: gx = myBij.forward(x)grad = tape.gradient(gx, shift)
结果为None
,并且脚本结束时还抛出以下异常:
Exception ignored in: <bound method GradientTape.__del__ of <tensorflow.python.eager.backprop.GradientTape object at 0x7f529c4702e8>>Traceback (most recent call last):File "~/.local/lib/python3.6/site-packages/tensorflow/python/eager/backprop.py", line 765, in __del__AttributeError: 'NoneType' object has no attribute 'context'
我在这里错过了什么?
编辑:我在图/会话中成功运行了它,所以似乎是急切执行的问题…
注意:我使用的是TensorFlow版本1.12.0和tensorflow_probability版本0.5.0
回答:
如果您使用的是急切模式,您需要从变量开始重新计算所有内容。最好将此逻辑捕获在一个函数中;
import tensorflow as tfimport tensorflow_probability as tfptfd = tfp.distributionstf.enable_eager_execution()shift = tf.Variable(1., dtype=tf.float32)def f(): myBij = tfp.bijectors.Affine(shift=shift) # 以零为中心的正态分布,然后使用双射将其移到1 myDistr = tfd.TransformedDistribution( distribution=tfd.Normal(loc=0., scale=1.), bijector=myBij, name="test") # 以1为中心的正态分布的2个样本: y = myDistr.sample(2) # 通过myBij的逆变换获得以0为中心的正态分布的2个样本: x = myBij.inverse(y) return x, yx, y = f()shift.assign(2.)gx, _ = f()
关于梯度,您需要将对f()
的调用包装在GradientTape
中