如何在 PyMC3 中定义自定义似然?在 PyMC2 中,我可以使用 @pymc.potential
.我尝试使用 pymc.Potential
然而,在 PyMC3 中,似乎 bool 运算不能应用于参数(当我这样做时,我收到类似 this 的错误)。例如,以下代码不起作用:
from pymc import *
with Model() as model:
x = Normal('x', 1, 1)
def z(u):
if u > 0: #comparisons like this are not supported
# if theano.tensor.lt(0,u): this is how comparison should be done
return u ** 2
return -u**3
x2 = Potential('x2', z(x))
start = model.test_point
h = find_hessian(start)
step = Metropolis(model.vars, h)
sample(100, step, start)
我不可能将似然内的所有比较更改为 Theano 语法(即 theano.tensor.{lt,le,eq,neq,gt,ge})。反正有没有使用定义类似于 PyMC2 的似然函数?
最佳答案
您需要使用 DensityDist
函数来包装你的对数似然。从与源捆绑的示例中:
with Model() as model:
lam = Exponential('lam', 1)
failure = np.array([0, 1])
value = np.array([1, 0])
def logp(failure, value):
return sum(failure * log(lam) - lam * value)
x = DensityDist('x', logp, observed=(failure, value))
您可以使用
@theano.compile.ops.as_op
进行任意非 Theano 确定性。装饰器,但对于随机指标来说并不那么容易。
关于pymc - pymc3 中的自定义可能性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27545420/