In Dan-Foreman Mackey’s recent modeling package built on top of PyMC3 there’s a helpful function called
eval_in_model
for evaluating variables in a PyMC3 model given some values of the parameters:
https://exoplanet.dfm.io/en/latest/tutorials/pymc3-extras/#evaluating-model-components-for-specific-samples
I would like to have the model in a separate function or class and be able to evaluate it after sampling but I’ m not sure how to do that. I modified Dan’s example to
def model():
with pm.Model() as model:
logs = pm.Normal("logs", mu=-3.0, sd=1.0)
a0 = pm.Normal("a0")
a1 = pm.Normal("a1")
a2 = pm.Normal("a2")
mod = a0 + a1 * x + a2 * x**2
# Sample from the prior
prior_sample = pm.sample_prior_predictive(samples=1)
y = xo.eval_in_model(mod, prior_sample)
y += np.exp(prior_sample["logs"]) * np.random.randn(len(y))
# Add the likelihood
pm.Normal("obs", mu=mod, sd=pm.math.exp(logs), observed=y)
return model
with model():
# Fit the data
map_soln = pm.find_MAP()
trace = pm.sample()
x_grid = np.linspace(-1.1, 1.1, 5000)
with model():
pred = xo.eval_in_model(a0 + a1 * x_grid + a2 * x_grid**2, map_soln)
but I’m getting an error:
NameError: name 'a0' is not defined
What am I doing wrong?