Extracting posterior draws with pymc

I want to extract the posterior draws after fitting a model using PyMC, but for some reason I cannot find the answer when I google “extracting posterior draws pymc”. The same search for Stan gives you a perfect answer: Extract posterior draws — fit-method-draws • cmdstanr

Is it not possible to extract posterior draws with pymc?

I would really appreciate it if you could share a reference or a vignette on extracting posterior draws with pymc.

By default results are stored in an ArviZ’s InferenceData object, which has potentially many groups storing different data, including posterior samples, posterior predictive samples, the loglikelihood etc. To retrieve the posterior you can do something like.

with pm.Model() as model:
    # your model
    idata = pm.sample()

idata.posterior
2 Likes

Thanks @aloctavodia. I want to be able to create prediction lines, for a simple problem of y ~ N(mu, sigma), mu = alpha + beta * x, using draws of mu for each x in my dataset. I was wondering if there is a vignette showing how to do that with pymc so I can save some time instead of fiddling with the InferenceData object to figure that out?

In RStan I can do it quickly using as_draws_df(fit$draws("mu")). I’m looking for a similar solution in pymc.

Bambi can compute the mean of the linear predictor automatically. With PyMC you will need to extract the values of alpha and beta from the InfenceData object, see GLM: Linear regression — PyMC 4.1.7 documentation

Additionally you can define a deterministic variable as part of your model something like.

mu = pm.Deterministic("mu", alpha + beta*x)

1 Like