【发布时间】:2019-04-01 20:21:03
【问题描述】:
在 TensorFlow Probability (v0.4.0) 和 PyTorch (v0.4.1) 中,正态分布 (tfp, PyTorch) 和拉普拉斯分布 (tfp, PyTorch) 的 KL 散度都不是t 实现导致抛出 NotImplementedError 错误。
>>> import tensorflow as tf
>>> import tensorflow_probability as tfp
>>> tfd = tfp.distributions
>>> import torch
>>>
>>> tf.__version__
'1.11.0'
>>> tfp.__version__
'0.4.0'
>>> torch.__version__
'0.4.1'
>>>
>>> p = tfd.Normal(loc=0., scale=1.)
>>> q = tfd.Laplace(loc=0., scale=1.)
>>> tfd.kl_divergence(p, q)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/miniconda/envs/example/lib/python3.6/site-packages/tensorflow/python/ops/distributions/kullback_leibler.py", line 95, in kl_divergence
% (type(distribution_a).__name__, type(distribution_b).__name__))
NotImplementedError: No KL(distribution_a || distribution_b) registered for distribution_a type Normal and distribution_b type Laplace
>>>
>>> a = torch.distributions.normal.Normal(loc=0., scale=1.)
>>> b = torch.distributions.laplace.Laplace(loc=0., scale=1.)
>>> torch.distributions.kl.kl_divergence(a,b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/root/miniconda/envs/example/lib/python3.6/site-packages/torch/distributions/kl.py", line 161, in kl_divergence
raise NotImplementedError
NotImplementedError
我假设这两个库都缺少此功能,这是有充分理由的,并且用户应该自己使用 TensorFlow Probability 中的 tfp.distributions.RegisterKL 和 PyTorch 中的 torch.distributions.kl.register_kl 来实现它。
这是正确的假设吗?如果是这样,有人可以解释为什么不对给定的分布类别实施 KL Divergence 吗?我想我错过了一些非常基本的东西。
如果我的假设是错误的,有人可以解释如何正确地让 TensorFlow 和 PyTorch 实现这些操作吗?
如需更多参考,本示例使用与 Edward 配合使用的旧版 TensorFlow,
pip install tensorflow==1.7
pip install edward
在上面这个最小的示例中,我尝试在tfp(或torch)中实现与以下edward 玩具示例代码等效的代码。
import tensorflow as tf
import edward as ed
p = ed.models.Normal(loc=0., scale=1.)
s = tf.Variable(1.)
q = ed.models.Laplace(loc=0., scale=s)
inference = ed.KLqp({p: q})
inference.run(n_iter=5000)
【问题讨论】:
-
不知道关于 TF 或 PyTorch,但由于 KL(p, q) = cross-entropy(p, q) 减去熵(p, p),我想你可能可以从定义。也许像 Maxima (maxima.sourceforge.net) 这样的符号计算系统可以帮助处理积分。
-
@RobertDodier 确实,计算这样的事情是微不足道的。千里马,虽然很好(所以你的工作的道具)甚至不需要。这更像是一个演示更大问题的最小示例。
标签: python tensorflow statistics pytorch tensorflow-probability