Install
conda install pystan
In [1]:
%matplotlib inline
from matplotlib import pyplot as plt
In [2]:
import pystan
In [3]:
import warnings
warnings.filterwarnings("ignore")
In [4]:
schools_code = """
data {
int<lower=0> J; // number of schools
real y[J]; // estimated treatment effects
real<lower=0> sigma[J]; // s.e. of effect estimates
}
parameters {
real mu;
real<lower=0> tau;
real eta[J];
}
transformed parameters {
real theta[J];
for (j in 1:J)
theta[j] <- mu + tau * eta[j];
}
model {
eta ~ normal(0, 1);
y ~ normal(theta, sigma);
}
"""
In [5]:
schools_dat = {'J': 8,
'y': [28, 8, -3, 7, -1, 1, 18, 12],
'sigma': [15, 10, 16, 11, 9, 11, 10, 18]}
In [6]:
fit = pystan.stan(model_code=schools_code, data=schools_dat,
iter=1000, chains=4)
In [7]:
fit
Out[7]:
In [8]:
la = fit.extract(permuted=True)
la.keys()
Out[8]:
In [9]:
for k,v in la.iteritems():
print k,v.shape
In [10]:
fit.plot()
plt.gcf().set_size_inches(18.5, 10.5);
In [11]:
ocode = """
data {
int<lower=1> N;
real y[N];
}
parameters {
real mu;
}
model {
y ~ normal(mu, 1);
}
"""
sm = pystan.StanModel(model_code=ocode)
In [12]:
y2 = np.random.normal(size=20)
np.mean(y2)
Out[12]:
In [13]:
op = sm.optimizing(data=dict(y=y2, N=len(y2)))
op
Out[13]:
In [ ]: