在TensorFlow双射器中使用和修改变量

在TensorFlow Distributions(现称为Probability)的论文中提到,可以使用TensorFlow的Variable来构建BijectorTransformedDistribution对象,例如:

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注