I wrote simple Poisson model creation code. But PyMC3 produces an error requiring an additional variable inside the model.
The model looks fine. But I am not sure what went wrong.
Code:
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)
Error:
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.
I resolved the issue. The issue was mainly due to the nature of PyMC3 which is very different to PyMC.
The updated code is below.
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)