HSI
From: Bayesian Models for Astrophysical Data, Cambridge Univ. Press
(c) 2017, Joseph M. Hilbe, Rafael S. de Souza and Emille E. O. Ishida
you are kindly asked to include the complete citation if you used this material in a publication
​
​
Code 6.8 Bayesian Poisson model in Python using Stan
=================================================
import numpy as np
import pystan
import statsmodels.api as sm
from scipy.stats import norm, poisson, binom
# Data
np.random.seed(18472) # set seed to replicate example
nobs= 750 # number of obs in model
​
x1_2 = binom.rvs(1, 0.7, size=nobs)
x2 = norm.rvs(loc=0, scale=1.0, size=nobs)
xb = 1 - 1.5 * x1_2 - 3.5 * x2 # linear predictor
exb = np.exp(xb)
py = poisson.rvs(exb) # create y as adjusted
X = sm.add_constant(np.column_stack((x1_2, x2)))
​
mydata = {} # build data dictionary
mydata['N'] = nobs # sample size
mydata['X'] = X # predictors
mydata['Y'] = py # response variable
mydata['K'] = mydata['X'].shape[1] # number of coefficients
# Fit
stan_code = """
data{
int N;
int K;
matrix[N,K] X;
int Y[N];
}
parameters{
vector[K] beta;
}
model{
Y ~ poisson_log(X * beta);
}
"""
# Run mcmc
fit = pystan.stan(model_code=stan_code, data=mydata, iter=5000, chains=3,
warmup=4000, n_jobs=3)
​
# Output
print(fit)
=================================================
Output on screen:
​
Inference for Stan model: anon_model_5e42b5816937937e2fd26f80455a697e.
3 chains, each with iter=5000; warmup=4000; thin=1;
post-warmup draws per chain=1000, total post-warmup draws=3000.
​
mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat
beta[0] 1.0 3.7e-4 0.01 0.98 0.99 1.0 1.01 1.02 944.0 1.0
beta[1] - 1.5 1.9e-4 5.9e-3 -1.51 -1.5 -1.5 -1.5 -1.49 1005.0 1.0
beta[2] -3.5 1.3e-4 4.1e-3 -3.51 -3.5 -3.5 -3.5 -3.49 955.0 1.0
lp__ 2.3e6 0.04 1.14 2.3e6 2.3e6 2.3e6 2.3e6 2.3e6 994.0 1.0
​
Samples were drawn using NUTS at Sat Dec 24 11:04:16 2016.
For each parameter, n_eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor on split chains (at
convergence, Rhat=1).