top of page

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 5.11 Inverse Gaussian model in Python using Stan

===============================================================

import numpy as np
import statsmodels.api as sm
import pystan

from scipy.stats import uniform, invgauss

â€‹

# Data
np.random.seed(1056)                                           # set seed to replicate example
nobs= 1000                                                            # number of obs in model
x1 = uniform.rvs(size=nobs)                                 # random uniform variable

â€‹

beta0 = 1.0
beta1 = 0.5
l1 = 20

â€‹

xb = beta0 + beta1 * x1                                        # linear predictor
exb = np.exp(xb)

y = invgauss.rvs(exb/l1, scale=l1)                       # create response variable

# Fit
stan_data = {}                                                     # build data dictionary
stan_data['Y'] = y                                                # response variable
stan_data['x1'] = x1                                             # explanatory variable
stan_data['N'] = nobs                                          # sample size

â€‹

# Stan code
stan_code = """
data{
int<lower=0> N;
vector[N] Y;
vector[N] x1;
}
parameters{
real beta0;
real beta1;
real<lower=0> lambda;
}
transformed parameters{
vector[N] exb;
vector[N] xb;

for (i in 1:N) xb[i] = beta0 + beta1 * x1[i];
for (i in 1:N) exb[i] = exp(xb[i]);
}
model{
real l1;
real l2;
vector[N] loglike;

â€‹

lambda ~ uniform(0.0001, 100);

â€‹

for (i in 1:N){
l1 = 0.5 * (log(lambda) - log(2 * pi() * pow(Y[i], 3)));
l2 = -lambda*pow(Y[i] - exb[i], 2)/(2 * pow(exb[i], 2) * Y[i]);
loglike[i] = l1 + l2;
}

â€‹

target += loglike;
}
"""

â€‹

fit = pystan.stan(model_code=stan_code, data=stan_data, iter=5000, chains=3,
warmup=2500, n_jobs=3)

â€‹

# Output
nlines = 8                                   # number of lines in screen output

â€‹

output = str(fit).split('\n')
for item in output[:nlines]:
print(item)

Output on screen:

â€‹

Inference for Stan model: anon_model_3144222fcb42d14e4d926d825b50c34c.
3 chains, each with iter=5000; warmup=2500; thin=1;
post-warmup draws per chain=2500, total post-warmup draws=7500.

â€‹

mean      se_mean          sd        2.5%         25%         50%         75%       97.5%      n_eff        Rhat
beta0             0.99          4.4e-4       0.03        0.94          0.97          0.99          1.0           1.04    3214.0          1.0
beta1             0.52          8.3e-4       0.05        0.43          0.49          0.52         0.55          0.61    3071.0          1.0
lambda        20.24             0.01       0.83      18.69        19.68        20.23       20.78        21.9      4279.0          1.0

bottom of page