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 5.5 Lognormal model in Python using Stan
==============================================
import numpy as np
from scipy.stats import uniform, lognorm
import pystan
​
# Data
np.random.seed(1056) # set seed to replicate example
nobs= 5000 # number of obs in model
x1 = uniform.rvs(size=nobs) # random uniform variable
beta0 = 2.0 # intercept
beta1 = 3.0 # linear predictor
sigma = 1.0 # dispersion
xb = beta0 + beta1 * x1 # linear predictor, xb
exb = np.exp(xb)
​
y = lognorm.rvs(sigma, scale=exb, size=nobs) # create y as adjusted
# random normal variate
# Fit
mydata = {}
mydata['N'] = nobs
mydata['x1'] = x1
mydata['y'] = y
stan_lognormal = """
data{
int<lower=0> N;
vector[N] x1;
vector[N] y;
}
parameters{
real beta0;
real beta1;
real<lower=0> sigma;
}
transformed parameters{
vector[N] mu;
for (i in 1:N) mu[i] = beta0 + beta1 * x1[i];
}
model{
y ~ lognormal(mu, sigma);
}
"""
​
# fit
fit = pystan.stan(model_code=stan_lognormal, data=mydata, iter=5000, chains=3,
verbose=False, n_jobs=3)
# Output
nlines = 8 # number of lines in output
output = str(fit).split('\n')
for item in output[:nlines]:
print(item)
==============================================
Output on screen:
​
Inference for Stan model: anon_model_74e214ef8b541b8d71bc91e76ef3dd3d.
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 1.99 5.0e-4 0.03 1.93 1.97 1.99 2.00 2.04 2798.0 1.0
beta1 3.00 8.9e-4 0.05 2.91 2.97 3.00 3.03 3.09 2685.0 1.0
sigma 0.99 1.5e-4 9.4e-3 0.97 0.98 0.99 1.00 1.01 3838.0 1.0