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 6.28 Negative binomial model with three parameters in Python using Stan. Synthetic
data generated with R package MASS

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

import numpy as np
import pystan

import statsmodels.api as sm
from rpy2.robjects import r, FloatVector
from scipy.stats import uniform, binom, nbinom, poisson, gamma

def gen_negbin(N, mu1, theta1):
"""Negative binomial distribution."""

â€‹

r('library(MASS)')

â€‹

# get R functions
nbinomR = r['rnegbin']

â€‹

res = nbinomR(n=N, mu=FloatVector(mu1), theta=FloatVector(theta1))

â€‹

return res

â€‹

â€‹

# Data
nobs= 1500                                                                     # number of obs in model

x1 = uniform.rvs(size=nobs)                                          # categorical explanatory variable

xb = 2 - 5 * x1                                                                # linear predictor
exb = np.exp(xb)

theta = 0.5
Q = 1.4

nbpy = gen_negbin(nobs, exb, theta * (exb ** Q))

X = sm.add_constant(np.transpose(x1))                        # format data for input

mydata = {}                                                                    # build data dictionary
mydata['N'] = nobs                                                         # sample size
mydata['X'] = X                                                             # predictors
mydata['Y'] = nbpy                                                        # response variable
mydata['K'] = X.shape[1]

# Fit
stan_code = """
data{
int N;
int K;
matrix[N,K] X;
int Y[N];
}
parameters{
vector[K] beta;
real<lower=0> theta;
real<lower=0, upper=3> Q;
}
transformed parameters{
vector[N] mu;
real<lower=0> theta_eff[N];

mu = exp(X * beta);
for (i in 1:N) {
theta_eff[i] = theta * pow(mu[i], Q);
}
}
model{

Y ~ neg_binomial_2(mu, theta_eff);
}
"""

# Run mcmc
fit = pystan.stan(model_code=stan_code, data=mydata, iter=5000, chains=3,
warmup=2500, n_jobs=3)

â€‹

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

â€‹

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

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

Output:

â€‹

Inference for Stan model: anon_model_b4d79abfa4772c8f4848d1e352cc63ba.
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
beta[0]           2.09        8.1e-4       0.04         2.0        2.06      2.09        2.12       2.18     3042.0        1.0
beta[1]           -5.1         3.7e-3         0.2      -5.49      -5.23       -5.1      -4.97      -4.71     2853.0        1.0
theta              0.46         8.9e-4       0.05       0.36       0.43       0.46         0.5       0.57     3647.0        1.0
Q                  1.37          1.5e-3       0.09       1.21       1.31       1.36       1.42       1.55     3403.0        1.0

bottom of page