Diagnosing Biased Inference with Divergences

In [1]:
%matplotlib inline
import pymc3 as pm
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-darkgrid')
from collections import defaultdict
%config InlineBackend.figure_format = 'retina'
SEED = [20100420, 20100234]

print('Runing on PyMC3 v{}'.format(pm.__version__))
Runing on PyMC3 v3.3
/home/osvaldo/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters

This notebook is a PyMC3 port of Michael Betancourt’s post on ms-stan. For detailed explanation of the underlying mechanism please check the original post and Betancourt’s excellent paper.

Bayesian statistics is all about building a model and estimating the parameters in that model. However, a naive or direct parameterization of our probability model can sometimes be ineffective, you can check out Thomas Wiecki’s blog post on the same issue in PyMC3. Suboptimal parameterization often leads to slow sampling, and more problematic, biased MCMC estimators.

More formally, as explained in the original post:

Markov chain Monte Carlo (MCMC) approximates expectations with respect to a given target distribution,

\[\mathbb{E}{\pi} [ f ] = \int \mathrm{d}q \, \pi (q) \, f(q)\]

using the states of a Markov chain, \({q{0}, \ldots, q_{N} }\),

\[\mathbb{E}{\pi} [ f ] \approx \hat{f}{N} = \frac{1}{N + 1} \sum_{n = 0}^{N} f(q_{n})\]

These estimators, however, are guaranteed to be accurate only asymptotically as the chain grows to be infinitely long,

\[\lim_{N \rightarrow \infty} \hat{f}{N} = \mathbb{E}{\pi} [ f ]\]

To be useful in applied analyses, we need MCMC estimators to converge to the true expectation values sufficiently quickly that they are reasonably accurate before we exhaust our finite computational resources. This fast convergence requires strong ergodicity conditions to hold, in particular geometric ergodicity between a Markov transition and a target distribution. Geometric ergodicity is usually the necessary condition for MCMC estimators to follow a central limit theorem, which ensures not only that they are unbiased even after only a finite number of iterations but also that we can empirically quantify their precision using the MCMC standard error.

Unfortunately, proving geometric ergodicity is infeasible for any nontrivial problem. Instead we must rely on empirical diagnostics that identify obstructions to geometric ergodicity, and hence well-behaved MCMC estimators. For a general Markov transition and target distribution, the best known diagnostic is the split \(\hat{R}\) statistic over an ensemble of Markov chains initialized from diffuse points in parameter space; to do any better we need to exploit the particular structure of a given transition or target distribution.

Hamiltonian Monte Carlo, for example, is especially powerful in this regard as its failures to be geometrically ergodic with respect to any target distribution manifest in distinct behaviors that have been developed into sensitive diagnostics. One of these behaviors is the appearance of divergences that indicate the Hamiltonian Markov chain has encountered regions of high curvature in the target distribution which it cannot adequately explore.

In this notebook we aim to identify divergences and the underlying pathologies in PyMC3.

The Eight Schools Model

The hierarchical model of the Eight Schools dataset (Rubin 1981) as seen in Stan:

\[\mu \sim \mathcal{N}(0, 5)\]
\[\tau \sim \text{Half-Cauchy}(0, 5)\]
\[\theta_{n} \sim \mathcal{N}(\mu, \tau)\]
\[y_{n} \sim \mathcal{N}(\theta_{n}, \sigma_{n}),\]

where \(n \in \{1, \ldots, 8 \}\) and the \(\{ y_{n}, \sigma_{n} \}\) are given as data.

Inferring the hierarchical hyperparameters, \(\mu\) and \(\sigma\), together with the group-level parameters, \(\theta_{1}, \ldots, \theta_{8}\), allows the model to pool data across the groups and reduce their posterior variance. Unfortunately, the direct centered parameterization also squeezes the posterior distribution into a particularly challenging geometry that obstructs geometric ergodicity and hence biases MCMC estimation.

In [2]:
# Data of the Eight Schools Model
J = 8
y = np.array([28.,  8., -3.,  7., -1.,  1., 18., 12.])
sigma = np.array([15., 10., 16., 11.,  9., 11., 10., 18.])
# tau = 25.

A Centered Eight Schools Implementation

Stan model:

data {
  int<lower=0> J;
  real y[J];
  real<lower=0> sigma[J];
}

parameters {
  real mu;
  real<lower=0> tau;
  real theta[J];
}

model {
  mu ~ normal(0, 5);
  tau ~ cauchy(0, 5);
  theta ~ normal(mu, tau);
  y ~ normal(theta, sigma);
}

Similarly, we can easily implemented it in PyMC3

In [3]:
with pm.Model() as Centered_eight:
    mu = pm.Normal('mu', mu=0, sd=5)
    tau = pm.HalfCauchy('tau', beta=5)
    theta = pm.Normal('theta', mu=mu, sd=tau, shape=J)
    obs = pm.Normal('obs', mu=theta, sd=sigma, observed=y)

Unfortunately, this direct implementation of the model exhibits a pathological geometry that frustrates geometric ergodicity. Even more worrisome, the resulting bias is subtle and may not be obvious upon inspection of the Markov chain alone. To understand this bias, let’s consider first a short Markov chain, commonly used when computational expediency is a motivating factor, and only afterwards a longer Markov chain.

A Dangerously-Short Markov Chain

In [4]:
with Centered_eight:
    short_trace = pm.sample(600, chains=2, random_seed=SEED)
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 1100/1100 [00:02<00:00, 486.04it/s]
There were 10 divergences after tuning. Increase `target_accept` or reparameterize.
There were 9 divergences after tuning. Increase `target_accept` or reparameterize.
The estimated number of effective samples is smaller than 200 for some parameters.

In the original post a single chain of 1200 sample is applied. However, since split \(\hat{R}\) is not implemented in PyMC3 we fit 2 chains with 600 sample each instead.

The Gelman-Rubin diagnostic \(\hat{R}\) doesn’t indicate any problems (values are all close to 1). You could try re-running the model with a different seed and see if this still holds.

In [5]:
pm.summary(short_trace).round(2)
Out[5]:
mean sd mc_error hpd_2.5 hpd_97.5 n_eff Rhat
mu 4.18 3.31 0.18 -1.99 10.30 193.53 1.01
theta__0 6.37 5.94 0.26 -4.14 18.85 418.80 1.00
theta__1 4.99 4.65 0.21 -4.28 13.13 380.18 1.00
theta__2 3.41 6.07 0.25 -8.09 15.29 345.68 1.00
theta__3 4.50 4.89 0.19 -6.26 13.37 544.63 1.00
theta__4 3.20 4.89 0.20 -6.48 12.77 397.12 1.00
theta__5 3.91 4.86 0.21 -6.60 12.81 312.51 1.00
theta__6 6.24 5.17 0.23 -3.35 16.33 405.45 1.00
theta__7 4.81 5.85 0.24 -6.81 16.03 438.11 1.00
tau 4.28 3.03 0.20 0.89 10.31 123.81 1.02

Moreover, the trace plots all look fine. Let’s consider, for example, the hierarchical standard deviation \(\tau\), or more specifically, its logarithm, \(log(\tau)\). Because \(\tau\) is constrained to be positive, its logarithm will allow us to better resolve behavior for small values. Indeed the chains seems to be exploring both small and large values reasonably well,

In [6]:
# plot the trace of log(tau)
pm.traceplot(short_trace, varnames=['tau'], transform=np.log);
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_14_0.png

Unfortunately, the resulting estimate for the mean of \(log(\tau)\) is strongly biased away from the true value, here shown in grey.

In [7]:
# plot the estimate for the mean of log(τ) cumulating mean
logtau = np.log(short_trace['tau'])
mlogtau = [np.mean(logtau[:i]) for i in np.arange(1, len(logtau))]
plt.figure(figsize=(15, 4))
plt.axhline(0.7657852, lw=2.5, color='gray')
plt.plot(mlogtau, lw=2.5)
plt.ylim(0, 2)
plt.xlabel('Iteration')
plt.ylabel('MCMC mean of log(tau)')
plt.title('MCMC estimation of log(tau)');
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_16_0.png

Hamiltonian Monte Carlo, however, is not so oblivious to these issues as \(\approx\) 3% of the iterations in our lone Markov chain ended with a divergence.

In [8]:
# display the total number and percentage of divergent
divergent = short_trace['diverging']
print('Number of Divergent %d' % divergent.nonzero()[0].size)
divperc = divergent.nonzero()[0].size / len(short_trace) * 100
print('Percentage of Divergent %.1f' % divperc)
Number of Divergent 19
Percentage of Divergent 3.2

Even with a single short chain these divergences are able to identity the bias and advise skepticism of any resulting MCMC estimators.

Additionally, because the divergent transitions, here shown in green, tend to be located near the pathologies we can use them to identify the location of the problematic neighborhoods in parameter space.

In [9]:
pm.pairplot(short_trace,
           sub_varnames=['theta_0','tau_log__'],
           divergences=True,
           color='C3', figsize=(10, 5), kwargs_divergence={'color':'C2'})
plt.title('scatter plot between log(tau) and theta[0]');
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_20_0.png

It is important to point out that the pathological samples from the trace are not necessarily concentrated at the funnel: when a divergence is encountered, the subtree being constructed is rejected and the transition samples uniformly from the existing discrete trajectory. Consequently, divergent samples will not be located exactly in the region of high curvature.

In pymc3, we recently implemented a warning system that also saves the information of where the divergence occurs, and hence you can visualize them directly. To be more precise, what we include as the divergence point in the warning is the point where that problematic leapfrog step started. Some could also be because the divergence happens in one of the leapfrog step (which strictly speaking is not a point). But nonetheless, visualizing these should give a closer proximate where the funnel is.

Notices that only the first 100 divergences are stored, so that we don’t eat all memory.

In [10]:
divergent_point = defaultdict(list)

chain_warn = short_trace.report._chain_warnings
for i in range(len(chain_warn)):
    for warning_ in chain_warn[i]:
        if warning_.step is not None and warning_.extra is not None:
            for RV in Centered_eight.free_RVs:
                para_name = RV.name
                divergent_point[para_name].append(warning_.extra[para_name])

for RV in Centered_eight.free_RVs:
    para_name = RV.name
    divergent_point[para_name] = np.asarray(divergent_point[para_name])
ii = 5

tau_log_d = divergent_point['tau_log__']
theta0_d = divergent_point['theta'][:, ii]
Ndiv_recorded = len(tau_log_d)
In [11]:
_, ax = plt.subplots(1, 2, figsize=(15, 6), sharex=True, sharey=True)

pm.pairplot(short_trace,
               sub_varnames=['theta_0', 'tau_log__'],
               divergences=True,
               ax=ax[0],
               color='C7', figsize=(12, 10), alpha=0.2,
               kwargs_divergence={'color':'C2'})

plt.title('scatter plot between log(tau) and theta[5]')

pm.pairplot(short_trace,
               sub_varnames=['theta_0', 'tau_log__'],
               divergences=True,
               ax=ax[1],
               color='C7', alpha=0.2, figsize=(12, 10),
               kwargs_divergence={'color':'C2', 'label':'Divergent samples'})

theta_trace = short_trace['theta']
theta0 = theta_trace[:, 0]

plt.plot([theta0[divergent == 1][:Ndiv_recorded], theta0_d],
           [logtau[divergent == 1][:Ndiv_recorded], tau_log_d],
           'k-', alpha=.25)

plt.scatter(theta0_d, tau_log_d,
              color='C3', alpha=.5, label='Location of Energy error (start location of leapfrog)')

plt.title('scatter plot between log(tau) and theta[0]')
plt.legend();
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_23_0.png

There are many other ways to explore and visualize the pathological region in the parameter space. For example, we can reproduce Figure 5b in Visualization in Bayesian workflow

In [12]:
tracedf = pm.trace_to_dataframe(short_trace)
plotorder = ['mu', 'tau', 'theta__0', 'theta__1', 'theta__2', 'theta__3', 'theta__4',
             'theta__5', 'theta__6', 'theta__7']
tracedf = tracedf[plotorder]

_, ax = plt.subplots(1, 2, figsize=(15, 4), sharex=True, sharey=True)
ax[0].plot(tracedf.values[divergent == 0].T, color='k', alpha=.025)
ax[0].plot(tracedf.values[divergent == 1].T, color='C2', lw=.5)

ax[1].plot(tracedf.values[divergent == 0].T, color='k', alpha=.025)
ax[1].plot(tracedf.values[divergent == 1].T, color='C2', lw=.5)
divsp = np.hstack([divergent_point['mu'][:,None],
                   np.exp(divergent_point['tau_log__'])[:,None],
                   divergent_point['theta']])
ax[1].plot(divsp.T, 'C3', lw=.5)
plt.ylim([-20,40])
plt.xticks(range(10), plotorder)
plt.tight_layout();
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_25_0.png
In [13]:
# A small wrapper function for displaying the MCMC sampler diagnostics as above
def report_trace(trace):
    # plot the trace of log(tau)
    pm.traceplot(trace, varnames=['tau'], transform=np.log)

    # plot the estimate for the mean of log(τ) cumulating mean
    logtau = np.log(trace['tau'])
    mlogtau = [np.mean(logtau[:i]) for i in np.arange(1, len(logtau))]
    plt.figure(figsize=(15, 4))
    plt.axhline(0.7657852, lw=2.5, color='gray')
    plt.plot(mlogtau, lw=2.5)
    plt.ylim(0, 2)
    plt.xlabel('Iteration')
    plt.ylabel('MCMC mean of log(tau)')
    plt.title('MCMC estimation of log(tau)')
    plt.show()

    # display the total number and percentage of divergent
    divergent = trace['diverging']
    print('Number of Divergent %d' % divergent.nonzero()[0].size)
    divperc = divergent.nonzero()[0].size / len(trace) * 100
    print('Percentage of Divergent %.1f' % divperc)

    # scatter plot between log(tau) and theta[0]
    # for the identifcation of the problematic neighborhoods in parameter space
    pm.pairplot(trace,
               sub_varnames=['theta_0', 'tau_log__'],
               divergences=True,
               color='C3', figsize=(10, 5), kwargs_divergence={'color':'C2'})
    plt.title('scatter plot between log(tau) and theta[0]');

A Safer, Longer Markov Chain

Given the potential insensitivity of split \(\hat{R}\) on single short chains, Stan recommend always running multiple chains as long as possible to have the best chance to observe any obstructions to geometric ergodicity. Because it is not always possible to run long chains for complex models, however, divergences are an incredibly powerful diagnostic for biased MCMC estimation.

In [14]:
with Centered_eight:
    longer_trace = pm.sample(4000, chains=2, tune=1000, random_seed=SEED)
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 5000/5000 [00:10<00:00, 455.96it/s]
There were 105 divergences after tuning. Increase `target_accept` or reparameterize.
There were 228 divergences after tuning. Increase `target_accept` or reparameterize.
The acceptance probability does not match the target. It is 0.5192263333577541, but should be close to 0.8. Try to increase the number of tuning steps.
The estimated number of effective samples is smaller than 200 for some parameters.
In [15]:
report_trace(longer_trace)
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_29_0.png
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_29_1.png
Number of Divergent 333
Percentage of Divergent 8.3
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_29_3.png
In [16]:
pm.summary(longer_trace).round(2)
Out[16]:
mean sd mc_error hpd_2.5 hpd_97.5 n_eff Rhat
mu 4.32 3.22 0.12 -1.98 10.62 458.33 1.02
theta__0 6.19 5.56 0.16 -4.27 18.22 432.74 1.00
theta__1 4.78 4.77 0.16 -4.43 14.66 113.48 1.02
theta__2 3.92 5.36 0.13 -7.19 14.98 1549.72 1.00
theta__3 4.69 4.70 0.12 -4.90 14.15 864.23 1.01
theta__4 3.46 4.64 0.13 -5.48 13.34 793.89 1.01
theta__5 4.06 4.70 0.12 -5.94 13.29 1261.23 1.01
theta__6 6.39 4.99 0.15 -2.45 17.32 707.78 1.00
theta__7 4.73 5.27 0.14 -5.62 15.67 850.21 1.01
tau 3.80 3.18 0.16 0.60 10.03 75.81 1.00

Similar to the result in Stan, \(\hat{R}\) does not indicate any serious issues. However, the effective sample size per iteration has drastically fallen, indicating that we are exploring less efficiently the longer we run. This odd behavior is a clear sign that something problematic is afoot. As shown in the trace plot, the chain occasionally “sticks” as it approaches small values of \(\tau\), exactly where we saw the divergences concentrating. This is a clear indication of the underlying pathologies. These sticky intervals induce severe oscillations in the MCMC estimators early on, until they seem to finally settle into biased values.

In fact the sticky intervals are the Markov chain trying to correct the biased exploration. If we ran the chain even longer then it would eventually get stuck again and drag the MCMC estimator down towards the true value. Given an infinite number of iterations this delicate balance asymptotes to the true expectation as we’d expect given the consistency guarantee of MCMC. Stopping after any finite number of iterations, however, destroys this balance and leaves us with a significant bias.

More details can be found in Betancourt’s recent paper.

Mitigating Divergences by Adjusting PyMC3’s Adaptation Routine

Divergences in Hamiltonian Monte Carlo arise when the Hamiltonian transition encounters regions of extremely large curvature, such as the opening of the hierarchical funnel. Unable to accurate resolve these regions, the transition malfunctions and flies off towards infinity. With the transitions unable to completely explore these regions of extreme curvature, we lose geometric ergodicity and our MCMC estimators become biased.

Algorithm implemented in Stan uses a heuristic to quickly identify these misbehaving trajectories, and hence label divergences, without having to wait for them to run all the way to infinity. This heuristic can be a bit aggressive, however, and sometimes label transitions as divergent even when we have not lost geometric ergodicity.

To resolve this potential ambiguity we can adjust the step size, \(\epsilon\), of the Hamiltonian transition. The smaller the step size the more accurate the trajectory and the less likely it will be mislabeled as a divergence. In other words, if we have geometric ergodicity between the Hamiltonian transition and the target distribution then decreasing the step size will reduce and then ultimately remove the divergences entirely. If we do not have geometric ergodicity, however, then decreasing the step size will not completely remove the divergences.

Like Stan, the step size in PyMC3 is tuned automatically during warm up, but we can coerce smaller step sizes by tweaking the configuration of PyMC3’s adaptation routine. In particular, we can increase the target_accept parameter from its default value of 0.8 closer to its maximum value of 1.

Adjusting Adaptation Routine

In [17]:
with Centered_eight:
    fit_cp85 = pm.sample(5000, chains=2, tune=2000,
                         nuts_kwargs=dict(target_accept=.85))
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 7000/7000 [00:16<00:00, 431.92it/s]
There were 210 divergences after tuning. Increase `target_accept` or reparameterize.
There were 122 divergences after tuning. Increase `target_accept` or reparameterize.
The number of effective samples is smaller than 10% for some parameters.
In [18]:
with Centered_eight:
    fit_cp90 = pm.sample(5000, chains=2, tune=2000,
                         nuts_kwargs=dict(target_accept=.90))
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 7000/7000 [00:15<00:00, 444.34it/s]
There were 108 divergences after tuning. Increase `target_accept` or reparameterize.
The acceptance probability does not match the target. It is 0.7681042731609842, but should be close to 0.9. Try to increase the number of tuning steps.
There were 186 divergences after tuning. Increase `target_accept` or reparameterize.
The number of effective samples is smaller than 10% for some parameters.
In [19]:
with Centered_eight:
    fit_cp95 = pm.sample(5000, chains=2, tune=2000,
                         nuts_kwargs=dict(target_accept=.95))
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 7000/7000 [00:32<00:00, 214.59it/s]
There were 59 divergences after tuning. Increase `target_accept` or reparameterize.
There were 246 divergences after tuning. Increase `target_accept` or reparameterize.
The acceptance probability does not match the target. It is 0.8854456149540602, but should be close to 0.95. Try to increase the number of tuning steps.
The number of effective samples is smaller than 10% for some parameters.
In [20]:
with Centered_eight:
    fit_cp99 = pm.sample(5000, chains=2, tune=2000,
                         nuts_kwargs=dict(target_accept=.99))
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta, tau_log__, mu]
100%|██████████| 7000/7000 [00:58<00:00, 120.01it/s]
There were 20 divergences after tuning. Increase `target_accept` or reparameterize.
There were 51 divergences after tuning. Increase `target_accept` or reparameterize.
The acceptance probability does not match the target. It is 0.9655538350420538, but should be close to 0.99. Try to increase the number of tuning steps.
The number of effective samples is smaller than 10% for some parameters.
In [21]:
df = pd.DataFrame([longer_trace['step_size'].mean(),
                  fit_cp85['step_size'].mean(),
                  fit_cp90['step_size'].mean(),
                  fit_cp95['step_size'].mean(),
                  fit_cp99['step_size'].mean()], columns=['Step_size'])
df['Divergent'] = pd.Series([longer_trace['diverging'].sum(),
                            fit_cp85['diverging'].sum(),
                            fit_cp90['diverging'].sum(),
                            fit_cp95['diverging'].sum(),
                            fit_cp99['diverging'].sum()])
df['delta_target'] = pd.Series(['.80', '.85', '.90', '.95', '.99'])
df
Out[21]:
Step_size Divergent delta_target
0 0.375381 333 .80
1 0.304575 332 .85
2 0.252309 294 .90
3 0.073495 305 .95
4 0.032518 71 .99

Here, the number of divergent transitions dropped dramatically when delta was increased to 0.99.

This behavior also has a nice geometric intuition. The more we decrease the step size the more the Hamiltonian Markov chain can explore the neck of the funnel. Consequently, the marginal posterior distribution for \(log (\tau)\) stretches further and further towards negative values with the decreasing step size.

Since in PyMC3 after tuning we have a smaller step size than Stan, the geometery is better explored.

However, the Hamiltonian transition is still not geometrically ergodic with respect to the centered implementation of the Eight Schools model. Indeed, this is expected given the observed bias.

In [22]:
_, ax = plt.subplots(1, 1, figsize=(10, 6))

pm.pairplot(fit_cp99, sub_varnames=['theta_1', 'tau_log__'], ax=ax,
               color='C3', alpha=0.6, label='Centered, delta=0.85')

pm.pairplot(longer_trace, sub_varnames=['theta_1', 'tau_log__'], ax=ax,
               color='C1', alpha=0.6, label='Centered, delta=0.99')

plt.title('scatter plot between log(tau) and theta[1]')
plt.legend();
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_40_0.png
In [23]:
logtau0 = longer_trace['tau_log__']
logtau2 = np.log(fit_cp90['tau'])
logtau1 = fit_cp99['tau_log__']

plt.figure(figsize=(15, 4))
plt.axhline(0.7657852, lw=2.5, color='gray')
mlogtau0 = [np.mean(logtau0[:i]) for i in np.arange(1, len(logtau0))]
plt.plot(mlogtau0, label='Centered, delta=0.85', lw=2.5)
mlogtau2 = [np.mean(logtau2[:i]) for i in np.arange(1, len(logtau2))]
plt.plot(mlogtau2, label='Centered, delta=0.90', lw=2.5)
mlogtau1 = [np.mean(logtau1[:i]) for i in np.arange(1, len(logtau1))]
plt.plot(mlogtau1, label='Centered, delta=0.99', lw=2.5)
plt.ylim(0, 2)
plt.xlabel('Iteration')
plt.ylabel('MCMC mean of log(tau)')
plt.title('MCMC estimation of log(tau)')
plt.legend();
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_41_0.png

A Non-Centered Eight Schools Implementation

Although reducing the step size improves exploration, ultimately it only reveals the true extent the pathology in the centered implementation. Fortunately, there is another way to implement hierarchical models that does not suffer from the same pathologies.

In a non-centered parameterization we do not try to fit the group-level parameters directly, rather we fit a latent Gaussian variable from which we can recover the group-level parameters with a scaling and a translation.

\[\mu \sim \mathcal{N}(0, 5)\]
\[\tau \sim \text{Half-Cauchy}(0, 5)\]
\[\tilde{\theta}_{n} \sim \mathcal{N}(0, 1)\]
\[\theta_{n} = \mu + \tau \cdot \tilde{\theta}_{n}.\]

Stan model:

data {
  int<lower=0> J;
  real y[J];
  real<lower=0> sigma[J];
}

parameters {
  real mu;
  real<lower=0> tau;
  real theta_tilde[J];
}

transformed parameters {
  real theta[J];
  for (j in 1:J)
    theta[j] = mu + tau * theta_tilde[j];
}

model {
  mu ~ normal(0, 5);
  tau ~ cauchy(0, 5);
  theta_tilde ~ normal(0, 1);
  y ~ normal(theta, sigma);
}
In [24]:
with pm.Model() as NonCentered_eight:
    mu = pm.Normal('mu', mu=0, sd=5)
    tau = pm.HalfCauchy('tau', beta=5)
    theta_tilde = pm.Normal('theta_t', mu=0, sd=1, shape=J)
    theta = pm.Deterministic('theta', mu + tau * theta_tilde)
    obs = pm.Normal('obs', mu=theta, sd=sigma, observed=y)
In [25]:
with NonCentered_eight:
    fit_ncp80 = pm.sample(5000, chains=2, tune=1000, random_seed=SEED,
                         nuts_kwargs=dict(target_accept=.80))
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta_t, tau_log__, mu]
100%|██████████| 6000/6000 [00:06<00:00, 964.62it/s]
There were 5 divergences after tuning. Increase `target_accept` or reparameterize.
There were 3 divergences after tuning. Increase `target_accept` or reparameterize.
In [26]:
pm.summary(fit_ncp80).round(2)
Out[26]:
mean sd mc_error hpd_2.5 hpd_97.5 n_eff Rhat
mu 4.38 3.30 0.03 -2.49 10.57 11024.33 1.0
theta_t__0 0.33 0.98 0.01 -1.62 2.21 14375.77 1.0
theta_t__1 0.09 0.96 0.01 -1.82 1.91 13212.45 1.0
theta_t__2 -0.08 0.95 0.01 -1.95 1.76 14160.93 1.0
theta_t__3 0.06 0.96 0.01 -1.86 1.91 14159.81 1.0
theta_t__4 -0.17 0.93 0.01 -1.94 1.74 13618.34 1.0
theta_t__5 -0.08 0.94 0.01 -1.85 1.86 14357.32 1.0
theta_t__6 0.36 0.97 0.01 -1.55 2.18 11769.38 1.0
theta_t__7 0.08 0.98 0.01 -1.81 2.00 12260.39 1.0
tau 3.71 3.32 0.04 0.00 10.31 6344.00 1.0
theta__0 6.31 5.71 0.06 -4.55 17.98 9310.19 1.0
theta__1 4.94 4.69 0.04 -4.49 14.38 11068.91 1.0
theta__2 3.92 5.19 0.06 -7.36 13.73 10019.67 1.0
theta__3 4.76 4.84 0.05 -4.90 14.65 11157.51 1.0
theta__4 3.51 4.61 0.04 -6.24 12.18 10478.96 1.0
theta__5 3.98 4.82 0.05 -5.71 13.64 10618.70 1.0
theta__6 6.35 5.13 0.05 -3.60 16.64 9684.43 1.0
theta__7 4.86 5.27 0.05 -6.19 15.27 10132.72 1.0

As shown above, the effective sample size per iteration has drastically improved, and the trace plots no longer show any “stickyness”. However, we do still see the rare divergence. These infrequent divergences do not seem concentrate anywhere in parameter space, which is indicative of the divergences being false positives.

In [27]:
report_trace(fit_ncp80)
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_47_0.png
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_47_1.png
Number of Divergent 8
Percentage of Divergent 0.2
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_47_3.png

As expected of false positives, we can remove the divergences entirely by decreasing the step size,

In [28]:
with NonCentered_eight:
    fit_ncp90 = pm.sample(5000, chains=2, tune=1000, random_seed=SEED,
                         nuts_kwargs=dict(target_accept=.90))

# display the total number and percentage of divergent
divergent = fit_ncp90['diverging']
print('Number of Divergent %d' % divergent.nonzero()[0].size)
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (2 chains in 2 jobs)
NUTS: [theta_t, tau_log__, mu]
100%|██████████| 6000/6000 [00:08<00:00, 746.35it/s]
Number of Divergent 0

The more agreeable geometry of the non-centered implementation allows the Markov chain to explore deep into the neck of the funnel, capturing even the smallest values of \(\tau\) that are consistent with the measurements. Consequently, MCMC estimators from the non-centered chain rapidly converge towards their true expectation values.

In [29]:
_, ax = plt.subplots(1, 1, figsize=(10, 6))

pm.pairplot(fit_ncp80, sub_varnames=['theta_0', 'tau_log__'], ax=ax,
               color='C0', alpha=0.6, label='Centered, delta=0.80')

pm.pairplot(fit_cp99, sub_varnames=['theta_0', 'tau_log__'], ax=ax,
               color='C3', alpha=0.6, label='Centered, delta=0.99')

pm.pairplot(fit_cp90, sub_varnames=['theta_0', 'tau_log__'], ax=ax,
               color='C1', alpha=0.6, label='Centered, delta=0.90')
plt.title('scatter plot between log(tau) and theta[1]')
plt.legend();

../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_51_0.png
In [30]:
logtaun = fit_ncp80['tau_log__']

plt.figure(figsize=(15, 4))
plt.axhline(0.7657852, lw=2.5, color='gray')
mlogtaun = [np.mean(logtaun[:i]) for i in np.arange(1, len(logtaun))]
plt.plot(mlogtaun, color='C0', lw=2.5, label='Non-Centered, delta=0.80')

mlogtau1 = [np.mean(logtau1[:i]) for i in np.arange(1, len(logtau1))]
plt.plot(mlogtau1, color='C3', lw=2.5, label='Centered, delta=0.99')

mlogtau0 = [np.mean(logtau0[:i]) for i in np.arange(1, len(logtau0))]
plt.plot(mlogtau0, color='C1', lw=2.5, label='Centered, delta=0.90')
plt.ylim(0, 2)
plt.xlabel('Iteration')
plt.ylabel('MCMC mean of log(tau)')
plt.title('MCMC estimation of log(tau)')
plt.legend();
../_images/notebooks_Diagnosing_biased_Inference_with_Divergences_52_0.png