PyMC3 在 Possion 模型创建过程中产生错误

PyMC3 generates error during Possion model creation

我写了简单的泊松模型创建代码。但是 PyMC3 会产生一个错误,需要在模型中添加一个额外的变量。

模型看起来不错。但是我不确定哪里出了问题。

代码:

with pm.Model() as model:

    lambda_1 = pm.Exponential('lambda_1', alpha) # create stochastic    variable
    lambda_2 = pm.Exponential('lambda_2', alpha) #create stochastic variable

    tau = pm.DiscreteUniform("tau", lower=0, upper=size)
    print("Random output:", tau.random(), tau.random(), tau.random())


    def lambda_ (tau=tau, lambda_1 = lambda_1, lambda_2 = lambda_2):
       out = np.zeros(size)
       out[:tau] = lambda_1
       out[tau:] = lambda_2

       return out

   observation = pm.Poisson("obs", lambda_, lambda_value = textfile,    observed=True)

   model = pm.Model(observation, lambda_1, lambda_2, tau)

错误:

File "", line 1, in
runfile('/home/saul/pythonWork/textmessageAnalysis.py', wdir='/home/saul/pythonWork')

File "/home/saul/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 786, in runfile execfile(filename, namespace)

File "/home/saul/anaconda3/lib/python3.7/site-packages/spyder_kernels/customize/spydercustomize.py", line 110, in execfile exec(compile(f.read(), filename, 'exec'), namespace)

File "/home/saul/pythonWork/textmessageAnalysis.py", line 51, in observation = pm.Poisson("obs", lambda_, lambda_value = textfile, observed=True)

File "/home/saul/.local/lib/python3.7/site-packages/pymc3/distributions/distribution.py", line 31, in new raise TypeError("No model on context stack, which is needed to "

TypeError: No model on context stack, which is needed to instantiate distributions. Add variable inside a 'with model:' block, or use the '.dist' syntax for a standalone distribution.

我解决了这个问题。该问题主要是由于 PyMC3 的性质与 PyMC 有很大不同。

更新后的代码如下。

n_data_points = size   
idx = np.arange(n_data_points)
with model:
    lambda_ = pm.math.switch(tau >= idx, lambda_1, lambda_2)            


with model:
    obs = pm.Poisson("obs", lambda_, observed=textfile)
print(obs.tag.test_value)

model = pm.Model([obs, lambda_1, lambda_2, tau])
print(model)