# Prior and Posterior Predictive Checks¶

Posterior predictive checks (PPCs) are a great way to validate a model. The idea is to generate data from the model using parameters from draws from the posterior.

Elaborating slightly, one can say that PPCs analyze the degree to which data generated from the model deviate from data generated from the true distribution. So, often you will want to know if, for example, your posterior distribution is approximating your underlying distribution. The visualization aspect of this model evaluation method is also great for a ‘sense check’ or explaining your model to others and getting criticism.

Prior predictive checks are also a crucial part of the Bayesian modeling workflow. Basically, they have two main benefits:

• They allow you to check whether you are indeed incorporating scientific knowledge into your model – in short, they help you check how credible your assumptions before seeing the data are.

• They can help sampling considerably, especially for generalized linear models, where the outcome space and the parameter space diverge because of the link function.

Here, we will implement a general routine to draw samples from the observed nodes of a model. The models are basic but they will be a steppingstone for creating your own routines. If you want to see how to do prior and posterior predictive checks in a more complex, multidimensional model, you can check this notebook. Now, let’s sample!

[1]:

import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pymc3 as pm

from scipy.special import expit as logistic

RANDOM_SEED = 58

WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.

[2]:

az.style.use("arviz-darkgrid")

def standardize(series):
"""Standardize a pandas series"""
return (series - series.mean()) / series.std()


Lets generate a very simple linear regression model. On purpose, I’ll simulate data that don’t come from a standard Normal (you’ll see why later):

[3]:

N = 100

true_a, true_b, predictor = 0.5, 3.0, np.random.normal(loc=2, scale=6, size=N)
true_mu = true_a + true_b * predictor
true_sd = 2.0

outcome = np.random.normal(loc=true_mu, scale=true_sd, size=N)

f"{predictor.mean():.2f}, {predictor.std():.2f}, {outcome.mean():.2f}, {outcome.std():.2f}"

[3]:

'1.72, 5.52, 5.57, 16.48'


As you can see, variation in our predictor and outcome are quite high – which is often the case with real data. And sometimes, the sampler won’t like this – and you don’t want to make the sampler angry when you’re a Bayesian… So, let’s do what you’ll often have to do with real data: standardize! This way, our predictor and outcome will have a mean of 0 and std of 1, and the sampler will be much, much happier:

[4]:

predictor_scaled = standardize(predictor)
outcome_scaled = standardize(outcome)

f"{predictor_scaled.mean():.2f}, {predictor_scaled.std():.2f}, {outcome_scaled.mean():.2f}, {outcome_scaled.std():.2f}"

[4]:

'0.00, 1.00, -0.00, 1.00'


And now, let’s write the model with conventional flat priors and sample prior predictive samples:

[5]:

with pm.Model() as model_1:
a = pm.Normal("a", 0.0, 10.0)
b = pm.Normal("b", 0.0, 10.0)

mu = a + b * predictor_scaled
sd = pm.Exponential("sd", 1.0)

obs = pm.Normal("obs", mu=mu, sigma=sd, observed=outcome_scaled)
prior_checks = pm.sample_prior_predictive(samples=50, random_seed=RANDOM_SEED)


What do these priors mean? It’s always hard to tell on paper – the best is to plot their implication on the outcome scale, like that:

[6]:

_, ax = plt.subplots()

x = np.linspace(-2, 2, 50)

for a, b in zip(prior_checks["a"], prior_checks["b"]):
y = a + b * x
ax.plot(x, y, c="k", alpha=0.4)

ax.set_xlabel("Predictor (stdz)")
ax.set_ylabel("Mean Outcome (stdz)")
ax.set_title("Prior predictive checks -- Flat priors");


These priors allow for absurdly strong relationships between the outcome and predictor. Of course, the choice of prior always depends on your model and data, but look at the scale of the y axis: the outcome can go from -40 to +40 standard deviations (remember, the data are standardized). I hope you will agree this is way too permissive – we can do better! Let’s use weakly informative priors and see what they yield. In a real case study, this is the part where you incorporate scientific knowledge into your model:

[7]:

with pm.Model() as model_1:
a = pm.Normal("a", 0.0, 0.5)
b = pm.Normal("b", 0.0, 1.0)

mu = a + b * predictor_scaled
sd = pm.Exponential("sd", 1.0)

obs = pm.Normal("obs", mu=mu, sigma=sd, observed=outcome_scaled)
prior_checks = pm.sample_prior_predictive(samples=50, random_seed=RANDOM_SEED)

[8]:

_, ax = plt.subplots()

x = np.linspace(-2, 2, 50)

for a, b in zip(prior_checks["a"], prior_checks["b"]):
y = a + b * x
ax.plot(x, y, c="k", alpha=0.4)

ax.set_xlabel("Predictor (stdz)")
ax.set_ylabel("Mean Outcome (stdz)")
ax.set_title("Prior predictive checks -- Weakly regularizing priors");


Well that’s way better! There are still very strong relationships, but at least now the outcome stays in the realm of possibilities. Now, it’s time to party – if by “party” you mean “run the model”, of course.

[9]:

with model_1:
trace_1 = pm.sample(1000, tune=2000, random_seed=RANDOM_SEED, return_inferencedata=True)
az.plot_trace(trace_1);

Auto-assigning NUTS sampler...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sd, b, a]

100.00% [12000/12000 00:02<00:00 Sampling 4 chains, 0 divergences]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 3 seconds.


Everything ran smoothly, but it’s often difficult to understand what the parameters’ values mean when analyzing a trace plot or table summary – even more so here, as the parameters live in the standardized space. A useful thing to understand your models is… you guessed it: posterior predictive checks! We’ll use PyMC’s dedicated function to sample data from the posterior. This function will randomly draw 4000 samples of parameters from the trace. Then, for each sample, it will draw 100 random numbers from a normal distribution specified by the values of mu and sd in that sample:

[10]:

with model_1:
ppc = pm.sample_posterior_predictive(
trace_1, var_names=["a", "b", "obs"], random_seed=RANDOM_SEED
)

100.00% [4000/4000 00:17<00:00]

Now, ppc contains 4000 generated data sets (containing 100 samples each), each using a different parameter setting from the posterior:

[11]:

ppc["obs"].shape

[11]:

(4000, 100)


One common way to visualize is to look if the model can reproduce the patterns observed in the real data. ArviZ has a really neat function to do that out of the box:

[12]:

az.plot_ppc(az.from_pymc3(posterior_predictive=ppc, model=model_1));

/home/marco/miniconda/envs/pymc3-dev/lib/python3.8/site-packages/IPython/core/pylabtools.py:132: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
fig.canvas.print_figure(bytes_io, **kw)


It looks like the model is pretty good at retrodicting the data. In addition to this generic function, it’s always nice to make a plot tailored to your use-case. Here, it would be interesting to plot the predicted relationship between the predictor and the outcome. This is quite easy, now that we already sampled posterior predictive samples – we just have to push the parameters through the model:

[13]:

mu_pp = (ppc["a"] + ppc["b"] * predictor_scaled[:, None]).T

_, ax = plt.subplots()

ax.plot(predictor_scaled, outcome_scaled, "o", ms=4, alpha=0.4, label="Data")
ax.plot(predictor_scaled, mu_pp.mean(0), label="Mean outcome", alpha=0.6)
az.plot_hpd(
predictor_scaled,
mu_pp,
ax=ax,
fill_kwargs={"alpha": 0.8, "label": "Mean outcome 94% HPD"},
)
az.plot_hpd(
predictor_scaled,
ppc["obs"],
ax=ax,
fill_kwargs={"alpha": 0.8, "color": "#a1dab4", "label": "Outcome 94% HPD"},
)

ax.set_xlabel("Predictor (stdz)")
ax.set_ylabel("Outcome (stdz)")
ax.set_title("Posterior predictive checks")
ax.legend(ncol=2, fontsize=10);

/home/marco/miniconda/envs/pymc3-dev/lib/python3.8/site-packages/arviz/stats/stats.py:483: FutureWarning: hdi currently interprets 2d data as (draw, shape) but this will change in a future release to (chain, draw) for coherence with other functions
warnings.warn(
/home/marco/miniconda/envs/pymc3-dev/lib/python3.8/site-packages/arviz/stats/stats.py:483: FutureWarning: hdi currently interprets 2d data as (draw, shape) but this will change in a future release to (chain, draw) for coherence with other functions
warnings.warn(


We have a lot of data, so the uncertainty around the mean of the outcome is pretty narrow; but the uncertainty surrounding the outcome in general seems quite in line with the observed data.

## Comparison between PPC and other model evaluation methods.¶

An excellent introduction to this was given in the Edward documentation:

PPCs are an excellent tool for revising models, simplifying or expanding the current model as one examines how well it fits the data. They are inspired by prior checks and classical hypothesis testing, under the philosophy that models should be criticized under the frequentist perspective of large sample assessment.

PPCs can also be applied to tasks such as hypothesis testing, model comparison, model selection, and model averaging. It’s important to note that while they can be applied as a form of Bayesian hypothesis testing, hypothesis testing is generally not recommended: binary decision making from a single test is not as common a use case as one might believe. We recommend performing many PPCs to get a holistic understanding of the model fit.

## Prediction¶

The same pattern can be used for prediction. Here, we are building a logistic regression model:

[14]:

N = 400
true_intercept = 0.2
true_slope = 1.0
predictors = np.random.normal(size=N)
true_p = logistic(true_intercept + true_slope * predictors)

outcomes = np.random.binomial(1, true_p)
outcomes[:10]

[14]:

array([1, 1, 0, 1, 1, 1, 1, 0, 0, 1])

[15]:

with pm.Model() as model_2:
betas = pm.Normal("betas", mu=0.0, sigma=np.array([0.5, 1.0]), shape=2)

# set predictors as shared variable to change them for PPCs:
pred = pm.Data("pred", predictors)
p = pm.Deterministic("p", pm.math.invlogit(betas[0] + betas[1] * pred))

outcome = pm.Bernoulli("outcome", p=p, observed=outcomes)

trace_2 = pm.sample(1000, tune=2000, random_seed=RANDOM_SEED, return_inferencedata=True)
az.summary(trace_2, var_names=["betas"], round_to=2)

Auto-assigning NUTS sampler...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [betas]

100.00% [12000/12000 00:02<00:00 Sampling 4 chains, 0 divergences]
Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + 4_000 draws total) took 3 seconds.

[15]:

mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_mean ess_sd ess_bulk ess_tail r_hat
betas[0] 0.24 0.11 0.05 0.45 0.0 0.0 3283.48 3135.74 3294.10 2836.18 1.0
betas[1] 1.08 0.14 0.84 1.35 0.0 0.0 3166.22 3065.49 3170.95 2628.00 1.0

Now, let’s simulate out-of-sample data to see how the model predicts them. We’ll give the new predictors to the model and it’ll then tell us what it thinks the outcomes are, based on what it learned in the training round. We’ll then compare the model’s predictions to the true out-of-sample outcomes.

[16]:

predictors_out_of_sample = np.random.normal(size=50)
outcomes_out_of_sample = np.random.binomial(
1, logistic(true_intercept + true_slope * predictors_out_of_sample)
)

with model_2:
# update values of predictors:
pm.set_data({"pred": predictors_out_of_sample})
# use the updated values and predict outcomes and probabilities:
posterior_predictive = pm.sample_posterior_predictive(
trace_2, var_names=["p"], random_seed=RANDOM_SEED
)
model_preds = posterior_predictive["p"]

100.00% [4000/4000 00:00<00:00]

### Mean predicted values plus error bars to give a sense of uncertainty in prediction¶

Note that since we are dealing with the full posterior, we are also getting uncertainty in our predictions for free.

[17]:

_, ax = plt.subplots(figsize=(12, 6))

ax.plot(
[predictors_out_of_sample, predictors_out_of_sample],
az.hpd(model_preds).T,
lw=6,
color="#00204C",
alpha=0.8,
)
# expected probability of success:
ax.plot(
predictors_out_of_sample,
model_preds.mean(0),
"o",
ms=5,
color="#FFE945",
alpha=0.8,
label="Expected prob.",
)

# actual outcomes:
ax.scatter(
x=predictors_out_of_sample,
y=outcomes_out_of_sample,
marker="x",
color="#A69C75",
alpha=0.8,
label="Observed outcomes",
)

# true probabilities:
x = np.linspace(predictors_out_of_sample.min() - 0.1, predictors_out_of_sample.max() + 0.1)
ax.plot(
x,
logistic(true_intercept + true_slope * x),
lw=2,
ls="--",
color="#565C6C",
alpha=0.8,
label="True prob.",
)

ax.set_xlabel("Predictor")
ax.set_ylabel("Prob. of succes")
ax.set_title("Out-of-sample Predictions")
ax.legend(fontsize=10, frameon=True, framealpha=0.5);

/home/marco/miniconda/envs/pymc3-dev/lib/python3.8/site-packages/arviz/stats/stats.py:338: UserWarning: hpd will be deprecated Please replace hdi
warnings.warn(("hpd will be deprecated " "Please replace hdi"),)
/home/marco/miniconda/envs/pymc3-dev/lib/python3.8/site-packages/arviz/stats/stats.py:483: FutureWarning: hdi currently interprets 2d data as (draw, shape) but this will change in a future release to (chain, draw) for coherence with other functions
warnings.warn(

[18]:

%load_ext watermark
%watermark -n -u -v -iv -w

numpy 1.19.1
pymc3 3.9.3
arviz 0.9.0
last updated: Wed Sep 16 2020

CPython 3.8.5
IPython 7.17.0
watermark 2.0.2