Illustration of simple problematic posteriors

Author

Aki Vehtari

Published

2021-06-10

Modified

2026-07-10

This notebook includes the code for Bayesian Workflow book Section 12.3 Failure modes and steps forward.

1 Introduction

This case study demonstrates using simple examples the most common failure modes in Markov chain Monte Carlo based Bayesian inference, how to recognize these using the diagnostics, and how to fix the problems.

Load packages

import sys
import warnings

sys.path.insert(0, "..")

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
from cmdstanpy import CmdStanModel, disable_logging
import arviz as az

from utils import print_stan

# Set plotting style
az.style.use("arviz-variat")
plt.rcParams["figure.dpi"] = 100

warnings.filterwarnings("ignore")
disable_logging()

SEED = 48927
np.random.seed(SEED)
/home/osvaldo/anaconda3/envs/bwb/lib/python3.14/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm

2 Improper posterior

An unbounded likelihood without a proper prior can lead to an improper posterior. We recommend to always use proper priors (integral over a proper distribution is finite) to guarantee proper posteriors.

A commonly used model that can have unbounded likelihood is logistic regression with complete separation in data.

2.1 Data

Univariate continous predictor \(x\), binary target \(y\), and the two classes are completely separable, which leads to unbounded likelihood.

rng = np.random.default_rng(SEED + 4)
M = 1
N = 10
# x = np.sort(rng.normal(size=(N, M)), axis=0)
x = np.array(
    [
        [-1.61675183],
        [-0.94052670],
        [-0.66244057],
        [-0.60232373],
        [-0.57819996],
        [-0.30952063],
        [-0.23880912],
        [-0.19792298],
        [0.04290007],
        [1.10171923],
    ]
)
y = np.repeat([0, 1], N / 2)
data_logit = {"M": M, "N": N, "x": x, "y": y}
df = pd.DataFrame({"x": x.flatten(), "y": y})
_, ax = plt.subplots(figsize=(6, 3))

ax.scatter(df["x"], df["y"])
ax.set(yticks=[0, 1], xlabel="x", ylabel="y");
Figure 1

2.2 Model

We use the following Stan logistic regression model, where we have “forgot” to include prior for the coefficient beta.

mod_logit = CmdStanModel(stan_file=str("logit_glm.stan"))
print_stan(mod_logit)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0,upper=1> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
}
model {
  y ~ bernoulli_logit_glm(x, alpha, beta);
}

Sample

fit_logit = mod_logit.sample(data=data_logit, seed=SEED, show_progress=False)
dt_logit = az.from_cmdstanpy(fit_logit)

2.3 Convergence diagnostics

When running Stan, we get warnings. We can also explicitly check the inference diagnostics:

az.diagnose(dt_logit)
Divergences
1520 of 4000 (38.00%) transitions ended with a divergence.
These divergent transitions indicate that HMC is not fully able to explore the posterior distribution.
Try increasing adapt delta closer to 1.
If this doesn't remove all divergences, try to reparameterize the model.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
The following parameters has fewer than 400 effective samples:
  alpha, beta
This suggests that the sampler may not have fully explored the posterior distribution for this parameter.
Consider reparameterizing the model or increasing the number of samples.

R-hat
The following parameters has R-hat values greater than 1.01:
  alpha, beta
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.
True

We can also check \(\widehat{R}\) and effective sample size (ESS) diagnostics(Vehtari et al. 2021)

az.summary(dt_logit)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 2e+45 4e+45 4.7e+23 1.1e+46 4 5 3.11 1.7e+45 1.7e+45
beta[0] 4e+45 9e+45 1.1e+24 2.5e+46 4 5 3.07 3.8e+45 4e+45

We see that \(\widehat{R}\) for both alpha and beta are about 3 or 4 and ESS is about 4, which indicate that the chains are not mixing at all.

The above diagnostics refer to a documentation (https://mc-stan.org/misc/warnings) that mentions possibility to adjust the sampling algorithm options (e.g., increasing adapt_delta and max_treedepth), but it is better first to investigate the posterior.

The following Figure shows the posterior draws as marginal histograms and joint scatterplots. The range of the values is huge, which is typical for improper posterior, but the values of alpha and beta in any practical application are likely to have much smaller magnitude. In this case, increasing adapt_delta and max_treedepth would not have solved the problem, and would have just caused waste of modeler and computation time.

az.plot_pair(
    dt_logit,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 2

2.3.1 Stan compiler pedantic check

The above diagnostics are applicable with any probabilistic programming framework. Stan compiler can also recognize some common problems. By default the pedantic mode is not enabled, but we can use option pedantic = TRUE at compilation time.

The pedantic check correctly warns that alpha and beta don’t have priors.

2.4 A fixed model with proper priors

We add proper weak priors and rerun inference.

mod_logit2 = CmdStanModel(stan_file="logit_glm2.stan")
print_stan(mod_logit2)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0,upper=1> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
}
model {
  alpha ~ normal(0,10);
  beta ~ normal(0,10);
  y ~ bernoulli_logit_glm(x, alpha, beta);
}

Sample

fit_logit2 = mod_logit2.sample(data=data_logit, seed=SEED, show_progress=False)
dt_logit2 = az.from_cmdstanpy(fit_logit2)

2.4.1 Convergence diagnostics

There were no convergence warnings. We can also explicitly check the inference diagnostics:

az.diagnose(dt_logit2)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False

We check \(\widehat{R}\) and ESS values, which in this case all look good.

az.summary(dt_logit2)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 6.1 2.8 2 11 675 958 1.00 0.11 0.086
beta[0] 14.3 5.9 5.7 25 687 968 1.00 0.23 0.16

The following figure shows the more reasonable marginal histograms and joint scatterplots of the posterior sample.

az.plot_pair(
    dt_logit2,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 3

3 A model with unused parameter

When writing and editing models, a common mistake is to declare a parameter, but not use it in the model. If the parameter is not used at all, it doesn’t have proper prior and the likelihood doesn’t provide information about that parameter, and thus the posterior along that parameter is improper. We use the previous logistic regression model with proper priors on alpha and beta, but include extra parameter declaration real gamma.

3.1 Model

mod_logit3 = CmdStanModel(stan_file="logit_glm3.stan")
print_stan(mod_logit3)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0,upper=1> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
  real gamma;
}
model {
  alpha ~ normal(0,1);
  beta ~ normal(0,1);
  y ~ bernoulli_logit_glm(x, alpha, beta);
}

Sample

fit_logit3 = mod_logit3.sample(data=data_logit, seed=SEED, show_progress=False)
dt_logit3 = az.from_cmdstanpy(fit_logit3)

3.1.1 Convergence diagnostics

There is sampler warning. We can also explicitly call inference diagnostics:

az.diagnose(dt_logit3)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
The following parameters has fewer than 400 effective samples:
  gamma
This suggests that the sampler may not have fully explored the posterior distribution for this parameter.
Consider reparameterizing the model or increasing the number of samples.

R-hat
The following parameters has R-hat values greater than 1.01:
  gamma
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.
True

Instead of increasing max_treedepth, we check the other convergence diagnostics.

az.summary(dt_logit3)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 0.35 0.6 -0.61 1.3 3877 3107 1.00 0.0097 0.0067
beta[0] 1.26 0.78 0.05 2.5 3814 2821 1.00 0.013 0.0094
gamma -3e+18 3e+19 -4.9e+19 4.7e+19 14 16 1.49 7.4e+18 8e+18

\(\widehat{R}\), ESS look good for alpha and beta, but really bad for gamma, clearly pointing where to look for problems in the model code. The histogram of gamma posterior draws show huge magnitude of values (values larger than \(10^{20}\)) indicating improper posterior.

az.plot_pair(
    dt_logit3,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 4

Non-mixing is well diagnosed by \(\widehat{R}\) and ESS, but the following Figure shows one of the rare cases where trace plots are useful to illustrate the type of non-mixing in case of improper uniform posterior for one the parameters.

az.plot_trace(dt_logit3, var_names=["gamma"])
Figure 5

3.2 Stan compiler pedantic check

Stan compiler pedantic check also recognizes that parameter gamma was declared but was not used in the density calculation.

4 A posterior with two parameters competing

Sometimes the models have two or more parameters that have similar or exactly the same role. We illustrate this by adding an extra column to the previous data matrix. Sometimes the data matrix is augmented with a column of 1’s to present the intercept effect. In this case that is redundant as our model has the explicit intercept term alpha, and this redundancy will lead to problems.

4.1 Data

M = 2
N = 1000
x = np.column_stack([np.ones(N), np.sort(np.random.randn(N))])
y = ((x[:, 0] + np.random.randn(N) / 2) > 0).astype(int)
data_logit4 = {"M": M, "N": N, "x": x, "y": y}

4.2 Model

We use the previous logistic regression model with proper priors (and no extra gamma).

print_stan(mod_logit2)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0,upper=1> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
}
model {
  alpha ~ normal(0,10);
  beta ~ normal(0,10);
  y ~ bernoulli_logit_glm(x, alpha, beta);
}

Sample

mod_logit4 = CmdStanModel(stan_file="logit_glm2.stan")
fit_logit4 = mod_logit4.sample(data=data_logit4, seed=SEED, show_progress=False)
dt_logit4 = az.from_cmdstanpy(fit_logit4)

The Stan sampling time per chain with the original data matrix was less than 0.1s per chain. Now the Stan sampling time per chain is several seconds, which is suspicious. There are no automatic convergence diagnostic warnings and checking other diagnostics don’t show anything really bad.

4.3 Convergence diagnostics

az.diagnose(dt_logit4)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False
az.summary(dt_logit4)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 1.9 7.2 -9.2 14 938 963 1.01 0.24 0.16
beta[0] 1.8 7.2 -10 13 938 974 1.01 0.24 0.17
beta[1] -0.19 0.215 -0.53 0.16 1226 1489 1.00 0.0061 0.0043

ESS estimates are above the recommended diagnostic thresholds (Vehtari et al. 2021), but lower than what we would expect in general from Stan for such a lower dimensional problem.

The following figure shows marginal histograms and joint scatterplots, and we can see that alpha and beta_0 are highly correlated.

az.plot_pair(
    dt_logit4,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 6

We can compute the correlation.

posterior_samples = az.extract(dt_logit4)
alpha_samples = posterior_samples["alpha"].values
beta_samples = posterior_samples["beta"].values
correlation = np.corrcoef(alpha_samples, beta_samples)[0, 1]
print(f"Correlation: {correlation:.2f}")
Correlation: -1.00

The numerical value for the correlation is \(-1\). The correlation close to 1 can happen also from other reasons (see the next example), but one possibility is that parameters have similar role in the model. Here the reason is the constant column in \(x\), which we put there for the demonstration purposes. We may have constant column, for example, if the predictor matrix is augmented with the intercept predictor, or if the observed data or subdata used in the specific analysis happens to have only one unique value.

4.4 Stan compiler pedantic check

Stan compiler pedantic check examining the code can’t recognize this issue, as the problem depends also on the data.

5 A posterior with very high correlation

In the previous example the two parameters had the same role in the model, leading to high posterior correlation. High posterior correlations are common also in linear models when the predictor values are far from 0. We illustrate this with a linear regression model for the summer temperature in Kilpisjärvi, Finland, 1952–2013. We use the year as the covariate \(x\) without centering it.

5.1 Data

The data are Kilpisjärvi summer month temperatures 1952-2013 measured by Finnish Meteorological Institute.

data_kilpis = pd.read_csv("data/kilpisjarvi-summer-temp.csv", sep=";")
M = 1
N = len(data_kilpis)
x = data_kilpis["year"].values.reshape(-1, 1)
y = data_kilpis.iloc[:, 4].values
data_lin = {"M": M, "N": N, "x": x, "y": y}
_, ax = plt.subplots(figsize=(6, 4))
ax.scatter(x, y)
ax.set(xlabel="Year", ylabel="Summer temp. @Kilpisjärvi")
Figure 7

5.2 Model

We use the following Stan linear regression model

mod_lin = CmdStanModel(stan_file="linear_glm_kilpis.stan")
print_stan(mod_lin)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  vector[N] y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
  real sigma;
}
model {
  alpha ~ normal(0, 100);
  beta ~ normal(0, 100);
  sigma ~ normal(0, 1);
  y ~ normal_id_glm(x, alpha, beta, sigma);
}
fit_lin = mod_lin.sample(data=data_lin, seed=SEED, show_progress=False)
dt_lin = az.from_cmdstanpy(fit_lin)

5.2.1 Convergence diagnostics

Stan gives a warning: There were X transitions after warmup that exceeded the maximum treedepth. As in the previous example, there are no other warnings.

az.diagnose(dt_lin)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False
az.summary(dt_lin)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha -30.1 15.5 -55 -5.4 1067 1100 1.01 0.47 0.32
beta[0] 0.0199 0.0078 0.0074 0.032 1068 1097 1.01 0.00024 0.00016
sigma 1.123 0.109 0.97 1.3 1228 1263 1.01 0.0032 0.0028

ESS estimates are above the diagnostic threshold, but lower than we would expect for such a low dimensional model, unless there are strong posterior correlations. The following figure shows the marginal histograms and joint scatterplot for alpha and beta_0, which shows they are very highly correlated.

az.plot_pair(
    dt_lin,
    var_names=["alpha", "beta"],
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 8

Here the reason is that the \(x\) values are in the range 1952–2013, and the intercept alpha denotes the temperature at year 0, which is very far away from the range of observed \(x\). If the intercept alpha changes, the slope beta needs to change too. The high correlation makes the inference slower, and we can make it faster by centering \(x\). Here we simply subtract 1982.5 from the predictor year, so that the mean of \(x\) is 0. We could also include the centering and back transformation in the Stan code.

5.3 Centered data

x_centered = data_kilpis["year"].values - 1982.5
data_lin = {"M": M, "N": N, "x": np.atleast_2d(x_centered).T, "y": y}
fit_lin = mod_lin.sample(data=data_lin, seed=SEED, show_progress=False)
dt_lin = az.from_cmdstanpy(fit_lin)

5.4 Convergence diagnostics

We check the diagnostics

az.diagnose(dt_lin)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False
az.summary(dt_lin)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 9.315 0.144 9.1 9.5 3393 2877 1.00 0.0025 0.0018
beta[0] 0.0204 0.008 0.0076 0.033 4360 3005 1.00 0.00012 8.9e-05
sigma 1.12 0.106 0.97 1.3 2986 2205 1.00 0.002 0.0016

The following figure shows the scatter plot.

az.plot_pair(
    dt_lin,
    var_names=["alpha", "beta"],
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 9

With this change, there is no posterior correlation, ESS estimates are 3 times bigger, and the mean time per chain goes from 1.3s to less than 0.05s; that is, we get 2 orders of magnitude faster inference. In a bigger problems this could correspond to reduction of computation time from 24 hours to less than 20 minutes.

6 A bimodal posterior

Bimodal distributions can arise from many reasons as in mixture models or models with non-log-concave likelihoods or priors (that is, with distributions with thick tails). We illustrate the diagnostics revealing the multimodal posterior. We use a simple toy problem with \(t\) model and data that is not from a \(t\) distribution, but from a mixture of two normal distributions.

6.1 Data

Bimodally distributed data

N = 20
y = np.concatenate([np.random.normal(-5, 1, N // 2), np.random.normal(5, 1, N // 2)])
data_tt = {"N": N, "y": y}

6.2 Model

Unimodal Student’s \(t\) model:

mod_tt = CmdStanModel(stan_file="student.stan")
print_stan(mod_tt)
// student-student model
data {
  int<lower=0> N;
  vector[N] y;
}
parameters {
  real mu;
}
model {
  mu ~ student_t(4, 0, 100);
  y ~ student_t(4, mu, 1);
}

Sample

fit_tt = mod_tt.sample(data=data_tt, seed=SEED, show_progress=False)
dt_tt = az.from_cmdstanpy(fit_tt)

6.2.1 Convergence diagnostics

We check the diagnostics

az.diagnose(dt_tt)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
The following parameters has fewer than 400 effective samples:
  mu
This suggests that the sampler may not have fully explored the posterior distribution for this parameter.
Consider reparameterizing the model or increasing the number of samples.

R-hat
The following parameters has R-hat values greater than 1.01:
  mu
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.
True
az.summary(dt_tt)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
mu -0 3.9 -4.6 4.1 6 40 1.73 1.9 0.23

The \(\widehat{R}\) values for mu are large and ESS values for mu are small indicating convergence problems. The following figure shows the histogram and trace plots of the posterior draws, clearly showing the bimodality and that chains are not mixing between the modes.

az.plot_dist(
    dt_tt,
    kind="hist",
    visuals={
        "point_estimate": False,
        "point_estimate_text": False,
        "credible_interval": False,
    },
)
Figure 10

In this toy example, with random initialization each chain has 50% probability of ending in either mode. We used Stan’s default of 4 chains, and when random initialization is used, there is 6% chance that when running Stan once, we would miss the multimodality. If the attraction areas within the random initialization range are not equal, the probability of missing one mode is even higher. There is a tradeoff between the default computation cost and cost of having higher probability of finding multiple modes. If there is a reason to suspect multimodality, it is useful to run more chains. Running more chains helps to diagnose the multimodality, but the probability of chains ending in different modes can be different from the relative probability mass of each mode, and running more chains doesn’t fix this. Other means are needed to improve mixing between the modes (e.g. Yao et al., 2020) or to approxima|tely weight the chains (e.g. Yao et al., 2022).

7 Easy bimodal posterior

If the modes in the bimodal distribution are not strongly separated, MCMC can jump from one mode to another and there are no convergence issues.

N = 20
y = np.concatenate([rng.normal(-3, 1, N // 2), rng.normal(3, 1, N // 2)])
data_tt = {"N": N, "y": y}
fit_tt = mod_tt.sample(data=data_tt, seed=SEED, show_progress=False)
dt_tt = az.from_cmdstanpy(fit_tt)

7.1 Convergence diagnostics

We check the diagnostics

az.diagnose(dt_tt)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False
az.summary(dt_tt)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
mu 0.4 1.2 -1.6 2 549 870 1.01 0.055 0.026

Two modes are visible.

az.plot_dist(dt_tt, kind="hist")
Figure 11

Trace plot is not very useful. It shows the chains are jumping between modes, but it’s difficult to see whether the jumps happen often enough and chains are mixing well.

az.plot_trace(dt_tt);
Figure 12

Rank plot (Säilynoja, Bürkner, and Vehtari 2022) indicates good mixing as all chains have their lines inside the envelope. The envelope assumes no autocorrelation, hence az.plot_rank automatically thins the draws here. This can be disable by passing the argument.thin=False.

az.plot_rank(dt_tt)
Figure 13

8 Initial value issues

MCMC requires some initial values. By default, Stan generates them randomly from [-2,2] in unconstrained space (constraints on parameters are achieved by transformations). Sometimes these initial values can be bad and cause numerical issues. Computers,(in general) use finite number of bits to present numbers and with very small or large numbers, there can be problems of presenting them or there can be significant loss of accuracy.

The data is generated from a Poisson regression model. The Poisson intensity parameter has to be positive and usually the latent linear predictor is exponentiated to be positive (the exponentiation can also be justified by multiplicative effects on Poisson intensity).

We intentionally generate the data so that there are initialization problems, but the same problem is common with real data when the scale of the predictors is large or small compared to the unit scale. The following figure shows the simulated data.

8.1 Data

np.random.seed(SEED + 6)
M = 1
N = 20
x = 1e3 * np.sort(np.random.randn(N)).reshape(-1, M)
y = np.random.poisson(np.exp(1e-3 * x[:, 0]))
data_pois = {"M": M, "N": N, "x": x, "y": y}
_, ax = plt.subplots(figsize=(6, 3))
ax.scatter(x, y)
ax.set(xlabel='x', ylabel='y');
Figure 14

8.2 Model

We use a Poisson regression model with proper priors. The poisson_log_glm corresponds to a distribution in which the log intensity of the Poisson distribution is modeled with alpha + beta * x but is implemented with better computational efficiency.

mod_pois = CmdStanModel(stan_file="pois_glm.stan")
print_stan(mod_pois)
// Poisson regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
}
model {
  alpha ~ normal(0,10);
  beta ~ normal(0,10);
  y ~ poisson_log_glm(x, alpha, beta);
}

Sample

mod_pois = CmdStanModel(stan_file="pois_glm.stan")
fit_pois = mod_pois.sample(data=data_pois, seed=SEED, show_progress=False)
dt_pois = az.from_cmdstanpy(fit_pois)

We get a lot of warnings about rejecting initial values.

8.3 Convergence diagnostics

We check the diagnostics:

az.diagnose(dt_pois)
Divergences
No divergent transitions found.

E-BFMI
Chain 0: E-BFMI = 0.002
E-BFMI values are below the threshold 0.30 which suggests that HMC may have trouble exploring the target distribution.
If possible, try to reparameterize the model.

ESS
The following parameters has fewer than 400 effective samples:
  alpha, beta
This suggests that the sampler may not have fully explored the posterior distribution for this parameter.
Consider reparameterizing the model or increasing the number of samples.

R-hat
The following parameters has R-hat values greater than 1.01:
  alpha, beta
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.
True
dt_pois = az.from_cmdstanpy(fit_pois)
az.summary(dt_pois)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha -0.2 0.9 -1.7 0.57 7 4 1.53 0.42 0.23
beta[0] -0.01 0.02 -0.041 0.00099 6 4 1.60 0.0089 0.0051

\(\widehat{R}\) values are large and ESS values are small, indicating bad mixing. Marginal histograms and joint scatterplots of the posterior draws in the figure below clearly show that two chains have been stuck away from two others.

az.plot_pair(
    dt_pois,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 15

The reason for the issue is that the initial values for beta are sampled from \((-2, 2)\) and x has some large values. If the initial value for beta is higher than about 0.3 or lower than \(-0.4\), some of the values of exp(alpha + beta * x) will overflow to floating point infinity (Inf).

8.4 Scaled data

Sometimes an easy option is to change the initialization range. For example, in this case the sampling succeeds if the initial values are drawn from the range \((-0.001, 0.001)\). Alternatively we can scale x to have scale close to unit scale. After this scaling, the computation is fast and all convergence diagnostics look good.

data_pois = {'M': M, 'N': N, 'x': x / 1e3, 'y': y}
_, ax = plt.subplots(figsize=(6, 3))
ax.scatter(data_pois["x"], data_pois["y"])
ax.set(xlabel="x", ylabel="y")
Figure 16
fit_pois = mod_pois.sample(data=data_pois, seed=SEED, show_progress=False)
dt_pois = az.from_cmdstanpy(fit_pois)

8.5 Convergence diagnostics

We check the diagnostics:

az.diagnose(dt_pois)
Divergences
No divergent transitions found.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.

Processing complete, no problems detected.
False
az.summary(dt_pois)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 0.28 0.203 -0.039 0.6 1256 1423 1.00 0.0057 0.004
beta[0] 0.863 0.085 0.73 1 1302 1520 1.00 0.0023 0.0017

If the initial value warning comes only once, it is possible that MCMC was able to escape the bad region and rest of the inference is ok.

9 Thick tailed posterior

We return to the logistic regression example with separable data. Now we use proper, but thick tailed Cauchy prior.

9.1 Model

mod_logit_glm4 = CmdStanModel(stan_file="logit_glm4.stan")
print_stan(mod_logit_glm4)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  array[N] int<lower=0,upper=1> y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
}
model {
  alpha ~ cauchy(0, 10);
  beta ~ cauchy(0, 10);
  y ~ bernoulli_logit_glm(x, alpha, beta);
}

Sample

np.random.seed(SEED + 4)
M = 1
N = 10
x = np.sort(np.random.randn(N)).reshape(-1, M)
y = np.repeat([0, 1], N // 2)
data_logit = {"M": M, "N": N, "x": x, "y": y}

fit_logit_glm4 = mod_logit_glm4.sample(data=data_logit, seed=SEED, show_progress=False)
dt_logit_glm4 = az.from_cmdstanpy(fit_logit_glm4)

9.2 Convergence diagnostics

We check diagnostics

az.diagnose(dt_logit_glm4)
Divergences
1068 of 4000 (26.70%) transitions ended with a divergence.
These divergent transitions indicate that HMC is not fully able to explore the posterior distribution.
Try increasing adapt delta closer to 1.
If this doesn't remove all divergences, try to reparameterize the model.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
The following parameters has fewer than 400 effective samples:
  alpha, beta
This suggests that the sampler may not have fully explored the posterior distribution for this parameter.
Consider reparameterizing the model or increasing the number of samples.

R-hat
The following parameters has R-hat values greater than 1.01:
  alpha, beta
Such high values indicate incomplete mixing and biased estimation.
You should consider regularizing your model with additional prior information or a more effective parameterization.
True
az.summary(dt_logit_glm4)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 4 6 -1.4 15 140 238 1.03 0.5 0.99
beta[0] 8e+01 1e+02 5.3 290 150 278 1.02 9.2 18

The rounded \(\widehat{R}\) values look good, ESS values are low. Looking at the marginal histograms and joint scatterplots of the posterior draws in the following figure show a thick tail.

az.plot_pair(
    dt_logit_glm4,
    marginal_kind="hist",
    figure_kwargs={"figsize": (8, 4)},
    visuals={"divergence": True},
)
Figure 17

The dynamic HMC algorithm used by Stan, along with many other MCMC methods, have problems with such thick tails and mixing is slow.

Rank plot indicates good mixing as all chains have their lines inside the envelope. The envelope assumes no autocorrelation, hence az.plot_rank automatically thins the draws here. This can be disable by passing the argument.thin=False. Notice how the envelope looks highly stepped/jagged; because heavy thinning (due to low ESS) leaves so few draws to compute the rank plots and its envelope.

az.plot_rank(dt_logit_glm4, var_names=["alpha"])
Figure 18

More iterations confirm a reasonable mixing.

fit_logit_glm4 = mod_logit_glm4.sample(
    data=data_logit, 
    seed=SEED, 
    show_progress=False,
    iter_sampling=4000
)
idata_logit_glm4 = az.from_cmdstanpy(fit_logit_glm4)
az.summary(idata_logit_glm4)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 4.1 7 -1.5 16 564 857 1.01 0.29 0.74
beta[0] 9e+01 1e+02 5.2 300 636 903 1.01 5.9 22
az.plot_rank(dt_logit_glm4, var_names=["alpha"])
Figure 19

10 Variance parameter that is not constrained to be positive

Demonstration what happens if we forget to constrain a parameter that has to be positive. In Stan the constraint can be added when declaring the parameter as real<lower=0> sigma;

10.1 Data

We simulated x and y independently from normal(0,1) and normal(0,0.1) respectively. As \(N=8\) is small, there will be a lot of uncertainty about the parameters including the scale sigma.

M = 1
N = 8
np.random.seed(SEED)
x = np.random.randn(N).reshape(-1, M)
y = np.random.randn(N) / 10
data_lin = {'M': M, 'N': N, 'x': x, 'y': y}

10.2 Model

We use linear regression model with proper priors.

mod_lin = CmdStanModel(stan_file="linear_glm.stan")
print_stan(mod_lin)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  vector[N] y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
  real sigma;
}
model {
  alpha ~ normal(0, 1);
  beta ~ normal(0, 1);
  sigma ~ normal(0, 1);
  y ~ normal_id_glm(x, alpha, beta, sigma);
}

Sample

fit_lin = mod_lin.sample(data=data_lin, seed=SEED, show_progress=False)
idata_lin = az.from_cmdstanpy(fit_lin)

We get many warnings about the scale parameter being negative.

Sometimes these warnings appear in early phase of the sampling, even if the model has been correctly defined. Now we have too many of them, which indicates the sampler is trying to jump to infeasible values, which here means the negative scale parameter values. Many rejections may lead to biased estimates.

There are some divergences reported, which is also indication that there might be some problem (as divergence diagnostic has an ad hoc diagnostic threshold, there can also be false positive warnings). Other convergence diagnostics are good, but due to many rejection warnings, it is good to check the model code and numerical accuracy of the computations.

10.3 Convergence diagnostics

We check diagnostics

az.diagnose(idata_lin)
Divergences
3 of 4000 (0.07%) transitions ended with a divergence.
These divergent transitions indicate that HMC is not fully able to explore the posterior distribution.
Try increasing adapt delta closer to 1.
If this doesn't remove all divergences, try to reparameterize the model.

E-BFMI
E-BFMI satisfactory for all chains.

ESS
Effective sample size satisfactory for all parameters.

R-hat
R-hat values satisfactory for all parameters.
True
az.summary(idata_lin)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 0.018 0.049 -0.057 0.093 2348 1992 1.00 0.001 0.0011
beta[0] -0.005 0.045 -0.07 0.062 2130 1913 1.00 0.00096 0.0011
sigma 0.128 0.051 0.074 0.22 1520 1253 1.00 0.0016 0.0025

10.4 Stan compiler pedantic check

Stan compiler pedantic check can recognize that a normal distribution is given parameter sigma as a scale parameter, but sigma was not constrained to be strictly positive. The pedantic check is also warning about the very wide priors.

After fixing the model with proper parameter constraint, MCMC runs without warnings and the sampling efficiency is better. In this specific case, the bias is negligible when running MCMC with the model code without the constraint, but it is difficult to diagnose without running the fixed model.

Fixed model includes <lower=0> constraint for sigma.

mod_lin2 = CmdStanModel(stan_file="linear_glm2.stan")
print_stan(mod_lin2)
// logistic regression
data {
  int<lower=0> N;
  int<lower=0> M;
  vector[N] y;
  matrix[N,M] x;
}
parameters {
  real alpha;
  vector[M] beta;
  real<lower=0> sigma;
}
model {
  alpha ~ normal(0, 1);
  beta ~ normal(0, 1);
  sigma ~ normal(0, 1);
  y ~ normal_id_glm(x, alpha, beta, sigma);
}

Sample

fit_lin2 = mod_lin2.sample(data=data_lin, seed=SEED, show_progress=False)

We check diagnostics

idata_lin2 = az.from_cmdstanpy(fit_lin2)
az.summary(idata_lin2)
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
alpha 0.017 0.048 -0.059 0.093 2366 1601 1.01 0.001 0.00093
beta[0] -0.002 0.045 -0.071 0.068 2209 1854 1.00 0.001 0.0011
sigma 0.13 0.053 0.074 0.22 1570 1764 1.00 0.0014 0.0024

In this specific case, the bias is negligible when running MCMC with the model code without the constraint, but it is difficult to diagnose without running the fixed model.


References

Säilynoja, Teemu, Paul-Christian Bürkner, and Aki Vehtari. 2022. “Graphical Test for Discrete Uniformity and Its Applications in Goodness-of-Fit Evaluation and Multiple Sample Comparison.” Statistics and Computing 32: 1573–375.
Vehtari, Aki, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. 2021. “Rank-Normalization, Folding, and Localization: An Improved \(\widehat{R}\) for Assessing Convergence of MCMC (with Discussion).” Bayesian Analysis 16 (2): 667–718.

Licenses

  • Code © 2021–2025, Aki Vehtari, licensed under BSD-3.
  • Text © 2021–2025, Aki Vehtari, licensed under CC-BY-NC 4.0.