# Posterior Predictive Checks with an 'error-in-variables' model

**URL:** <https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155>\
**Category:** General\
**Created:** [September 28, 2024, 2:08am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155 "2024-09-28T02:08:58Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![jjorg](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jjorg/32/8556_2.png) [@jjorg](https://discourse.pymc.io/u/jjorg)\
**Post date:** [September 28, 2024, 2:08am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/1 "2024-09-28T02:08:58Z")

</div>

Hi there,

I have a conceptual query regarding the ‘error-in-variables’ approach. Is it possible to perform meaningful posterior predictive checks with the observed noisy predictor data (let’s call that xobs)? My understanding, given the underlying process is a function of the latent, unobserved, true predictor (call this xt), is that this is at least complicated with the methods available in PyMC3 (I’m using version 3.11.2), if not impossible.

If I take the example [posterior predictive check example](https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/posterior_predictive.html), then I note that the checks are performed using the scaled observed predictor data xobs (as expected). But, in the ‘error-in-variables’ approach, a set of xobs is sampled from the posterior for each sample when running sample\_posterior\_predictive. So, the plotting mu\_pp.mean (see example) and plot\_hdi against the original observed data xobs does not seem relevant, given each realisation of mu\_pp is generated based on a sampled set of x\_obs. Is there a principled way to approach this?

Regards,  
Jack

---

<div class="post-metadata">

**Author:** ![jessegrabowski](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jessegrabowski/32/5010_2.png) [@jessegrabowski](https://discourse.pymc.io/u/jessegrabowski)\
**Post date:** [September 28, 2024, 4:28am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/2 "2024-09-28T04:28:33Z")

</div>

Preamble: PyMC3 is legacy software that is not maintained. This reply assumes you go get the latest version, which is 5.16.2 at the time of writing.

You can add measurement error to covariates by assigning them distributions, and using the (noisy) data as observations of these distributions. Here’s an example:

```python
import pymc as pm
import numpy as np
import arviz as az

with pm.Model() as error_model:    
    
    mu_x = pm.Normal('mu_x', sigma=100)
    sigma_x = pm.Exponential('sigma_x', 0.1)
    x = pm.Normal('x', mu=mu_x, sigma=sigma_x, size=(100,))

    alpha = pm.Normal('alpha', sigma=100)
    beta = pm.Normal('beta', sigma=10)
    mu = pm.Deterministic('mu', alpha + beta * x)    

    sigma = pm.Exponential('sigma', 1)
    obs = pm.Normal('obs', mu=mu, sigma=sigma)

```

Use this model to take some prior draws, and choose one to use as data, and modify the model to include the observations:

```python
with error_model:
    prior = pm.sample_prior_predictive()

draw_idx = np.random.choice(500)
true_data = prior.prior.isel(chain=0, draw=draw_idx)
model = pm.observe(error_model, {x:true_data.x, obs:true_data.obs})
model.to_graphviz()

```

Here’s what you end up with. Notice that uncertainty from `x` flows down into `obs`

 ![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/c/c481efe8cc86edab9da180aca06f7bf29479de09.png)

Sample the model and make some plots:

```python
with model:
    idata = pm.sample()
    idata = pm.sample_posterior_predictive(idata, extend_inferencedata=True)
    
var_names = ['mu_x', 'sigma_x', 'alpha', 'beta']
ref_val = np.r_[[true_data[x].item() for x in var_names]].tolist()
az.plot_posterior(idata, var_names=var_names, ref_val=ref_val)
az.plot_ppc(idata, var_names=['obs', 'x'])

```

 ![Untitled](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/e/e3301c71ed50b05a79d8344bf6c27618e06815bd.png)  
 ![Untitled](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/f/f007d9914aa14c606371f660e4217e980cc6f78a.jpeg)

The posterior predictive draws for `obs` are computed conditional on the draws of `x`, combining uncertainty from both. You can verify this by comparing the outputs to a second model that directly uses the `x` data:

```auto
with pm.Model() as fixed_x_model:
    alpha = pm.Flat('alpha')
    beta = pm.Flat('beta')
    mu = pm.Deterministic('mu', alpha + beta * true_data.x.values)
    
    sigma = pm.Flat('sigma')
    obs = pm.Normal('obs', mu=mu, sigma=sigma, observed=true_data.obs.values)
    fixed_x_idata = pm.sample_posterior_predictive(idata, extend_inferencedata=False, var_names=['mu', 'obs'])

```

Plot results:

```python
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
az.plot_ppc(idata, var_names=['obs'], ax=ax, mean=False, observed=False, legend=False, alpha=0.1)
az.plot_ppc(fixed_x_idata, var_names=['obs'], ax=ax, color='tab:orange', mean=False, observed=False, legend=False, alpha=0.1)

```

Blue includes uncertainty on x, orange does not  
 ![Untitled](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/a/aa06712648166cd765b7efc49d148180d2edc76c.png)

---

<div class="post-metadata">

**Author:** ![jjorg](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jjorg/32/8556_2.png) [@jjorg](https://discourse.pymc.io/u/jjorg)\
**Post date:** [September 29, 2024, 3:56am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/3 "2024-09-29T03:56:39Z")

</div>

Good morning Jesse,

Thank you for your quick response, it is much appreciated!

I’ve a couple of queries to get my head around this approach.

1. If I interpret the model graph correctly the underlying true value _mu_ is a function of the noisy observation of _x_, and the parameters _alpha_ & _beta_ function on the noisy _x_. The example I’ve looked at for an ‘error-in-variables’ approach from [this post](https://discourse.pymc.io/t/errors-in-variables-model-in-pymc3/3519) is slightly, but importantly, different. _alpha_ & _beta_ function on the true, underlying variable _mu\_x_. The uncertainty in _x_ flows through to _obs_ through the draws of _mu\_x_ taken for each sample. Is there a particular reason why the model you’ve shown is set-up for _mu = f(x)_ rather than _mu = f(mu\_x)_?
2. From that starting point, I think I follow the process. The draws on _obs_ being conditional on _x_ (or, in the model structure I’m assuming, _mu\_x_) makes sense. But, and this is where I’m struggling conceptually, if we then want to use a call to plot\_hdi (such as is shown in the example [ppc page](https://www.pymc.io/projects/docs/en/stable/learn/core_notebooks/posterior_predictive.html), what values do we plot the hdi against? It seems to me it should be against _mu\_x_, but I’m not sure which _mu\_x_ (an average of realisations?)

Thanks again.

Regards,  
Jack

---

<div class="post-metadata">

**Author:** ![jessegrabowski](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jessegrabowski/32/5010_2.png) [@jessegrabowski](https://discourse.pymc.io/u/jessegrabowski)\
**Post date:** [September 29, 2024, 5:37am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/4 "2024-09-29T05:37:56Z")

</div>

`mu_x` is your prior value on the mean of the distribution that generates `x`. It is a scalar value. If you use `mu_x` in your definition of `mu = alpha + beta * mu_x`, you will not have any variation in the `x` dimension to identify `beta`. It is possible, however, that this is what you want, but in this case I conceptually don’t know what you are expecting from the model.

You cannot “plot against” `mu_x`, because there is only one value of `mu_x`. If you wanted to plots HDIs in this case, I would first make a scatterplot of the true data at positions (x\_true, y\_true). Then do a forestplot showing the hdi in the y-dimension vertically, and the hdi in the x-dimension horizontally.

---

<div class="post-metadata">

**Author:** ![jjorg](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jjorg/32/8556_2.png) [@jjorg](https://discourse.pymc.io/u/jjorg)\
**Post date:** [September 29, 2024, 7:25am UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/5 "2024-09-29T07:25:05Z")

</div>

Thanks Jesse. Apologies, I think I’ve confused matters here by mixing nomenclature between your model and the example I’m following.

I’ll refer directly to the model structure that is used in the ‘error-in-variables’ post (see link in my previous post). See below the model structure. If I’m not mistaken, this is different to the set-up in your example.

![image](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/7/7da2afb83b073fc660f2ba5b561072b883282592.png)

Then, the model is implemented as below

```auto
with pm.Model() as model:
    err_odr = pm.HalfNormal('err_odr', 5.)
    err_param = pm.HalfNormal('err_param', 5.)
    x_lat = pm.Normal('x_mu', 0, 5., shape=x.shape[0])
    x_obs = pm.Normal('x_obs', mu=x_lat, sd=err_odr, observed=x, shape=x.shape[0])
    offset = pm.Normal('offset', 0, err_param)
    slope = pm.Normal('slope', 0, err_param)
    y_pred = pm.Deterministic('y_pred', offset + slope * x_lat)
    y_obs = pm.Normal('y', mu=y_pred, sd=err_odr, observed=y)
    
    trace = pm.sample(800, tune=1500, chains=4, cores=3, init='jitter+adapt_diag')

```

So, we have some observed data _x_ and _y_. _x_ is assumed to be a set of noisy observations of a true underlying latent variable _x\_mu_. _y_ is assumed to a set of noisy observations of the true underlying variable _y\_pred_. And _y\_pred_ is assumed to be a function of the underlying latent variable _x\_mu_.

When the model is sampled, for each sample a set of _x\_mu_ are drawn.

This is where I’m stuck. To the suggestion of a scatterplot of true data as the basis for the HDI - this would need to be the mean of samples of _x\_mu_, and of the resultant _y\_pred_. And then the HDI’s of _x\_obs_ and _y\_obs_ on top. I’m going to give this a go.

---

<div class="post-metadata">

**Author:** ![bob-carpenter](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/bob-carpenter/32/8124_2.png) [@bob-carpenter](https://discourse.pymc.io/u/bob-carpenter)\
**Post date:** [October 2, 2024, 8:35pm UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/6 "2024-10-02T20:35:06Z")

</div>

> [@jjorg](#):
>
> So, the plotting mu\_pp.mean (see example) and plot\_hdi against the original observed data xobs does not seem relevant

For posterior predictive checks, you’re usually generating replicates of the _modeled data_, not the unmodeled data like covariates. So in a regression of (dependent) `y` on (independent) `x`, the posterior predictive checks would keep `x` fixed and generate replicates of `y`. The fact that `x` has measurement error doesn’t change this.

I’m pretty sure that’s what @jessegrabowski meant by

> Notice that uncertainty from `x` flows down into `obs`

> [@jjorg](#):
>
> When the model is sampled, for each sample a set of _x\_mu_ are drawn.

Yes, you just marginalize those out by ignoring them, the same way you “ignore” the other parameters. In math, you have some noisy `x` and some noisy `y` and some parameters, which we’ll collectively call `theta`. What you’re trying to compute with posterior predictive checks for `y` is this:

\displaystyle p(y^{\textrm{sim}} \mid y) = \int\_{\Theta} p(y^\textrm{sim} \mid x, \theta) \cdot p(\theta \mid x, y) \, \textrm{d} \theta..

The x\_\mu are treated like parameters and just get margianlized out like all the other elements of \theta.

---

<div class="post-metadata">

**Author:** ![jjorg](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/jjorg/32/8556_2.png) [@jjorg](https://discourse.pymc.io/u/jjorg)\
**Post date:** [October 2, 2024, 10:39pm UTC](https://discourse.pymc.io/t/posterior-predictive-checks-with-an-error-in-variables-model/15155/7 "2024-10-02T22:39:29Z")

</div>

Good morning Bob,

Thank you for your response. The concept of marginalizing the sample x\_mu values makes sense.

Regards,  
Jack
