19. Posterior Distributions for AR(1) Parameters#

GPU

This lecture was built using a machine with the latest CUDA and CUDANN frameworks installed with access to a GPU.

To run this lecture on Google Colab, click on the “play” icon top right, select Colab, and set the runtime environment to include a GPU.

To run this lecture on your own machine, you need to install the software listed following this notice.

!pip install numpyro jax

Hide code cell output

Requirement already satisfied: numpyro in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (0.19.0)
Requirement already satisfied: jax in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (0.6.2)
Requirement already satisfied: jaxlib>=0.4.25 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from numpyro) (0.6.2)
Requirement already satisfied: multipledispatch in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from numpyro) (0.6.0)
Requirement already satisfied: numpy in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from numpyro) (2.1.3)
Requirement already satisfied: tqdm in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from numpyro) (4.67.1)
Requirement already satisfied: ml_dtypes>=0.5.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from jax) (0.5.3)
Requirement already satisfied: opt_einsum in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from jax) (3.4.0)
Requirement already satisfied: scipy>=1.12 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from jax) (1.15.3)
Requirement already satisfied: six in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from multipledispatch->numpyro) (1.17.0)

In addition to what’s included in base Anaconda, we need to install the following packages

!pip install arviz pymc

Hide code cell output

Collecting arviz
  Downloading arviz-0.22.0-py3-none-any.whl.metadata (8.9 kB)
Collecting pymc
  Downloading pymc-5.25.1-py3-none-any.whl.metadata (16 kB)
Requirement already satisfied: setuptools>=60.0.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (72.1.0)
Requirement already satisfied: matplotlib>=3.8 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (3.10.0)
Requirement already satisfied: numpy>=1.26.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (2.1.3)
Requirement already satisfied: scipy>=1.11.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (1.15.3)
Requirement already satisfied: packaging in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (24.2)
Requirement already satisfied: pandas>=2.1.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (2.2.3)
Requirement already satisfied: xarray>=2023.7.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (2025.4.0)
Collecting h5netcdf>=1.0.2 (from arviz)
  Downloading h5netcdf-1.6.4-py3-none-any.whl.metadata (13 kB)
Requirement already satisfied: typing-extensions>=4.1.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from arviz) (4.12.2)
Collecting xarray-einstats>=0.3 (from arviz)
  Downloading xarray_einstats-0.9.1-py3-none-any.whl.metadata (5.9 kB)
Requirement already satisfied: cachetools>=4.2.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pymc) (5.5.1)
Requirement already satisfied: cloudpickle in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pymc) (3.0.0)
Collecting pytensor<2.32,>=2.31.7 (from pymc)
  Downloading pytensor-2.31.7-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (6.9 kB)
Collecting rich>=13.7.1 (from pymc)
  Downloading rich-14.1.0-py3-none-any.whl.metadata (18 kB)
Requirement already satisfied: threadpoolctl<4.0.0,>=3.1.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pymc) (3.5.0)
Requirement already satisfied: filelock>=3.15 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pytensor<2.32,>=2.31.7->pymc) (3.17.0)
Collecting etuples (from pytensor<2.32,>=2.31.7->pymc)
  Downloading etuples-0.3.10-py3-none-any.whl.metadata (4.8 kB)
Collecting logical-unification (from pytensor<2.32,>=2.31.7->pymc)
  Downloading logical-unification-0.4.6.tar.gz (31 kB)
  Preparing metadata (setup.py) ... ?25l-
 done
?25hCollecting miniKanren (from pytensor<2.32,>=2.31.7->pymc)
  Downloading minikanren-1.0.5-py3-none-any.whl.metadata (7.6 kB)
Collecting cons (from pytensor<2.32,>=2.31.7->pymc)
  Downloading cons-0.4.7-py3-none-any.whl.metadata (3.8 kB)
Requirement already satisfied: h5py in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from h5netcdf>=1.0.2->arviz) (3.12.1)
Requirement already satisfied: contourpy>=1.0.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (1.3.1)
Requirement already satisfied: cycler>=0.10 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (0.11.0)
Requirement already satisfied: fonttools>=4.22.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (4.55.3)
Requirement already satisfied: kiwisolver>=1.3.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (1.4.8)
Requirement already satisfied: pillow>=8 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (11.1.0)
Requirement already satisfied: pyparsing>=2.3.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (3.2.0)
Requirement already satisfied: python-dateutil>=2.7 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from matplotlib>=3.8->arviz) (2.9.0.post0)
Requirement already satisfied: pytz>=2020.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pandas>=2.1.0->arviz) (2024.1)
Requirement already satisfied: tzdata>=2022.7 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from pandas>=2.1.0->arviz) (2025.2)
Requirement already satisfied: six>=1.5 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from python-dateutil>=2.7->matplotlib>=3.8->arviz) (1.17.0)
Requirement already satisfied: markdown-it-py>=2.2.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from rich>=13.7.1->pymc) (3.0.0)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from rich>=13.7.1->pymc) (2.19.1)
Requirement already satisfied: mdurl~=0.1 in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from markdown-it-py>=2.2.0->rich>=13.7.1->pymc) (0.1.0)
Requirement already satisfied: toolz in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from logical-unification->pytensor<2.32,>=2.31.7->pymc) (1.0.0)
Requirement already satisfied: multipledispatch in /home/runner/miniconda3/envs/quantecon/lib/python3.13/site-packages (from logical-unification->pytensor<2.32,>=2.31.7->pymc) (0.6.0)
Downloading arviz-0.22.0-py3-none-any.whl (1.7 MB)
?25l   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/1.7 MB ? eta -:--:--
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.7/1.7 MB 50.4 MB/s eta 0:00:00
?25hDownloading pymc-5.25.1-py3-none-any.whl (535 kB)
?25l   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/535.5 kB ? eta -:--:--
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 535.5/535.5 kB 26.0 MB/s eta 0:00:00
?25hDownloading pytensor-2.31.7-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (2.1 MB)
?25l   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0.0/2.1 MB ? eta -:--:--
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 95.1 MB/s eta 0:00:00
?25hDownloading h5netcdf-1.6.4-py3-none-any.whl (50 kB)
Downloading rich-14.1.0-py3-none-any.whl (243 kB)
Downloading xarray_einstats-0.9.1-py3-none-any.whl (39 kB)
Downloading cons-0.4.7-py3-none-any.whl (8.6 kB)
Downloading etuples-0.3.10-py3-none-any.whl (12 kB)
Downloading minikanren-1.0.5-py3-none-any.whl (24 kB)
Building wheels for collected packages: logical-unification
  DEPRECATION: Building 'logical-unification' using the legacy setup.py bdist_wheel mechanism, which will be removed in a future version. pip 25.3 will enforce this behaviour change. A possible replacement is to use the standardized build interface by setting the `--use-pep517` option, (possibly combined with `--no-build-isolation`), or adding a `pyproject.toml` file to the source tree of 'logical-unification'. Discussion can be found at https://github.com/pypa/pip/issues/6334

  Building wheel for logical-unification (setup.py) ... ?25l-
 \
 done
?25h  Created wheel for logical-unification: filename=logical_unification-0.4.6-py3-none-any.whl size=13912 sha256=dae1cbf5097053e749a6126dd07e30deb50300ffd3d059361a78283fd04c1a71
  Stored in directory: /home/runner/.cache/pip/wheels/50/9a/bf/3927d356d65af78752ad339a5a29142ecc58c19d5c57531ede
Successfully built logical-unification
Installing collected packages: rich, logical-unification, h5netcdf, cons, xarray-einstats, etuples, miniKanren, arviz, pytensor, pymc
?25l
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━  0/10 [rich]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━━━━━  7/10 [arviz]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━━━━━  7/10 [arviz]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━  8/10 [pytensor]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━  8/10 [pytensor]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━  8/10 [pytensor]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━  8/10 [pytensor]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━━━━━  8/10 [pytensor]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━  9/10 [pymc]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╺━━━  9/10 [pymc]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10/10 [pymc]
?25h
Successfully installed arviz-0.22.0 cons-0.4.7 etuples-0.3.10 h5netcdf-1.6.4 logical-unification-0.4.6 miniKanren-1.0.5 pymc-5.25.1 pytensor-2.31.7 rich-14.1.0 xarray-einstats-0.9.1

We’ll begin with some Python imports.

import arviz as az
import pymc as pmc
import numpyro
from numpyro import distributions as dist

import numpy as np
import jax.numpy as jnp
from jax import random
import matplotlib.pyplot as plt

import logging
logging.basicConfig()
logger = logging.getLogger('pymc')
logger.setLevel(logging.CRITICAL)

This lecture uses Bayesian methods offered by pymc and numpyro to make statistical inferences about two parameters of a univariate first-order autoregression.

The model is a good laboratory for illustrating consequences of alternative ways of modeling the distribution of the initial \(y_0\):

  • As a fixed number

  • As a random variable drawn from the stationary distribution of the \(\{y_t\}\) stochastic process

The first component of the statistical model is

(19.1)#\[ y_{t+1} = \rho y_t + \sigma_x \epsilon_{t+1}, \quad t \geq 0 \]

where the scalars \(\rho\) and \(\sigma_x\) satisfy \(|\rho| < 1\) and \(\sigma_x > 0\); \(\{\epsilon_{t+1}\}\) is a sequence of i.i.d. normal random variables with mean \(0\) and variance \(1\).

The second component of the statistical model is

(19.2)#\[ y_0 \sim {\cal N}(\mu_0, \sigma_0^2) \]

Consider a sample \(\{y_t\}_{t=0}^T\) governed by this statistical model.

The model implies that the likelihood function of \(\{y_t\}_{t=0}^T\) can be factored:

\[ f(y_T, y_{T-1}, \ldots, y_0) = f(y_T| y_{T-1}) f(y_{T-1}| y_{T-2}) \cdots f(y_1 | y_0 ) f(y_0) \]

where we use \(f\) to denote a generic probability density.

The statistical model (19.1)-(19.2) implies

\[\begin{split} \begin{aligned} f(y_t | y_{t-1}) & \sim {\mathcal N}(\rho y_{t-1}, \sigma_x^2) \\ f(y_0) & \sim {\mathcal N}(\mu_0, \sigma_0^2) \end{aligned} \end{split}\]

We want to study how inferences about the unknown parameters \((\rho, \sigma_x)\) depend on what is assumed about the parameters \(\mu_0, \sigma_0\) of the distribution of \(y_0\).

Below, we study two widely used alternative assumptions:

  • \((\mu_0,\sigma_0) = (y_0, 0)\) which means that \(y_0\) is drawn from the distribution \({\mathcal N}(y_0, 0)\); in effect, we are conditioning on an observed initial value.

  • \(\mu_0,\sigma_0\) are functions of \(\rho, \sigma_x\) because \(y_0\) is drawn from the stationary distribution implied by \(\rho, \sigma_x\).

Note: We do not treat a third possible case in which \(\mu_0,\sigma_0\) are free parameters to be estimated.

Unknown parameters are \(\rho, \sigma_x\).

We have independent prior probability distributions for \(\rho, \sigma_x\) and want to compute a posterior probability distribution after observing a sample \(\{y_{t}\}_{t=0}^T\).

The notebook uses pymc4 and numpyro to compute a posterior distribution of \(\rho, \sigma_x\). We will use NUTS samplers to generate samples from the posterior in a chain. Both of these libraries support NUTS samplers.

NUTS is a form of Monte Carlo Markov Chain (MCMC) algorithm that bypasses random walk behaviour and allows for convergence to a target distribution more quickly. This not only has the advantage of speed, but allows for complex models to be fitted without having to employ specialised knowledge regarding the theory underlying those fitting methods.

Thus, we explore consequences of making these alternative assumptions about the distribution of \(y_0\):

  • A first procedure is to condition on whatever value of \(y_0\) is observed. This amounts to assuming that the probability distribution of the random variable \(y_0\) is a Dirac delta function that puts probability one on the observed value of \(y_0\).

  • A second procedure assumes that \(y_0\) is drawn from the stationary distribution of a process described by (19.1) so that \(y_0 \sim {\cal N} \left(0, {\sigma_x^2\over (1-\rho)^2} \right) \)

When the initial value \(y_0\) is far out in a tail of the stationary distribution, conditioning on an initial value gives a posterior that is more accurate in a sense that we’ll explain.

Basically, when \(y_0\) happens to be in a tail of the stationary distribution and we don’t condition on \(y_0\), the likelihood function for \(\{y_t\}_{t=0}^T\) adjusts the posterior distribution of the parameter pair \(\rho, \sigma_x \) to make the observed value of \(y_0\) more likely than it really is under the stationary distribution, thereby adversely twisting the posterior in short samples.

An example below shows how not conditioning on \(y_0\) adversely shifts the posterior probability distribution of \(\rho\) toward larger values.

We begin by solving a direct problem that simulates an AR(1) process.

How we select the initial value \(y_0\) matters.

  • If we think \(y_0\) is drawn from the stationary distribution \({\mathcal N}(0, \frac{\sigma_x^{2}}{1-\rho^2})\), then it is a good idea to use this distribution as \(f(y_0)\). Why? Because \(y_0\) contains information about \(\rho, \sigma_x\).

  • If we suspect that \(y_0\) is far in the tails of the stationary distribution – so that variation in early observations in the sample have a significant transient component – it is better to condition on \(y_0\) by setting \(f(y_0) = 1\).

To illustrate the issue, we’ll begin by choosing an initial \(y_0\) that is far out in a tail of the stationary distribution.

def ar1_simulate(rho, sigma, y0, T):

    # Allocate space and draw epsilons
    y = np.empty(T)
    eps = np.random.normal(0.,sigma,T)

    # Initial condition and step forward
    y[0] = y0
    for t in range(1, T):
        y[t] = rho*y[t-1] + eps[t]

    return y

sigma =  1.
rho = 0.5
T = 50

np.random.seed(145353452)
y = ar1_simulate(rho, sigma, 10, T)
plt.plot(y)
plt.tight_layout()
_images/e8c2e99e1ab9a01f7045c04399ca566efb932c6aa6aed1b6e6d6223c9903006d.png

Now we shall use Bayes’ law to construct a posterior distribution, conditioning on the initial value of \(y_0\).

(Later we’ll assume that \(y_0\) is drawn from the stationary distribution, but not now.)

First we’ll use pymc4.

19.1. PyMC Implementation#

For a normal distribution in pymc, \(var = 1/\tau = \sigma^{2}\).

AR1_model = pmc.Model()

with AR1_model:

    # Start with priors
    rho = pmc.Uniform('rho', lower=-1., upper=1.) # Assume stable rho
    sigma = pmc.HalfNormal('sigma', sigma = np.sqrt(10))

    # Expected value of y at the next period (rho * y)
    yhat = rho * y[:-1]

    # Likelihood of the actual realization
    y_like = pmc.Normal('y_obs', mu=yhat, sigma=sigma, observed=y[1:])

pmc.sample by default uses the NUTS samplers to generate samples as shown in the below cell:

with AR1_model:
    trace = pmc.sample(50000, tune=10000, return_inferencedata=True)

with AR1_model:
    az.plot_trace(trace, figsize=(17,6))
_images/72b559d8a6e5e2c3fb9ecf6a1cf83cea772c64e24bf32448cb930dc5714b8ae6.png

Evidently, the posteriors aren’t centered on the true values of \(.5, 1\) that we used to generate the data.

This is a symptom of the classic Hurwicz bias for first order autoregressive processes (see Leonid Hurwicz [Hurwicz, 1950].)

The Hurwicz bias is worse the smaller is the sample (see [Orcutt and Winokur, 1969]).

Be that as it may, here is more information about the posterior.

with AR1_model:
    summary = az.summary(trace, round_to=4)

summary
mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
rho 0.5361 0.0709 0.4032 0.6705 0.0002 0.0002 176203.5643 126290.9618 1.0
sigma 1.0105 0.1065 0.8181 1.2113 0.0003 0.0003 186049.4745 139233.6855 1.0

Now we shall compute a posterior distribution after seeing the same data but instead assuming that \(y_0\) is drawn from the stationary distribution.

This means that

\[ y_0 \sim N \left(0, \frac{\sigma_x^{2}}{1 - \rho^{2}} \right) \]

We alter the code as follows:

AR1_model_y0 = pmc.Model()

with AR1_model_y0:

    # Start with priors
    rho = pmc.Uniform('rho', lower=-1., upper=1.) # Assume stable rho
    sigma = pmc.HalfNormal('sigma', sigma=np.sqrt(10))

    # Standard deviation of ergodic y
    y_sd = sigma / np.sqrt(1 - rho**2)

    # yhat
    yhat = rho * y[:-1]
    y_data = pmc.Normal('y_obs', mu=yhat, sigma=sigma, observed=y[1:])
    y0_data = pmc.Normal('y0_obs', mu=0., sigma=y_sd, observed=y[0])
with AR1_model_y0:
    trace_y0 = pmc.sample(50000, tune=10000, return_inferencedata=True)

# Grey vertical lines are the cases of divergence

with AR1_model_y0:
    az.plot_trace(trace_y0, figsize=(17,6))
_images/761548975021103f63095b1f25d95b451cb331f201681ed1c321d9f6bfac31b8.png
with AR1_model:
    summary_y0 = az.summary(trace_y0, round_to=4)

summary_y0
mean sd hdi_3% hdi_97% mcse_mean mcse_sd ess_bulk ess_tail r_hat
rho 0.8762 0.0811 0.7317 0.9978 0.0002 0.0002 100214.6057 78133.6868 1.0
sigma 1.4047 0.1472 1.1407 1.6841 0.0005 0.0004 108006.8730 99735.6578 1.0

Please note how the posterior for \(\rho\) has shifted to the right relative to when we conditioned on \(y_0\) instead of assuming that \(y_0\) is drawn from the stationary distribution.

Think about why this happens.

Hint

It is connected to how Bayes Law (conditional probability) solves an inverse problem by putting high probability on parameter values that make observations more likely.

We’ll return to this issue after we use numpyro to compute posteriors under our two alternative assumptions about the distribution of \(y_0\).

We’ll now repeat the calculations using numpyro.

19.2. Numpyro Implementation#

def plot_posterior(sample):
    """
    Plot trace and histogram
    """
    # To np array
    rhos = sample['rho']
    sigmas = sample['sigma']
    rhos, sigmas, = np.array(rhos), np.array(sigmas)

    fig, axs = plt.subplots(2, 2, figsize=(17, 6))
    # Plot trace
    axs[0, 0].plot(rhos)   # rho
    axs[1, 0].plot(sigmas) # sigma

    # Plot posterior
    axs[0, 1].hist(rhos, bins=50, density=True, alpha=0.7)
    axs[0, 1].set_xlim([0, 1])
    axs[1, 1].hist(sigmas, bins=50, density=True, alpha=0.7)

    axs[0, 0].set_title("rho")
    axs[0, 1].set_title("rho")
    axs[1, 0].set_title("sigma")
    axs[1, 1].set_title("sigma")
    plt.show()
def AR1_model(data):
    # set prior
    rho = numpyro.sample('rho', dist.Uniform(low=-1., high=1.))
    sigma = numpyro.sample('sigma', dist.HalfNormal(scale=np.sqrt(10)))

    # Expected value of y at the next period (rho * y)
    yhat = rho * data[:-1]

    # Likelihood of the actual realization.
    y_data = numpyro.sample('y_obs', dist.Normal(loc=yhat, scale=sigma), obs=data[1:])
# Make jnp array
y = jnp.array(y)

# Set NUTS kernal
NUTS_kernel = numpyro.infer.NUTS(AR1_model)

# Run MCMC
mcmc = numpyro.infer.MCMC(NUTS_kernel, num_samples=50000, num_warmup=10000, progress_bar=False)
mcmc.run(rng_key=random.PRNGKey(1), data=y)
plot_posterior(mcmc.get_samples())
_images/d9d9ac41436e06f176c7767383dfe55bd13cf0d085592f1ea05bce9e543df59b.png
mcmc.print_summary()
                mean       std    median      5.0%     95.0%     n_eff     r_hat
       rho      0.54      0.07      0.54      0.42      0.65  44430.72      1.00
     sigma      1.01      0.11      1.00      0.84      1.18  42626.35      1.00

Number of divergences: 0

Next, we again compute the posterior under the assumption that \(y_0\) is drawn from the stationary distribution, so that

\[ y_0 \sim N \left(0, \frac{\sigma_x^{2}}{1 - \rho^{2}} \right) \]

Here’s the new code to achieve this.

def AR1_model_y0(data):
    # Set prior
    rho = numpyro.sample('rho', dist.Uniform(low=-1., high=1.))
    sigma = numpyro.sample('sigma', dist.HalfNormal(scale=np.sqrt(10)))

    # Standard deviation of ergodic y
    y_sd = sigma / jnp.sqrt(1 - rho**2)

    # Expected value of y at the next period (rho * y)
    yhat = rho * data[:-1]

    # Likelihood of the actual realization.
    y_data = numpyro.sample('y_obs', dist.Normal(loc=yhat, scale=sigma), obs=data[1:])
    y0_data = numpyro.sample('y0_obs', dist.Normal(loc=0., scale=y_sd), obs=data[0])
# Make jnp array
y = jnp.array(y)

# Set NUTS kernal
NUTS_kernel = numpyro.infer.NUTS(AR1_model_y0)

# Run MCMC
mcmc2 = numpyro.infer.MCMC(NUTS_kernel, num_samples=50000, num_warmup=10000, progress_bar=False)
mcmc2.run(rng_key=random.PRNGKey(1), data=y)
plot_posterior(mcmc2.get_samples())
_images/30d6749b77d884db06614b4bb6ee79389aa6eb57a1c309d265807a224fd71cd5.png
mcmc2.print_summary()
                mean       std    median      5.0%     95.0%     n_eff     r_hat
       rho      0.88      0.08      0.89      0.76      1.00  31419.08      1.00
     sigma      1.41      0.15      1.39      1.17      1.64  26542.08      1.00

Number of divergences: 0

Look what happened to the posterior!

It has moved far from the true values of the parameters used to generate the data because of how Bayes’ Law (i.e., conditional probability) is telling numpyro to explain what it interprets as “explosive” observations early in the sample.

Bayes’ Law is able to generate a plausible likelihood for the first observation by driving \(\rho \rightarrow 1\) and \(\sigma \uparrow\) in order to raise the variance of the stationary distribution.

Our example illustrates the importance of what you assume about the distribution of initial conditions.