【发布时间】:2016-09-02 17:19:11
【问题描述】:
我正在尝试使用 pymc3 定义一个复杂的自定义似然函数。似然函数涉及大量迭代,因此我尝试使用 theano 的 scan 方法直接在 theano 中定义迭代。这是一个非常简化的示例,说明了我面临的挑战。我试图定义的(假)似然函数只是两个 pymc3 随机变量 p 和 theta 的总和。当然,我可以简单地返回 p+theta,但我要编写的实际似然函数更复杂,而且我认为我需要使用 theano.scan,因为它涉及大量迭代。
import pymc3 as pm
from pymc3 import Model, Uniform, DensityDist
import theano.tensor as T
import theano
import numpy as np
### theano test
theano.config.compute_test_value = 'raise'
X = np.asarray([[1.0,2.0,3.0],[1.0,2.0,3.0]])
### pymc3 implementation
with Model() as bg_model:
p = pm.Uniform('p', lower = 0, upper = 1)
theta = pm.Uniform('theta', lower = 0, upper = .2)
def logp(X):
f = p+theta
print("f",f)
get_ll = theano.function(name='get_ll',inputs = [p, theta], outputs = f)
print("p keys ",p.__dict__.keys())
print("theta keys ",theta.__dict__.keys())
print("p name ",p.name,"p.type ",p.type,"type(p)",type(p),"p.tag",p.tag)
result=get_ll(p, theta)
print("result",result)
return result
y = pm.DensityDist('y', logp, observed = X) # Nx4 y = f(f,x,tx,n | p, theta)
当我运行它时,我得到了错误:
TypeError: ('Bad input argument to theano function with name "get_ll" at index 0(0-based)', 'Expected an array-like object, but found a Variable: maybe you are trying to call a function on a (possibly shared) variable instead of a numeric array?')
我了解问题发生在一行中 结果=get_ll(p, theta)
因为 p 和 theta 是 pymc3.TransformedRV 类型,并且 theano 函数的输入需要是简单 numpy 数组的标量数。但是,pymc3 TransformedRV 似乎没有任何明显的方法来获取随机变量本身的当前值。
是否可以定义一个对数似然函数,该函数涉及使用将 pymc3 随机变量作为输入的 theano 函数?
【问题讨论】:
-
您是否已经在PyMC3 repository 中搜索过示例?